json.hpp 146.6 KB
Newer Older
N
Niels 已提交
1 2 3 4 5 6 7 8 9
/*!
@file
@copyright The code is licensed under the MIT License
           <http://opensource.org/licenses/MIT>,
           Copyright (c) 2013-2015 Niels Lohmann.
@author Niels Lohmann <http://nlohmann.me>
@see https://github.com/nlohmann/json
*/

N
Niels 已提交
10 11
#ifndef NLOHMANN_JSON_HPP
#define NLOHMANN_JSON_HPP
N
Niels 已提交
12 13

#include <algorithm>
14
#include <array>
N
Niels 已提交
15
#include <ciso646>
N
Niels 已提交
16
#include <cmath>
N
Niels 已提交
17
#include <cstdio>
N
Niels 已提交
18 19
#include <functional>
#include <initializer_list>
N
Niels 已提交
20
#include <iomanip>
N
Niels 已提交
21 22 23 24 25
#include <iostream>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
N
Niels 已提交
26
#include <sstream>
N
Niels 已提交
27 28 29 30 31
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

N
Niels 已提交
32 33 34 35 36 37 38
// enable ssize_t on MinGW
#ifdef __GNUC__
    #ifdef __MINGW32__
        #include <sys/types.h>
    #endif
#endif

N
Niels 已提交
39
/*!
N
Niels 已提交
40
@brief namespace for Niels Lohmann
N
Niels 已提交
41 42 43 44 45
@see https://github.com/nlohmann
*/
namespace nlohmann
{

N
Niels 已提交
46 47 48 49

// Helper to determine whether there's a key_type for T.
// http://stackoverflow.com/a/7728728/266378
template<typename T>
N
Niels 已提交
50
struct has_mapped_type
N
Niels 已提交
51 52
{
  private:
N
Niels 已提交
53
    template<typename C> static char test(typename C::mapped_type*);
N
Niels 已提交
54 55 56 57 58
    template<typename C> static int  test(...);
  public:
    enum { value = sizeof(test<T>(0)) == sizeof(char) };
};

N
Niels 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71
/*!
@brief JSON

@tparam ObjectType         type for JSON objects
                           (@c std::map by default)
@tparam ArrayType          type for JSON arrays
                           (@c std::vector by default)
@tparam StringType         type for JSON strings and object keys
                           (@c std::string by default)
@tparam BooleanType        type for JSON booleans
                           (@c bool by default)
@tparam NumberIntegerType  type for JSON integer numbers
                           (@c int64_t by default)
N
Niels 已提交
72
@tparam NumberFloatType    type for JSON floating-point numbers
N
Niels 已提交
73
                           (@c double by default)
N
Niels 已提交
74
@tparam AllocatorType      type of the allocator to use
N
Niels 已提交
75
                           (@c std::allocator by default)
N
Niels 已提交
76

N
Niels 已提交
77 78
@note ObjectType trick from http://stackoverflow.com/a/9860911

N
Niels 已提交
79 80
@see RFC 7159 <http://rfc7159.net/rfc7159>
@see ECMA 404 <http://www.ecma-international.org/publications/standards/Ecma-404.htm>
N
Niels 已提交
81 82 83 84 85 86 87
*/
template <
    template<typename U, typename V, typename... Args> class ObjectType = std::map,
    template<typename U, typename... Args> class ArrayType = std::vector,
    class StringType = std::string,
    class BooleanType = bool,
    class NumberIntegerType = int64_t,
N
Niels 已提交
88
    class NumberFloatType = double,
N
Niels 已提交
89
    template<typename U> class AllocatorType = std::allocator
N
Niels 已提交
90 91 92 93 94 95 96 97
    >
class basic_json
{
  public:
    /////////////////////
    // container types //
    /////////////////////

N
Niels 已提交
98
    /// the type of elements in a basic_json container
N
Niels 已提交
99
    using value_type = basic_json;
N
Niels 已提交
100

N
Niels 已提交
101
    /// the type of an element reference
N
Niels 已提交
102
    using reference = value_type&;
N
Niels 已提交
103

N
Niels 已提交
104
    /// the type of an element const reference
N
Niels 已提交
105
    using const_reference = const value_type&;
N
Niels 已提交
106

N
Niels 已提交
107
    /// a type to represent differences between iterators
N
Niels 已提交
108 109
    using difference_type = std::ptrdiff_t;

N
Niels 已提交
110
    /// a type to represent container sizes
N
Niels 已提交
111 112 113
    using size_type = std::size_t;

    /// the allocator type
N
Niels 已提交
114
    using allocator_type = AllocatorType<basic_json>;
N
Niels 已提交
115

N
Niels 已提交
116
    /// the type of an element pointer
N
Niels 已提交
117
    using pointer = typename std::allocator_traits<allocator_type>::pointer;
N
Niels 已提交
118
    /// the type of an element const pointer
N
Niels 已提交
119
    using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
N
Niels 已提交
120

N
Niels 已提交
121 122 123 124 125 126 127 128
    /// an iterator for a basic_json container
    class iterator;
    /// a const iterator for a basic_json container
    class const_iterator;
    /// a reverse iterator for a basic_json container
    class reverse_iterator;
    /// a const reverse iterator for a basic_json container
    class const_reverse_iterator;
N
Niels 已提交
129

N
Niels 已提交
130
    /// returns the allocator associated with the container
N
Niels 已提交
131
    static allocator_type get_allocator()
N
Niels 已提交
132 133 134 135 136
    {
        return allocator_type();
    }


N
Niels 已提交
137 138 139 140 141
    ///////////////////////////
    // JSON value data types //
    ///////////////////////////

    /// a type for an object
N
Niels 已提交
142 143
    using object_t =
        ObjectType<StringType, basic_json, std::less<StringType>, AllocatorType<std::pair<const StringType, basic_json>>>;
N
Niels 已提交
144
    /// a type for an array
N
Niels 已提交
145
    using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
N
Niels 已提交
146 147 148 149 150 151
    /// a type for a string
    using string_t = StringType;
    /// a type for a boolean
    using boolean_t = BooleanType;
    /// a type for a number (integer)
    using number_integer_t = NumberIntegerType;
N
Niels 已提交
152
    /// a type for a number (floating-point)
N
Niels 已提交
153 154 155 156 157
    using number_float_t = NumberFloatType;
    /// a type for list initialization
    using list_init_t = std::initializer_list<basic_json>;


N
Niels 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    /////////////////////////////////
    // JSON value type enumeration //
    /////////////////////////////////

    /// JSON value type enumeration
    enum class value_t : uint8_t
    {
        null,           ///< null value
        object,         ///< object (unordered set of name/value pairs)
        array,          ///< array (ordered collection of values)
        string,         ///< string value
        boolean,        ///< boolean value
        number_integer, ///< number value (integer)
        number_float,   ///< number value (floating-point)
        discarded       ///< (internal) indicates the parser callback chose not to keep the value
    };

N
Niels 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187
    ////////////////////////
    // JSON value storage //
    ////////////////////////

    /// a JSON value
    union json_value
    {
        /// object (stored with pointer to save storage)
        object_t* object;
        /// array (stored with pointer to save storage)
        array_t* array;
        /// string (stored with pointer to save storage)
        string_t* string;
N
Niels 已提交
188
        /// boolean
N
Niels 已提交
189 190 191
        boolean_t boolean;
        /// number (integer)
        number_integer_t number_integer;
N
Niels 已提交
192
        /// number (floating-point)
N
Niels 已提交
193 194 195
        number_float_t number_float;

        /// default constructor (for null values)
N
Niels 已提交
196
        json_value() noexcept = default;
N
Niels 已提交
197
        /// constructor for booleans
N
Niels 已提交
198
        json_value(boolean_t v) noexcept : boolean(v) {}
N
Niels 已提交
199
        /// constructor for numbers (integer)
N
Niels 已提交
200
        json_value(number_integer_t v) noexcept : number_integer(v) {}
N
Niels 已提交
201
        /// constructor for numbers (floating-point)
N
Niels 已提交
202
        json_value(number_float_t v) noexcept : number_float(v) {}
N
Niels 已提交
203
        /// constructor for empty values of a given type
N
Niels 已提交
204
        json_value(value_t t)
N
Niels 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        {
            switch (t)
            {
                case (value_t::null):
                case (value_t::discarded):
                {
                    break;
                }

                case (value_t::object):
                {
                    AllocatorType<object_t> alloc;
                    object = alloc.allocate(1);
                    alloc.construct(object);
                    break;
                }
N
Niels 已提交
221

N
Niels 已提交
222 223 224 225 226 227 228
                case (value_t::array):
                {
                    AllocatorType<array_t> alloc;
                    array = alloc.allocate(1);
                    alloc.construct(array);
                    break;
                }
N
Niels 已提交
229

N
Niels 已提交
230 231 232 233 234 235 236
                case (value_t::string):
                {
                    AllocatorType<string_t> alloc;
                    string = alloc.allocate(1);
                    alloc.construct(string, "");
                    break;
                }
N
Niels 已提交
237

N
Niels 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
                case (value_t::boolean):
                {
                    boolean = boolean_t(false);
                    break;
                }

                case (value_t::number_integer):
                {
                    number_integer = number_integer_t(0);
                    break;
                }

                case (value_t::number_float):
                {
                    number_float = number_float_t(0.0);
                    break;
                }
            }
        }
N
Niels 已提交
257 258

        /// constructor for strings
N
Niels 已提交
259
        json_value(const string_t& value)
N
Niels 已提交
260 261 262 263 264 265 266
        {
            AllocatorType<string_t> alloc;
            string = alloc.allocate(1);
            alloc.construct(string, value);
        }

        /// constructor for objects
N
Niels 已提交
267
        json_value(const object_t& value)
N
Niels 已提交
268 269 270 271 272 273 274
        {
            AllocatorType<object_t> alloc;
            object = alloc.allocate(1);
            alloc.construct(object, value);
        }

        /// constructor for arrays
N
Niels 已提交
275
        json_value(const array_t& value)
N
Niels 已提交
276 277 278 279 280
        {
            AllocatorType<array_t> alloc;
            array = alloc.allocate(1);
            alloc.construct(array, value);
        }
N
Niels 已提交
281 282
    };

N
Niels 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
    //////////////////////////
    // JSON parser callback //
    //////////////////////////

    /// JSON callback event enumeration
    enum class parse_event_t : uint8_t
    {
        object_start,  ///< start an object scope (found a '{' token)
        object_end,    ///< end of an object scope (found '}' token)
        array_start,   ///< start of an array scope (found '[' token)
        array_end,     ///< end of an array scope (found ']' token)
        key,           ///< found an object key within an object scope
        value          ///< a value in an appropriate context (i.e., following a tag in an object scope)
    };

    /// per-element parser callback type
    using parser_callback_t = std::function<bool(int depth, parse_event_t event,
                              const basic_json& parsed)>;

N
Niels 已提交
302 303 304 305 306 307 308 309 310
    /*!
    @brief comparison operator for JSON value types

    Returns an ordering that is similar to Python:
    - order: null < boolean < number < object < array < string
    - furthermore, each type is not smaller than itself
    */
    friend bool operator<(const value_t lhs, const value_t rhs)
    {
N
Niels 已提交
311
        static constexpr std::array<uint8_t, 7> order = {{
312 313 314 315 316 317 318
                0, // null
                3, // object
                4, // array
                5, // string
                1, // boolean
                2, // integer
                2  // float
N
Niels 已提交
319
            }
320
        };
N
Niels 已提交
321 322 323 324 325 326 327

        // discarded values are not comparable
        if (lhs == value_t::discarded or rhs == value_t::discarded)
        {
            return false;
        }

328
        return order[static_cast<std::size_t>(lhs)] < order[static_cast<std::size_t>(rhs)];
N
Niels 已提交
329 330
    }

N
Niels 已提交
331 332 333 334 335

    //////////////////
    // constructors //
    //////////////////

N
Niels 已提交
336 337 338 339 340 341
    /*!
    @brief create an empty value with a given type
    @param value  the type to create an value of

    @exception std::bad_alloc  if allocation for object, array, or string fails.
    */
N
Niels 已提交
342
    basic_json(const value_t value)
N
Niels 已提交
343 344
        : m_type(value), m_value(value)
    {}
N
Niels 已提交
345

N
Niels 已提交
346 347 348 349
    /*!
    @brief create a null object (implicitly)
    @ingroup container
    */
N
Niels 已提交
350
    basic_json() noexcept = default;
N
Niels 已提交
351 352

    /// create a null object (explicitly)
N
Niels 已提交
353
    basic_json(std::nullptr_t) noexcept
N
Niels 已提交
354
        : basic_json(value_t::null)
N
Niels 已提交
355 356 357
    {}

    /// create an object (explicit)
N
Niels 已提交
358
    basic_json(const object_t& value)
N
Niels 已提交
359 360
        : m_type(value_t::object), m_value(value)
    {}
N
Niels 已提交
361 362 363 364

    /// create an object (implicit)
    template <class V, typename
              std::enable_if<
N
Niels 已提交
365
                  std::is_constructible<typename object_t::key_type, typename V::key_type>::value and
N
Niels 已提交
366 367
                  std::is_constructible<basic_json, typename V::mapped_type>::value, int>::type
              = 0>
N
Niels 已提交
368
    basic_json(const V& value)
N
Niels 已提交
369 370
        : m_type(value_t::object)
    {
N
Niels 已提交
371
        AllocatorType<object_t> alloc;
N
Niels 已提交
372
        m_value.object = alloc.allocate(1);
373 374 375
        using std::begin;
        using std::end;
        alloc.construct(m_value.object, begin(value), end(value));
N
Niels 已提交
376
    }
N
Niels 已提交
377 378

    /// create an array (explicit)
N
Niels 已提交
379
    basic_json(const array_t& value)
N
Niels 已提交
380 381
        : m_type(value_t::array), m_value(value)
    {}
N
Niels 已提交
382 383 384 385

    /// create an array (implicit)
    template <class V, typename
              std::enable_if<
N
Niels 已提交
386 387 388 389
                  not std::is_same<V, typename basic_json::iterator>::value and
                  not std::is_same<V, typename basic_json::const_iterator>::value and
                  not std::is_same<V, typename basic_json::reverse_iterator>::value and
                  not std::is_same<V, typename basic_json::const_reverse_iterator>::value and
N
Niels 已提交
390 391
                  not std::is_same<V, typename array_t::iterator>::value and
                  not std::is_same<V, typename array_t::const_iterator>::value and
N
Niels 已提交
392 393
                  std::is_constructible<basic_json, typename V::value_type>::value, int>::type
              = 0>
N
Niels 已提交
394
    basic_json(const V& value)
N
Niels 已提交
395 396
        : m_type(value_t::array)
    {
N
Niels 已提交
397
        AllocatorType<array_t> alloc;
N
Niels 已提交
398
        m_value.array = alloc.allocate(1);
399 400 401
        using std::begin;
        using std::end;
        alloc.construct(m_value.array, begin(value), end(value));
N
Niels 已提交
402
    }
N
Niels 已提交
403 404

    /// create a string (explicit)
N
Niels 已提交
405
    basic_json(const string_t& value)
N
Niels 已提交
406 407
        : m_type(value_t::string), m_value(value)
    {}
N
Niels 已提交
408 409

    /// create a string (explicit)
N
Niels 已提交
410
    basic_json(const typename string_t::value_type* value)
N
Niels 已提交
411 412
        : basic_json(string_t(value))
    {}
N
Niels 已提交
413 414 415 416 417 418

    /// create a string (implicit)
    template <class V, typename
              std::enable_if<
                  std::is_constructible<string_t, V>::value, int>::type
              = 0>
N
Niels 已提交
419
    basic_json(const V& value)
N
Niels 已提交
420 421 422 423
        : basic_json(string_t(value))
    {}

    /// create a boolean (explicit)
N
Niels 已提交
424
    basic_json(boolean_t value)
N
Niels 已提交
425 426 427
        : m_type(value_t::boolean), m_value(value)
    {}

N
Niels 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
    /*!
    @brief create an integer number (explicit)

    @tparam T  helper type to compare number_integer_t and int
    @param value  an integer to create a JSON number from

    This constructor takes care about explicitly passed values of type
    number_integer_t. However, this constructor would have the same signature
    as the existing one for const int values, so we need to switch this one off
    in case number_integer_t is the same as int.
    */
    template<typename T,
             typename std::enable_if<
                 not (std::is_same<T, int>::value)
                 and std::is_same<T, number_integer_t>::value
                 , int>::type = 0>
    basic_json(const number_integer_t value)
N
Niels 已提交
445 446
        : m_type(value_t::number_integer), m_value(value)
    {}
N
Niels 已提交
447

N
Niels 已提交
448 449 450 451 452 453 454 455 456 457 458 459 460 461
    /*!
    @brief create an int number to support enum type (implicit)

    @param value  an integer to create a JSON number from

    This constructor allows to pass enums directly to a constructor. As C++ has
    no way of specifying the type of an anonymous enum explicitly, we can only
    rely on the fact that such values implicitly convert to int. As int may
    already be the same type of number_integer_t, we may need to switch off
    that constructor, which is done above.
    */
    basic_json(const int value)
        : m_type(value_t::number_integer),
          m_value(static_cast<number_integer_t>(value))
易思龙 已提交
462
    {}
N
Niels 已提交
463 464 465 466 467 468 469

    /// create an integer number (implicit)
    template<typename T, typename
             std::enable_if<
                 std::is_constructible<number_integer_t, T>::value and
                 std::numeric_limits<T>::is_integer, T>::type
             = 0>
N
Niels 已提交
470
    basic_json(const T value) noexcept
N
Niels 已提交
471 472
        : m_type(value_t::number_integer),
          m_value(static_cast<number_integer_t>(value))
N
Niels 已提交
473 474
    {}

N
Niels 已提交
475
    /// create a floating-point number (explicit)
N
Niels 已提交
476
    basic_json(const number_float_t value)
N
Niels 已提交
477
        : m_type(value_t::number_float), m_value(value)
N
Niels 已提交
478 479 480 481 482 483 484 485
    {
        // replace infinity and NAN by null
        if (not std::isfinite(value))
        {
            m_type = value_t::null;
            m_value = json_value();
        }
    }
N
Niels 已提交
486

N
Niels 已提交
487
    /// create a floating-point number (implicit)
N
Niels 已提交
488 489 490 491 492
    template<typename T, typename = typename
             std::enable_if<
                 std::is_constructible<number_float_t, T>::value and
                 std::is_floating_point<T>::value>::type
             >
N
Niels 已提交
493
    basic_json(const T value) noexcept
N
Niels 已提交
494 495
        : basic_json(number_float_t(value))
    {}
N
Niels 已提交
496

N
Niels 已提交
497
    /// create a container (array or object) from an initializer list
N
Niels 已提交
498 499
    basic_json(list_init_t init, bool type_deduction = true,
               value_t manual_type = value_t::array)
N
Niels 已提交
500 501 502 503
    {
        // the initializer list could describe an object
        bool is_object = true;

N
Niels 已提交
504 505
        // check if each element is an array with two elements whose first element
        // is a string
N
Niels 已提交
506
        for (const auto& element : init)
N
Niels 已提交
507
        {
N
Niels 已提交
508 509
            if (element.m_type != value_t::array or element.size() != 2
                    or element[0].m_type != value_t::string)
N
Niels 已提交
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
            {
                // we found an element that makes it impossible to use the
                // initializer list as object
                is_object = false;
                break;
            }
        }

        // adjust type if type deduction is not wanted
        if (not type_deduction)
        {
            // if array is wanted, do not create an object though possible
            if (manual_type == value_t::array)
            {
                is_object = false;
            }

            // if object is wanted but impossible, throw an exception
            if (manual_type == value_t::object and not is_object)
            {
N
Niels 已提交
530
                throw std::domain_error("cannot create JSON object from initializer list");
N
Niels 已提交
531 532 533 534 535 536 537
            }
        }

        if (is_object)
        {
            // the initializer list is a list of pairs -> create object
            m_type = value_t::object;
N
Niels 已提交
538
            m_value = value_t::object;
N
Niels 已提交
539

N
Niels 已提交
540
            for (auto& element : init)
N
Niels 已提交
541 542 543 544 545 546 547 548
            {
                m_value.object->emplace(std::move(*(element[0].m_value.string)), std::move(element[1]));
            }
        }
        else
        {
            // the initializer list describes an array -> create array
            m_type = value_t::array;
N
Niels 已提交
549
            AllocatorType<array_t> alloc;
N
Niels 已提交
550
            m_value.array = alloc.allocate(1);
N
Niels 已提交
551
            alloc.construct(m_value.array, std::move(init));
N
Niels 已提交
552 553 554
        }
    }

N
Niels 已提交
555
    /// explicitly create an array from an initializer list
N
Niels 已提交
556
    static basic_json array(list_init_t init = list_init_t())
N
Niels 已提交
557
    {
N
Niels 已提交
558
        return basic_json(init, false, value_t::array);
N
Niels 已提交
559 560
    }

N
Niels 已提交
561
    /// explicitly create an object from an initializer list
N
Niels 已提交
562
    static basic_json object(list_init_t init = list_init_t())
N
Niels 已提交
563
    {
N
Niels 已提交
564
        return basic_json(init, false, value_t::object);
N
Niels 已提交
565 566
    }

N
Niels 已提交
567
    /// construct an array with count copies of given value
N
Niels 已提交
568
    basic_json(size_type count, const basic_json& other)
N
Niels 已提交
569 570 571 572 573 574
        : m_type(value_t::array)
    {
        AllocatorType<array_t> alloc;
        m_value.array = alloc.allocate(1);
        alloc.construct(m_value.array, count, other);
    }
N
Niels 已提交
575

N
Niels 已提交
576
    /// construct a JSON container given an iterator range
N
Niels 已提交
577 578
    template <class T, typename
              std::enable_if<
N
Niels 已提交
579 580
                  std::is_same<T, typename basic_json::iterator>::value or
                  std::is_same<T, typename basic_json::const_iterator>::value
N
Niels 已提交
581 582
                  , int>::type
              = 0>
N
Niels 已提交
583
    basic_json(T first, T last)
N
Niels 已提交
584 585 586 587 588
    {
        // make sure iterator fits the current value
        if (first.m_object != last.m_object or
                first.m_object->m_type != last.m_object->m_type)
        {
N
Niels 已提交
589
            throw std::domain_error("iterators are not compatible");
N
Niels 已提交
590 591
        }

N
Niels 已提交
592
        // set the type
N
Niels 已提交
593 594
        m_type = first.m_object->m_type;

N
Niels 已提交
595
        // check if iterator range is complete for non-compound values
N
Niels 已提交
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
        switch (m_type)
        {
            case value_t::number_integer:
            case value_t::number_float:
            case value_t::boolean:
            case value_t::string:
            {
                if (first.m_it.generic_iterator != 0 or last.m_it.generic_iterator != 1)
                {
                    throw std::out_of_range("iterators out of range");
                }
                break;
            }

            default:
            {
                break;
            }
        }

        switch (m_type)
        {
            case value_t::number_integer:
            {
                m_value.number_integer = first.m_object->m_value.number_integer;
                break;
            }

            case value_t::number_float:
            {
                m_value.number_float = first.m_object->m_value.number_float;
                break;
            }

            case value_t::boolean:
            {
                m_value.boolean = first.m_object->m_value.boolean;
                break;
            }

            case value_t::string:
            {
N
Niels 已提交
638
                m_value = *first.m_object->m_value.string;
N
Niels 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
                break;
            }

            case value_t::object:
            {
                AllocatorType<object_t> alloc;
                m_value.object = alloc.allocate(1);
                alloc.construct(m_value.object, first.m_it.object_iterator, last.m_it.object_iterator);
                break;
            }

            case value_t::array:
            {
                AllocatorType<array_t> alloc;
                m_value.array = alloc.allocate(1);
                alloc.construct(m_value.array, first.m_it.array_iterator, last.m_it.array_iterator);
                break;
            }

            default:
            {
N
Niels 已提交
660
                throw std::domain_error("cannot use construct with iterators from " + first.m_object->type_name());
N
Niels 已提交
661 662 663 664
            }
        }
    }

N
Niels 已提交
665 666 667 668
    ///////////////////////////////////////
    // other constructors and destructor //
    ///////////////////////////////////////

N
Niels 已提交
669 670
    /*!
    @brief copy constructor
N
Niels 已提交
671 672 673

    @exception std::bad_alloc  if allocation for object, array, or string fails.

N
Niels 已提交
674 675
    @ingroup container
    */
N
Niels 已提交
676
    basic_json(const basic_json& other)
N
Niels 已提交
677 678 679 680 681
        : m_type(other.m_type)
    {
        switch (m_type)
        {
            case (value_t::null):
N
Niels 已提交
682
            case (value_t::discarded):
N
Niels 已提交
683 684 685
            {
                break;
            }
N
Niels 已提交
686

N
Niels 已提交
687 688
            case (value_t::object):
            {
N
Niels 已提交
689
                m_value = *other.m_value.object;
N
Niels 已提交
690 691
                break;
            }
N
Niels 已提交
692

N
Niels 已提交
693 694
            case (value_t::array):
            {
N
Niels 已提交
695
                m_value = *other.m_value.array;
N
Niels 已提交
696 697
                break;
            }
N
Niels 已提交
698

N
Niels 已提交
699 700
            case (value_t::string):
            {
N
Niels 已提交
701
                m_value = *other.m_value.string;
N
Niels 已提交
702 703
                break;
            }
N
Niels 已提交
704

N
Niels 已提交
705 706
            case (value_t::boolean):
            {
N
Niels 已提交
707
                m_value = other.m_value.boolean;
N
Niels 已提交
708 709
                break;
            }
N
Niels 已提交
710

N
Niels 已提交
711 712
            case (value_t::number_integer):
            {
N
Niels 已提交
713
                m_value = other.m_value.number_integer;
N
Niels 已提交
714 715
                break;
            }
N
Niels 已提交
716

N
Niels 已提交
717 718
            case (value_t::number_float):
            {
N
Niels 已提交
719
                m_value = other.m_value.number_float;
N
Niels 已提交
720 721 722 723 724 725
                break;
            }
        }
    }

    /// move constructor
N
Niels 已提交
726
    basic_json(basic_json&& other) noexcept
N
Niels 已提交
727 728 729
        : m_type(std::move(other.m_type)),
          m_value(std::move(other.m_value))
    {
N
Niels 已提交
730
        // invalidate payload
N
Niels 已提交
731 732 733 734
        other.m_type = value_t::null;
        other.m_value = {};
    }

N
Niels 已提交
735 736 737 738
    /*!
    @brief copy assignment
    @ingroup container
    */
N
Niels 已提交
739
    reference& operator=(basic_json other) noexcept (
N
Niels 已提交
740 741 742 743 744
        std::is_nothrow_move_constructible<value_t>::value and
        std::is_nothrow_move_assignable<value_t>::value and
        std::is_nothrow_move_constructible<json_value>::value and
        std::is_nothrow_move_assignable<json_value>::value
    )
N
Niels 已提交
745
    {
N
Niels 已提交
746
        using std::swap;
N
Niels 已提交
747 748 749 750 751
        std::swap(m_type, other.m_type);
        std::swap(m_value, other.m_value);
        return *this;
    }

N
Niels 已提交
752 753 754 755
    /*!
    @brief destructor
    @ingroup container
    */
N
Niels 已提交
756
    ~basic_json() noexcept
N
Niels 已提交
757 758 759 760 761
    {
        switch (m_type)
        {
            case (value_t::object):
            {
N
Niels 已提交
762
                AllocatorType<object_t> alloc;
N
Niels 已提交
763 764
                alloc.destroy(m_value.object);
                alloc.deallocate(m_value.object, 1);
N
Niels 已提交
765 766 767
                m_value.object = nullptr;
                break;
            }
N
Niels 已提交
768

N
Niels 已提交
769 770
            case (value_t::array):
            {
N
Niels 已提交
771
                AllocatorType<array_t> alloc;
N
Niels 已提交
772 773
                alloc.destroy(m_value.array);
                alloc.deallocate(m_value.array, 1);
N
Niels 已提交
774 775 776
                m_value.array = nullptr;
                break;
            }
N
Niels 已提交
777

N
Niels 已提交
778 779
            case (value_t::string):
            {
N
Niels 已提交
780
                AllocatorType<string_t> alloc;
N
Niels 已提交
781
                alloc.destroy(m_value.string);
N
Niels 已提交
782
                alloc.deallocate(m_value.string, 1);
N
Niels 已提交
783 784 785
                m_value.string = nullptr;
                break;
            }
N
Niels 已提交
786 787

            default:
N
Niels 已提交
788
            {
N
Niels 已提交
789
                // all other types need no specific destructor
N
Niels 已提交
790 791 792 793 794 795 796 797 798 799 800 801
                break;
            }
        }
    }


  public:
    ///////////////////////
    // object inspection //
    ///////////////////////

    /*!
N
Niels 已提交
802 803
    @brief serialization

N
Niels 已提交
804 805 806
    Serialization function for JSON objects. The function tries to mimick
    Python's @p json.dumps() function, and currently supports its @p indent
    parameter.
N
Niels 已提交
807

N
Niels 已提交
808
    @param indent  if indent is nonnegative, then array elements and object
N
Niels 已提交
809 810 811
    members will be pretty-printed with that indent level. An indent level of 0
    will only insert newlines. -1 (the default) selects the most compact
    representation
N
Niels 已提交
812 813 814

    @see https://docs.python.org/2/library/json.html#json.dump
    */
N
Niels 已提交
815
    string_t dump(const int indent = -1) const noexcept
N
Niels 已提交
816
    {
N
Niels 已提交
817 818
        std::stringstream ss;

N
Niels 已提交
819 820
        if (indent >= 0)
        {
N
Niels 已提交
821
            dump(ss, true, static_cast<unsigned int>(indent));
N
Niels 已提交
822 823 824
        }
        else
        {
N
Niels 已提交
825
            dump(ss, false, 0);
N
Niels 已提交
826
        }
N
Niels 已提交
827 828

        return ss.str();
N
Niels 已提交
829 830
    }

N
Niels 已提交
831
    /// return the type of the object (explicit)
N
Niels 已提交
832
    value_t type() const noexcept
N
Niels 已提交
833 834 835 836
    {
        return m_type;
    }

N
Niels 已提交
837
    // return whether value is null
N
Niels 已提交
838
    bool is_null() const noexcept
N
Niels 已提交
839 840 841 842 843
    {
        return m_type == value_t::null;
    }

    // return whether value is boolean
N
Niels 已提交
844
    bool is_boolean() const noexcept
N
Niels 已提交
845 846 847 848 849
    {
        return m_type == value_t::boolean;
    }

    // return whether value is number
N
Niels 已提交
850
    bool is_number() const noexcept
N
Niels 已提交
851 852 853 854
    {
        return (m_type == value_t::number_integer) or (m_type == value_t::number_float);
    }

N
Niels 已提交
855 856 857 858 859 860 861 862 863 864 865 866
    // return whether value an integer is number
    bool is_number_integer() const noexcept
    {
        return m_type == value_t::number_integer;
    }

    // return whether value is a floating-point number
    bool is_number_float() const noexcept
    {
        return m_type == value_t::number_float;
    }

N
Niels 已提交
867
    // return whether value is object
N
Niels 已提交
868
    bool is_object() const noexcept
N
Niels 已提交
869 870 871 872 873
    {
        return m_type == value_t::object;
    }

    // return whether value is array
N
Niels 已提交
874
    bool is_array() const noexcept
N
Niels 已提交
875 876 877 878 879
    {
        return m_type == value_t::array;
    }

    // return whether value is string
N
Niels 已提交
880
    bool is_string() const noexcept
N
Niels 已提交
881 882 883 884
    {
        return m_type == value_t::string;
    }

N
Niels 已提交
885
    // return whether value is discarded
N
Niels 已提交
886
    bool is_discarded() const noexcept
N
Niels 已提交
887 888 889 890
    {
        return m_type == value_t::discarded;
    }

N
Niels 已提交
891
    /// return the type of the object (implicit)
N
Niels 已提交
892
    operator value_t() const noexcept
N
Niels 已提交
893 894 895 896
    {
        return m_type;
    }

N
Niels 已提交
897
  private:
N
Niels 已提交
898 899 900 901
    //////////////////////
    // value conversion //
    //////////////////////

N
Niels 已提交
902
    /// get an object (explicit)
N
Niels 已提交
903 904
    template <class T, typename
              std::enable_if<
N
Niels 已提交
905 906 907
                  std::is_convertible<typename object_t::key_type, typename T::key_type>::value and
                  std::is_convertible<basic_json, typename T::mapped_type>::value
                  , int>::type = 0>
N
Niels 已提交
908
    T get_impl(T*) const
N
Niels 已提交
909 910 911 912
    {
        switch (m_type)
        {
            case (value_t::object):
N
Niels 已提交
913
            {
N
Niels 已提交
914
                return T(m_value.object->begin(), m_value.object->end());
N
Niels 已提交
915
            }
N
Niels 已提交
916
            default:
N
Niels 已提交
917
            {
N
Niels 已提交
918
                throw std::domain_error("cannot cast " + type_name() + " to " + typeid(T).name());
N
Niels 已提交
919 920 921 922 923
            }
        }
    }

    /// get an object (explicit)
N
Niels 已提交
924
    object_t get_impl(object_t*) const
N
Niels 已提交
925 926 927 928 929 930 931 932 933
    {
        switch (m_type)
        {
            case (value_t::object):
            {
                return *(m_value.object);
            }
            default:
            {
N
Niels 已提交
934
                throw std::domain_error("cannot cast " + type_name() + " to object");
N
Niels 已提交
935
            }
N
Niels 已提交
936 937 938
        }
    }

N
Niels 已提交
939
    /// get an array (explicit)
N
Niels 已提交
940 941
    template <class T, typename
              std::enable_if<
N
Niels 已提交
942 943 944 945 946 947
                  std::is_convertible<basic_json, typename T::value_type>::value and
                  not std::is_same<basic_json, typename T::value_type>::value and
                  not std::is_arithmetic<T>::value and
                  not std::is_convertible<std::string, T>::value and
                  not has_mapped_type<T>::value
                  , int>::type = 0>
N
Niels 已提交
948
    T get_impl(T*) const
N
Niels 已提交
949 950 951 952
    {
        switch (m_type)
        {
            case (value_t::array):
N
Niels 已提交
953 954 955 956 957 958 959 960 961
            {
                T to_vector;
                std::transform(m_value.array->begin(), m_value.array->end(),
                               std::inserter(to_vector, to_vector.end()), [](basic_json i)
                {
                    return i.get<typename T::value_type>();
                });
                return to_vector;
            }
N
Niels 已提交
962
            default:
N
Niels 已提交
963
            {
N
Niels 已提交
964
                throw std::domain_error("cannot cast " + type_name() + " to " + typeid(T).name());
N
Niels 已提交
965
            }
N
Niels 已提交
966 967 968
        }
    }

N
Niels 已提交
969 970
    /// get an array (explicit)
    template <class T, typename
N
Niels 已提交
971
              std::enable_if<
N
Niels 已提交
972 973 974
                  std::is_convertible<basic_json, T>::value and
                  not std::is_same<basic_json, T>::value
                  , int>::type = 0>
N
Niels 已提交
975
    std::vector<T> get_impl(std::vector<T>*) const
N
Niels 已提交
976 977 978
    {
        switch (m_type)
        {
N
Niels 已提交
979 980 981 982 983 984 985 986 987 988 989
            case (value_t::array):
            {
                std::vector<T> to_vector;
                to_vector.reserve(m_value.array->size());
                std::transform(m_value.array->begin(), m_value.array->end(),
                               std::inserter(to_vector, to_vector.end()), [](basic_json i)
                {
                    return i.get<T>();
                });
                return to_vector;
            }
N
Niels 已提交
990
            default:
N
Niels 已提交
991
            {
N
Niels 已提交
992
                throw std::domain_error("cannot cast " + type_name() + " to " + typeid(T).name());
N
Niels 已提交
993
            }
N
Niels 已提交
994 995 996
        }
    }

N
Niels 已提交
997 998 999 1000 1001 1002
    /// get an array (explicit)
    template <class T, typename
              std::enable_if<
                  std::is_same<basic_json, typename T::value_type>::value and
                  not has_mapped_type<T>::value
                  , int>::type = 0>
N
Niels 已提交
1003
    T get_impl(T*) const
N
Niels 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012
    {
        switch (m_type)
        {
            case (value_t::array):
            {
                return T(m_value.array->begin(), m_value.array->end());
            }
            default:
            {
N
Niels 已提交
1013
                throw std::domain_error("cannot cast " + type_name() + " to " + typeid(T).name());
N
Niels 已提交
1014 1015 1016 1017
            }
        }
    }

N
Niels 已提交
1018
    array_t get_impl(array_t*) const
N
Niels 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027
    {
        switch (m_type)
        {
            case (value_t::array):
            {
                return *(m_value.array);
            }
            default:
            {
N
Niels 已提交
1028
                throw std::domain_error("cannot cast " + type_name() + " to array");
N
Niels 已提交
1029 1030 1031 1032 1033
            }
        }
    }

    /// get a string (explicit)
N
Niels 已提交
1034 1035
    template <typename T, typename
              std::enable_if<
N
Niels 已提交
1036 1037
                  std::is_convertible<string_t, T>::value
                  , int>::type = 0>
N
Niels 已提交
1038
    T get_impl(T*) const
N
Niels 已提交
1039 1040 1041
    {
        switch (m_type)
        {
N
Niels 已提交
1042 1043 1044 1045
            case (value_t::string):
            {
                return *m_value.string;
            }
N
Niels 已提交
1046
            default:
N
Niels 已提交
1047
            {
N
Niels 已提交
1048
                throw std::domain_error("cannot cast " + type_name() + " to " + typeid(T).name());
N
Niels 已提交
1049
            }
N
Niels 已提交
1050 1051 1052
        }
    }

N
Niels 已提交
1053
    /// get a number (explicit)
N
Niels 已提交
1054 1055
    template<typename T, typename
             std::enable_if<
N
Niels 已提交
1056 1057
                 std::is_arithmetic<T>::value
                 , int>::type = 0>
N
Niels 已提交
1058
    T get_impl(T*) const
N
Niels 已提交
1059 1060 1061 1062
    {
        switch (m_type)
        {
            case (value_t::number_integer):
N
Niels 已提交
1063
            {
N
Niels 已提交
1064
                return static_cast<T>(m_value.number_integer);
N
Niels 已提交
1065
            }
N
Niels 已提交
1066
            case (value_t::number_float):
N
Niels 已提交
1067
            {
N
Niels 已提交
1068
                return static_cast<T>(m_value.number_float);
N
Niels 已提交
1069
            }
N
Niels 已提交
1070
            default:
N
Niels 已提交
1071
            {
N
Niels 已提交
1072
                throw std::domain_error("cannot cast " + type_name() + " to " + typeid(T).name());
N
Niels 已提交
1073 1074 1075 1076 1077
            }
        }
    }

    /// get a boolean (explicit)
N
Niels 已提交
1078
    boolean_t get_impl(boolean_t*) const
N
Niels 已提交
1079 1080 1081 1082 1083 1084 1085 1086 1087
    {
        switch (m_type)
        {
            case (value_t::boolean):
            {
                return m_value.boolean;
            }
            default:
            {
N
Niels 已提交
1088
                throw std::domain_error("cannot cast " + type_name() + " to " + typeid(boolean_t).name());
N
Niels 已提交
1089
            }
N
Niels 已提交
1090 1091 1092
        }
    }

N
Niels 已提交
1093 1094 1095 1096
  public:
    /// get a value (explicit)
    // <http://stackoverflow.com/a/8315197/266378>
    template<typename T>
N
Niels 已提交
1097
    T get() const
N
Niels 已提交
1098 1099 1100 1101
    {
        return get_impl(static_cast<T*>(nullptr));
    }

N
Niels 已提交
1102
    /// get a value (implicit)
N
Niels 已提交
1103
    template<typename T>
N
Niels 已提交
1104
    operator T() const
N
Niels 已提交
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    {
        return get<T>();
    }


    ////////////////////
    // element access //
    ////////////////////

    /// access specified element with bounds checking
N
Niels 已提交
1115
    reference at(size_type idx)
N
Niels 已提交
1116 1117 1118 1119
    {
        // at only works for arrays
        if (m_type != value_t::array)
        {
N
Niels 已提交
1120
            throw std::domain_error("cannot use at with " + type_name());
N
Niels 已提交
1121 1122
        }

1123
        return m_value.array->at(idx);
N
Niels 已提交
1124 1125 1126
    }

    /// access specified element with bounds checking
N
Niels 已提交
1127
    const_reference at(size_type idx) const
N
Niels 已提交
1128 1129 1130 1131
    {
        // at only works for arrays
        if (m_type != value_t::array)
        {
N
Niels 已提交
1132
            throw std::domain_error("cannot use at with " + type_name());
N
Niels 已提交
1133 1134
        }

1135 1136 1137 1138
        return m_value.array->at(idx);
    }

    /// access specified element with bounds checking
N
Niels 已提交
1139
    reference at(const typename object_t::key_type& key)
1140 1141 1142 1143
    {
        // at only works for objects
        if (m_type != value_t::object)
        {
N
Niels 已提交
1144
            throw std::domain_error("cannot use at with " + type_name());
1145 1146 1147 1148 1149 1150
        }

        return m_value.object->at(key);
    }

    /// access specified element with bounds checking
N
Niels 已提交
1151
    const_reference at(const typename object_t::key_type& key) const
1152 1153 1154 1155
    {
        // at only works for objects
        if (m_type != value_t::object)
        {
N
Niels 已提交
1156
            throw std::domain_error("cannot use at with " + type_name());
1157 1158 1159
        }

        return m_value.object->at(key);
N
Niels 已提交
1160 1161 1162
    }

    /// access specified element
N
Niels 已提交
1163
    reference operator[](size_type idx)
N
Niels 已提交
1164
    {
N
Niels 已提交
1165 1166 1167 1168
        // implicitly convert null to object
        if (m_type == value_t::null)
        {
            m_type = value_t::array;
N
Niels 已提交
1169
            AllocatorType<array_t> alloc;
N
Niels 已提交
1170 1171 1172 1173 1174
            m_value.array = alloc.allocate(1);
            alloc.construct(m_value.array);
        }

        // [] only works for arrays
N
Niels 已提交
1175 1176
        if (m_type != value_t::array)
        {
N
Niels 已提交
1177
            throw std::domain_error("cannot use [] with " + type_name());
N
Niels 已提交
1178 1179
        }

1180
        for (size_t i = m_value.array->size(); i <= idx; ++i)
N
Niels 已提交
1181 1182 1183 1184
        {
            m_value.array->push_back(basic_json());
        }

1185
        return m_value.array->operator[](idx);
N
Niels 已提交
1186 1187 1188
    }

    /// access specified element
N
Niels 已提交
1189
    const_reference operator[](size_type idx) const
N
Niels 已提交
1190 1191 1192 1193
    {
        // at only works for arrays
        if (m_type != value_t::array)
        {
N
Niels 已提交
1194
            throw std::domain_error("cannot use [] with " + type_name());
N
Niels 已提交
1195 1196
        }

1197
        return m_value.array->operator[](idx);
N
Niels 已提交
1198 1199 1200
    }

    /// access specified element
N
Niels 已提交
1201
    reference operator[](const typename object_t::key_type& key)
N
Niels 已提交
1202
    {
N
Niels 已提交
1203 1204 1205 1206
        // implicitly convert null to object
        if (m_type == value_t::null)
        {
            m_type = value_t::object;
N
Niels 已提交
1207
            AllocatorType<object_t> alloc;
N
Niels 已提交
1208 1209 1210 1211
            m_value.object = alloc.allocate(1);
            alloc.construct(m_value.object);
        }

N
Niels 已提交
1212
        // [] only works for objects
N
Niels 已提交
1213 1214
        if (m_type != value_t::object)
        {
N
Niels 已提交
1215
            throw std::domain_error("cannot use [] with " + type_name());
N
Niels 已提交
1216 1217 1218 1219 1220
        }

        return m_value.object->operator[](key);
    }

1221
    /// access specified element
N
Niels 已提交
1222
    const_reference operator[](const typename object_t::key_type& key) const
1223 1224 1225 1226
    {
        // at only works for objects
        if (m_type != value_t::object)
        {
N
Niels 已提交
1227
            throw std::domain_error("cannot use [] with " + type_name());
1228 1229 1230 1231 1232
        }

        return m_value.object->operator[](key);
    }

N
Niels 已提交
1233
    /// access specified element (needed for clang)
N
Niels 已提交
1234
    template<typename T, std::size_t n>
N
Niels 已提交
1235
    reference operator[](const T (&key)[n])
N
Niels 已提交
1236
    {
N
Niels 已提交
1237 1238 1239 1240
        // implicitly convert null to object
        if (m_type == value_t::null)
        {
            m_type = value_t::object;
N
Niels 已提交
1241
            m_value = value_t::object;
N
Niels 已提交
1242 1243
        }

N
Niels 已提交
1244 1245 1246
        // at only works for objects
        if (m_type != value_t::object)
        {
N
Niels 已提交
1247
            throw std::domain_error("cannot use [] with " + type_name());
N
Niels 已提交
1248 1249 1250 1251 1252
        }

        return m_value.object->operator[](key);
    }

1253
    /// access specified element (needed for clang)
N
Niels 已提交
1254
    template<typename T, std::size_t n>
N
Niels 已提交
1255
    const_reference operator[](const T (&key)[n]) const
1256 1257 1258 1259
    {
        // at only works for objects
        if (m_type != value_t::object)
        {
N
Niels 已提交
1260
            throw std::domain_error("cannot use [] with " + type_name());
1261 1262 1263 1264 1265
        }

        return m_value.object->operator[](key);
    }

N
Niels 已提交
1266
    /// access the first element
N
Niels 已提交
1267
    reference front()
N
Niels 已提交
1268 1269 1270 1271 1272
    {
        return *begin();
    }

    /// access the first element
N
Niels 已提交
1273
    const_reference front() const
N
Niels 已提交
1274 1275 1276 1277 1278
    {
        return *cbegin();
    }

    /// access the last element
N
Niels 已提交
1279
    reference back()
N
Niels 已提交
1280 1281 1282 1283 1284 1285 1286
    {
        auto tmp = end();
        --tmp;
        return *tmp;
    }

    /// access the last element
N
Niels 已提交
1287
    const_reference back() const
N
Niels 已提交
1288 1289 1290 1291 1292 1293
    {
        auto tmp = cend();
        --tmp;
        return *tmp;
    }

1294 1295 1296
    /// remove element given an iterator
    template <class T, typename
              std::enable_if<
N
Niels 已提交
1297 1298
                  std::is_same<T, typename basic_json::iterator>::value or
                  std::is_same<T, typename basic_json::const_iterator>::value
1299 1300
                  , int>::type
              = 0>
N
Niels 已提交
1301
    T erase(T pos)
1302 1303 1304 1305
    {
        // make sure iterator fits the current value
        if (this != pos.m_object or m_type != pos.m_object->m_type)
        {
N
Niels 已提交
1306
            throw std::domain_error("iterator does not fit current value");
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
        }

        T result = end();

        switch (m_type)
        {
            case value_t::number_integer:
            case value_t::number_float:
            case value_t::boolean:
            case value_t::string:
            {
                if (pos.m_it.generic_iterator != 0)
                {
                    throw std::out_of_range("iterator out of range");
                }

                if (m_type == value_t::string)
                {
                    delete m_value.string;
                    m_value.string = nullptr;
                }

                m_type = value_t::null;
                break;
            }

            case value_t::object:
            {
                result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
                break;
            }

            case value_t::array:
            {
                result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
                break;
            }

            default:
            {
N
Niels 已提交
1347
                throw std::domain_error("cannot use erase with " + type_name());
1348 1349 1350 1351 1352 1353 1354 1355 1356
            }
        }

        return result;
    }

    /// remove elements given an iterator range
    template <class T, typename
              std::enable_if<
N
Niels 已提交
1357 1358
                  std::is_same<T, typename basic_json::iterator>::value or
                  std::is_same<T, typename basic_json::const_iterator>::value
1359 1360
                  , int>::type
              = 0>
N
Niels 已提交
1361
    T erase(T first, T last)
1362 1363 1364 1365 1366
    {
        // make sure iterator fits the current value
        if (this != first.m_object or this != last.m_object or
                m_type != first.m_object->m_type or m_type != last.m_object->m_type)
        {
N
Niels 已提交
1367
            throw std::domain_error("iterators do not fit current value");
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
        }

        T result = end();

        switch (m_type)
        {
            case value_t::number_integer:
            case value_t::number_float:
            case value_t::boolean:
            case value_t::string:
            {
                if (first.m_it.generic_iterator != 0 or last.m_it.generic_iterator != 1)
                {
                    throw std::out_of_range("iterators out of range");
                }

                if (m_type == value_t::string)
                {
                    delete m_value.string;
                    m_value.string = nullptr;
                }

                m_type = value_t::null;
                break;
            }

            case value_t::object:
            {
                result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
                                              last.m_it.object_iterator);
                break;
            }

            case value_t::array:
            {
                result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
                                             last.m_it.array_iterator);
                break;
            }

            default:
            {
N
Niels 已提交
1410
                throw std::domain_error("cannot use erase with " + type_name());
1411 1412 1413 1414 1415 1416
            }
        }

        return result;
    }

1417
    /// remove element from an object given a key
N
Niels 已提交
1418
    size_type erase(const typename object_t::key_type& key)
1419
    {
N
Niels 已提交
1420
        // this erase only works for objects
1421 1422
        if (m_type != value_t::object)
        {
N
Niels 已提交
1423
            throw std::domain_error("cannot use erase with " + type_name());
1424 1425 1426 1427 1428
        }

        return m_value.object->erase(key);
    }

N
Niels 已提交
1429
    /// remove element from an array given an index
N
Niels 已提交
1430
    void erase(const size_type idx)
N
Niels 已提交
1431 1432 1433 1434
    {
        // this erase only works for arrays
        if (m_type != value_t::array)
        {
N
Niels 已提交
1435
            throw std::domain_error("cannot use erase with " + type_name());
N
Niels 已提交
1436 1437
        }

N
Niels 已提交
1438
        if (idx >= size())
N
Niels 已提交
1439 1440 1441 1442
        {
            throw std::out_of_range("index out of range");
        }

N
Niels 已提交
1443
        m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
N
Niels 已提交
1444 1445
    }

N
Niels 已提交
1446
    /// find an element in an object
N
Niels 已提交
1447
    iterator find(typename object_t::key_type key)
N
Niels 已提交
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
    {
        auto result = end();

        if (m_type == value_t::object)
        {
            result.m_it.object_iterator = m_value.object->find(key);
        }

        return result;
    }

    /// find an element in an object
N
Niels 已提交
1460
    const_iterator find(typename object_t::key_type key) const
N
Niels 已提交
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
    {
        auto result = cend();

        if (m_type == value_t::object)
        {
            result.m_it.object_iterator = m_value.object->find(key);
        }

        return result;
    }

1472
    /// returns the number of occurrences of a key in an object
N
Niels 已提交
1473
    size_type count(typename object_t::key_type key) const
1474 1475 1476 1477 1478
    {
        // return 0 for all nonobject types
        return (m_type == value_t::object) ? m_value.object->count(key) : 0;
    }

N
Niels 已提交
1479

N
Niels 已提交
1480 1481 1482 1483
    ///////////////
    // iterators //
    ///////////////

N
Niels 已提交
1484 1485 1486 1487
    /*!
    @brief returns an iterator to the first element
    @ingroup container
    */
N
Niels 已提交
1488
    iterator begin() noexcept
N
Niels 已提交
1489 1490 1491 1492 1493 1494
    {
        iterator result(this);
        result.set_begin();
        return result;
    }

N
Niels 已提交
1495 1496 1497 1498
    /*!
    @brief returns a const iterator to the first element
    @ingroup container
    */
N
Niels 已提交
1499
    const_iterator begin() const noexcept
N
Niels 已提交
1500
    {
N
Niels 已提交
1501
        return cbegin();
N
Niels 已提交
1502 1503
    }

N
Niels 已提交
1504 1505 1506 1507
    /*!
    @brief returns a const iterator to the first element
    @ingroup container
    */
N
Niels 已提交
1508
    const_iterator cbegin() const noexcept
N
Niels 已提交
1509 1510 1511 1512 1513 1514
    {
        const_iterator result(this);
        result.set_begin();
        return result;
    }

N
Niels 已提交
1515 1516 1517 1518
    /*!
    @brief returns an iterator to one past the last element
    @ingroup container
    */
N
Niels 已提交
1519
    iterator end() noexcept
N
Niels 已提交
1520 1521 1522 1523 1524 1525
    {
        iterator result(this);
        result.set_end();
        return result;
    }

N
Niels 已提交
1526 1527 1528 1529
    /*!
    @brief returns a const iterator to one past the last element
    @ingroup container
    */
N
Niels 已提交
1530
    const_iterator end() const noexcept
N
Niels 已提交
1531
    {
N
Niels 已提交
1532
        return cend();
N
Niels 已提交
1533 1534
    }

N
Niels 已提交
1535 1536 1537 1538
    /*!
    @brief returns a const iterator to one past the last element
    @ingroup container
    */
N
Niels 已提交
1539
    const_iterator cend() const noexcept
N
Niels 已提交
1540 1541 1542 1543 1544 1545
    {
        const_iterator result(this);
        result.set_end();
        return result;
    }

N
Niels 已提交
1546 1547 1548 1549
    /*!
    @brief returns a reverse iterator to the first element
    @ingroup reversiblecontainer
    */
N
Niels 已提交
1550
    reverse_iterator rbegin() noexcept
N
Niels 已提交
1551 1552 1553 1554
    {
        return reverse_iterator(end());
    }

N
Niels 已提交
1555 1556 1557 1558
    /*!
    @brief returns a const reverse iterator to the first element
    @ingroup reversiblecontainer
    */
N
Niels 已提交
1559
    const_reverse_iterator rbegin() const noexcept
N
Niels 已提交
1560
    {
N
Niels 已提交
1561
        return crbegin();
N
Niels 已提交
1562 1563
    }

N
Niels 已提交
1564 1565 1566 1567
    /*!
    @brief returns a reverse iterator to one past the last element
    @ingroup reversiblecontainer
    */
N
Niels 已提交
1568
    reverse_iterator rend() noexcept
N
Niels 已提交
1569 1570 1571 1572
    {
        return reverse_iterator(begin());
    }

N
Niels 已提交
1573 1574 1575 1576
    /*!
    @brief returns a const reverse iterator to one past the last element
    @ingroup reversiblecontainer
    */
N
Niels 已提交
1577
    const_reverse_iterator rend() const noexcept
N
Niels 已提交
1578
    {
N
Niels 已提交
1579
        return crend();
N
Niels 已提交
1580 1581
    }

N
Niels 已提交
1582 1583 1584 1585
    /*!
    @brief returns a const reverse iterator to the first element
    @ingroup reversiblecontainer
    */
N
Niels 已提交
1586
    const_reverse_iterator crbegin() const noexcept
N
Niels 已提交
1587 1588 1589 1590
    {
        return const_reverse_iterator(cend());
    }

N
Niels 已提交
1591 1592 1593 1594
    /*!
    @brief returns a const reverse iterator to one past the last element
    @ingroup reversiblecontainer
    */
N
Niels 已提交
1595
    const_reverse_iterator crend() const noexcept
N
Niels 已提交
1596 1597 1598 1599
    {
        return const_reverse_iterator(cbegin());
    }

N
Niels 已提交
1600 1601 1602 1603 1604

    //////////////
    // capacity //
    //////////////

N
Niels 已提交
1605 1606 1607 1608
    /*!
    @brief checks whether the container is empty
    @ingroup container
    */
N
Niels 已提交
1609
    bool empty() const noexcept
N
Niels 已提交
1610 1611 1612 1613 1614 1615 1616
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                return true;
            }
N
Niels 已提交
1617

N
Niels 已提交
1618 1619 1620 1621
            case (value_t::array):
            {
                return m_value.array->empty();
            }
N
Niels 已提交
1622

N
Niels 已提交
1623 1624 1625 1626
            case (value_t::object):
            {
                return m_value.object->empty();
            }
N
Niels 已提交
1627

N
Niels 已提交
1628 1629 1630 1631 1632 1633
            default:
            {
                // all other types are nonempty
                return false;
            }
        }
N
Niels 已提交
1634 1635
    }

N
Niels 已提交
1636 1637 1638 1639
    /*!
    @brief returns the number of elements
    @ingroup container
    */
N
Niels 已提交
1640
    size_type size() const noexcept
N
Niels 已提交
1641 1642 1643 1644 1645 1646 1647
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                return 0;
            }
N
Niels 已提交
1648

N
Niels 已提交
1649 1650 1651 1652
            case (value_t::array):
            {
                return m_value.array->size();
            }
N
Niels 已提交
1653

N
Niels 已提交
1654 1655 1656 1657
            case (value_t::object):
            {
                return m_value.object->size();
            }
N
Niels 已提交
1658

N
Niels 已提交
1659 1660 1661 1662 1663 1664
            default:
            {
                // all other types have size 1
                return 1;
            }
        }
N
Niels 已提交
1665 1666
    }

N
Niels 已提交
1667 1668 1669 1670
    /*!
    @brief returns the maximum possible number of elements
    @ingroup container
    */
N
Niels 已提交
1671
    size_type max_size() const noexcept
N
Niels 已提交
1672 1673 1674 1675 1676 1677 1678
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                return 0;
            }
N
Niels 已提交
1679

N
Niels 已提交
1680 1681 1682 1683
            case (value_t::array):
            {
                return m_value.array->max_size();
            }
N
Niels 已提交
1684

N
Niels 已提交
1685 1686 1687 1688
            case (value_t::object):
            {
                return m_value.object->max_size();
            }
N
Niels 已提交
1689

N
Niels 已提交
1690 1691 1692 1693 1694 1695
            default:
            {
                // all other types have max_size 1
                return 1;
            }
        }
N
Niels 已提交
1696 1697 1698 1699 1700 1701 1702 1703
    }


    ///////////////
    // modifiers //
    ///////////////

    /// clears the contents
N
Niels 已提交
1704
    void clear() noexcept
N
Niels 已提交
1705 1706 1707 1708
    {
        switch (m_type)
        {
            case (value_t::null):
N
Niels 已提交
1709
            case (value_t::discarded):
N
Niels 已提交
1710 1711 1712
            {
                break;
            }
N
Niels 已提交
1713

N
Niels 已提交
1714 1715
            case (value_t::number_integer):
            {
N
Niels 已提交
1716
                m_value.number_integer = 0;
N
Niels 已提交
1717 1718
                break;
            }
N
Niels 已提交
1719

N
Niels 已提交
1720 1721
            case (value_t::number_float):
            {
N
Niels 已提交
1722
                m_value.number_float = 0.0;
N
Niels 已提交
1723 1724
                break;
            }
N
Niels 已提交
1725

N
Niels 已提交
1726 1727
            case (value_t::boolean):
            {
N
Niels 已提交
1728
                m_value.boolean = false;
N
Niels 已提交
1729 1730
                break;
            }
N
Niels 已提交
1731

N
Niels 已提交
1732 1733 1734 1735 1736
            case (value_t::string):
            {
                m_value.string->clear();
                break;
            }
N
Niels 已提交
1737

N
Niels 已提交
1738 1739 1740 1741 1742
            case (value_t::array):
            {
                m_value.array->clear();
                break;
            }
N
Niels 已提交
1743

N
Niels 已提交
1744 1745 1746 1747 1748 1749 1750 1751 1752
            case (value_t::object):
            {
                m_value.object->clear();
                break;
            }
        }
    }

    /// add an object to an array
N
Niels 已提交
1753
    void push_back(basic_json&& value)
N
Niels 已提交
1754 1755 1756 1757
    {
        // push_back only works for null objects or arrays
        if (not(m_type == value_t::null or m_type == value_t::array))
        {
N
Niels 已提交
1758
            throw std::domain_error("cannot add element to " + type_name());
N
Niels 已提交
1759 1760 1761 1762 1763 1764
        }

        // transform null object into an array
        if (m_type == value_t::null)
        {
            m_type = value_t::array;
N
Niels 已提交
1765
            m_value = value_t::array;
N
Niels 已提交
1766 1767 1768 1769 1770 1771 1772 1773
        }

        // add element to array (move semantics)
        m_value.array->push_back(std::move(value));
        // invalidate object
        value.m_type = value_t::null;
    }

N
Niels 已提交
1774
    /// add an object to an array
N
Niels 已提交
1775
    reference operator+=(basic_json&& value)
N
Niels 已提交
1776 1777 1778 1779 1780
    {
        push_back(std::move(value));
        return *this;
    }

N
Niels 已提交
1781
    /// add an object to an array
N
Niels 已提交
1782
    void push_back(const basic_json& value)
N
Niels 已提交
1783 1784 1785 1786
    {
        // push_back only works for null objects or arrays
        if (not(m_type == value_t::null or m_type == value_t::array))
        {
N
Niels 已提交
1787
            throw std::domain_error("cannot add element to " + type_name());
N
Niels 已提交
1788 1789 1790 1791 1792 1793
        }

        // transform null object into an array
        if (m_type == value_t::null)
        {
            m_type = value_t::array;
N
Niels 已提交
1794
            m_value = value_t::array;
N
Niels 已提交
1795 1796 1797 1798 1799 1800 1801
        }

        // add element to array
        m_value.array->push_back(value);
    }

    /// add an object to an array
N
Niels 已提交
1802
    reference operator+=(const basic_json& value)
N
Niels 已提交
1803 1804 1805 1806 1807 1808
    {
        push_back(value);
        return *this;
    }

    /// add an object to an object
N
Niels 已提交
1809
    void push_back(const typename object_t::value_type& value)
N
Niels 已提交
1810 1811 1812 1813
    {
        // push_back only works for null objects or objects
        if (not(m_type == value_t::null or m_type == value_t::object))
        {
N
Niels 已提交
1814
            throw std::domain_error("cannot add element to " + type_name());
N
Niels 已提交
1815 1816 1817 1818 1819 1820
        }

        // transform null object into an object
        if (m_type == value_t::null)
        {
            m_type = value_t::object;
N
Niels 已提交
1821
            m_value = value_t::object;
N
Niels 已提交
1822 1823 1824 1825 1826 1827 1828
        }

        // add element to array
        m_value.object->insert(value);
    }

    /// add an object to an object
N
Niels 已提交
1829
    reference operator+=(const typename object_t::value_type& value)
N
Niels 已提交
1830 1831 1832 1833 1834
    {
        push_back(value);
        return operator[](value.first);
    }

N
Niels 已提交
1835 1836 1837 1838
    /*!
    @brief exchanges the values
    @ingroup container
    */
N
Niels 已提交
1839
    void swap(reference other) noexcept (
N
Niels 已提交
1840 1841 1842 1843 1844
        std::is_nothrow_move_constructible<value_t>::value and
        std::is_nothrow_move_assignable<value_t>::value and
        std::is_nothrow_move_constructible<json_value>::value and
        std::is_nothrow_move_assignable<json_value>::value
    )
N
Niels 已提交
1845 1846 1847 1848 1849 1850
    {
        std::swap(m_type, other.m_type);
        std::swap(m_value, other.m_value);
    }

    /// swaps the contents
N
Niels 已提交
1851
    void swap(array_t& other)
N
Niels 已提交
1852 1853 1854 1855
    {
        // swap only works for arrays
        if (m_type != value_t::array)
        {
N
Niels 已提交
1856
            throw std::domain_error("cannot use swap with " + type_name());
N
Niels 已提交
1857 1858 1859 1860 1861 1862 1863
        }

        // swap arrays
        std::swap(*(m_value.array), other);
    }

    /// swaps the contents
N
Niels 已提交
1864
    void swap(object_t& other)
N
Niels 已提交
1865 1866 1867 1868
    {
        // swap only works for objects
        if (m_type != value_t::object)
        {
N
Niels 已提交
1869
            throw std::domain_error("cannot use swap with " + type_name());
N
Niels 已提交
1870 1871 1872 1873 1874 1875 1876
        }

        // swap arrays
        std::swap(*(m_value.object), other);
    }

    /// swaps the contents
N
Niels 已提交
1877
    void swap(string_t& other)
N
Niels 已提交
1878 1879 1880 1881
    {
        // swap only works for strings
        if (m_type != value_t::string)
        {
N
Niels 已提交
1882
            throw std::domain_error("cannot use swap with " + type_name());
N
Niels 已提交
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
        }

        // swap arrays
        std::swap(*(m_value.string), other);
    }


    //////////////////////////////////////////
    // lexicographical comparison operators //
    //////////////////////////////////////////

N
Niels 已提交
1894 1895 1896 1897
    /*!
    @brief comparison: equal
    @ingroup container
    */
N
Niels 已提交
1898
    friend bool operator==(const_reference lhs, const_reference rhs) noexcept
N
Niels 已提交
1899
    {
F
Florian Weber 已提交
1900 1901
        const auto lhs_type = lhs.type();
        const auto rhs_type = rhs.type();
N
Niels 已提交
1902

F
Florian Weber 已提交
1903
        if (lhs_type == rhs_type)
N
Niels 已提交
1904
        {
F
Florian Weber 已提交
1905
            switch (lhs_type)
N
Niels 已提交
1906
            {
F
Florian Weber 已提交
1907
                case (value_t::array):
N
Niels 已提交
1908
                    return *lhs.m_value.array == *rhs.m_value.array;
F
Florian Weber 已提交
1909
                case (value_t::object):
N
Niels 已提交
1910
                    return *lhs.m_value.object == *rhs.m_value.object;
F
Florian Weber 已提交
1911
                case (value_t::null):
N
Niels 已提交
1912
                    return true;
F
Florian Weber 已提交
1913
                case (value_t::string):
N
Niels 已提交
1914
                    return *lhs.m_value.string == *rhs.m_value.string;
F
Florian Weber 已提交
1915
                case (value_t::boolean):
N
Niels 已提交
1916
                    return lhs.m_value.boolean == rhs.m_value.boolean;
F
Florian Weber 已提交
1917
                case (value_t::number_integer):
N
Niels 已提交
1918
                    return lhs.m_value.number_integer == rhs.m_value.number_integer;
F
Florian Weber 已提交
1919
                case (value_t::number_float):
1920
                    return approx(lhs.m_value.number_float, rhs.m_value.number_float);
N
Niels 已提交
1921 1922
                case (value_t::discarded):
                    return false;
N
Niels 已提交
1923 1924
            }
        }
F
Florian Weber 已提交
1925 1926
        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
        {
1927 1928
            return approx(static_cast<number_float_t>(lhs.m_value.number_integer),
                          rhs.m_value.number_float);
F
Florian Weber 已提交
1929 1930 1931 1932 1933 1934
        }
        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
        {
            return approx(lhs.m_value.number_float,
                          static_cast<number_float_t>(rhs.m_value.number_integer));
        }
N
Niels 已提交
1935 1936 1937
        return false;
    }

N
Niels 已提交
1938 1939 1940 1941
    /*!
    @brief comparison: not equal
    @ingroup container
    */
N
Niels 已提交
1942
    friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
N
Niels 已提交
1943 1944 1945 1946 1947
    {
        return not (lhs == rhs);
    }

    /// comparison: less than
N
Niels 已提交
1948
    friend bool operator<(const_reference lhs, const_reference rhs) noexcept
N
Niels 已提交
1949
    {
F
Florian Weber 已提交
1950 1951
        const auto lhs_type = lhs.type();
        const auto rhs_type = rhs.type();
N
Niels 已提交
1952

F
Florian Weber 已提交
1953
        if (lhs_type == rhs_type)
N
Niels 已提交
1954
        {
F
Florian Weber 已提交
1955
            switch (lhs_type)
N
Niels 已提交
1956
            {
F
Florian Weber 已提交
1957
                case (value_t::array):
N
Niels 已提交
1958
                    return *lhs.m_value.array < *rhs.m_value.array;
F
Florian Weber 已提交
1959
                case (value_t::object):
N
Niels 已提交
1960
                    return *lhs.m_value.object < *rhs.m_value.object;
F
Florian Weber 已提交
1961
                case (value_t::null):
N
Niels 已提交
1962
                    return false;
F
Florian Weber 已提交
1963
                case (value_t::string):
N
Niels 已提交
1964
                    return *lhs.m_value.string < *rhs.m_value.string;
F
Florian Weber 已提交
1965
                case (value_t::boolean):
N
Niels 已提交
1966
                    return lhs.m_value.boolean < rhs.m_value.boolean;
F
Florian Weber 已提交
1967
                case (value_t::number_integer):
N
Niels 已提交
1968
                    return lhs.m_value.number_integer < rhs.m_value.number_integer;
F
Florian Weber 已提交
1969
                case (value_t::number_float):
N
Niels 已提交
1970
                    return lhs.m_value.number_float < rhs.m_value.number_float;
N
Niels 已提交
1971 1972
                case (value_t::discarded):
                    return false;
N
Niels 已提交
1973 1974
            }
        }
F
Florian Weber 已提交
1975 1976
        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
        {
1977 1978
            return static_cast<number_float_t>(lhs.m_value.number_integer) <
                   rhs.m_value.number_float;
F
Florian Weber 已提交
1979 1980 1981 1982 1983 1984
        }
        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
        {
            return lhs.m_value.number_float <
                   static_cast<number_float_t>(rhs.m_value.number_integer);
        }
N
Niels 已提交
1985

N
Niels 已提交
1986 1987
        // We only reach this line if we cannot compare values. In that case,
        // we compare types.
F
Florian Weber 已提交
1988
        return lhs_type < rhs_type;
N
Niels 已提交
1989 1990 1991
    }

    /// comparison: less than or equal
N
Niels 已提交
1992
    friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
N
Niels 已提交
1993 1994 1995 1996 1997
    {
        return not (rhs < lhs);
    }

    /// comparison: greater than
N
Niels 已提交
1998
    friend bool operator>(const_reference lhs, const_reference rhs) noexcept
N
Niels 已提交
1999 2000 2001 2002 2003
    {
        return not (lhs <= rhs);
    }

    /// comparison: greater than or equal
N
Niels 已提交
2004
    friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
N
Niels 已提交
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
    {
        return not (lhs < rhs);
    }


    ///////////////////
    // serialization //
    ///////////////////

    /// serialize to stream
    friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
    {
N
Niels 已提交
2017
        // read width member and use it as indentation parameter if nonzero
N
Niels 已提交
2018 2019
        const bool pretty_print = (o.width() > 0);
        const auto indentation = (pretty_print ? o.width() : 0);
N
Niels 已提交
2020

N
Niels 已提交
2021 2022 2023 2024
        // reset width to 0 for subsequent calls to this stream
        o.width(0);

        // do the actual serialization
N
Niels 已提交
2025
        j.dump(o, pretty_print, static_cast<unsigned int>(indentation));
N
Niels 已提交
2026 2027 2028 2029 2030 2031
        return o;
    }

    /// serialize to stream
    friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
    {
N
Niels 已提交
2032
        return o << j;
N
Niels 已提交
2033 2034 2035 2036 2037 2038 2039
    }


    /////////////////////
    // deserialization //
    /////////////////////

N
Niels 已提交
2040
    /// deserialize from string
N
Niels 已提交
2041
    static basic_json parse(const string_t& s, parser_callback_t cb = nullptr)
N
Niels 已提交
2042
    {
N
Niels 已提交
2043
        return parser(s, cb).parse();
N
Niels 已提交
2044 2045
    }

N
Niels 已提交
2046
    /// deserialize from stream
N
Niels 已提交
2047
    static basic_json parse(std::istream& i, parser_callback_t cb = nullptr)
N
Niels 已提交
2048
    {
N
Niels 已提交
2049
        return parser(i, cb).parse();
N
Niels 已提交
2050 2051
    }

N
Niels 已提交
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
    /// deserialize from stream
    friend std::istream& operator>>(std::istream& i, basic_json& j)
    {
        j = parser(i).parse();
        return i;
    }

    /// deserialize from stream
    friend std::istream& operator<<(basic_json& j, std::istream& i)
    {
        j = parser(i).parse();
        return i;
    }


  private:
    ///////////////////////////
    // convenience functions //
    ///////////////////////////

    /// return the type as string
N
Niels 已提交
2073
    string_t type_name() const noexcept
N
Niels 已提交
2074 2075 2076 2077 2078 2079 2080
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                return "null";
            }
N
Niels 已提交
2081

N
Niels 已提交
2082 2083 2084 2085
            case (value_t::object):
            {
                return "object";
            }
N
Niels 已提交
2086

N
Niels 已提交
2087 2088 2089 2090
            case (value_t::array):
            {
                return "array";
            }
N
Niels 已提交
2091

N
Niels 已提交
2092 2093 2094 2095
            case (value_t::string):
            {
                return "string";
            }
N
Niels 已提交
2096

N
Niels 已提交
2097 2098 2099 2100
            case (value_t::boolean):
            {
                return "boolean";
            }
N
Niels 已提交
2101

N
Niels 已提交
2102 2103 2104 2105 2106
            case (value_t::discarded):
            {
                return "discarded";
            }

N
Niels 已提交
2107
            default:
N
Niels 已提交
2108 2109 2110 2111 2112 2113 2114 2115
            {
                return "number";
            }
        }
    }

    /*!
    @brief escape a string
N
Niels 已提交
2116

N
Niels 已提交
2117 2118 2119 2120 2121
    Escape a string by replacing certain special characters by a sequence of an
    escape character (backslash) and another character and other control
    characters by a sequence of "\u" followed by a four-digit hex
    representation.

N
Niels 已提交
2122
    @param o  the stream to write the escaped string to
N
Niels 已提交
2123 2124
    @param s  the string to escape
    */
N
Niels 已提交
2125
    static void escape_string(std::ostream& o, const string_t& s) noexcept
N
Niels 已提交
2126 2127 2128 2129 2130 2131 2132 2133
    {
        for (const auto c : s)
        {
            switch (c)
            {
                // quotation mark (0x22)
                case '"':
                {
N
Niels 已提交
2134
                    o << "\\\"";
N
Niels 已提交
2135 2136
                    break;
                }
N
Niels 已提交
2137

N
Niels 已提交
2138 2139 2140
                // reverse solidus (0x5c)
                case '\\':
                {
N
Niels 已提交
2141
                    o << "\\\\";
N
Niels 已提交
2142 2143
                    break;
                }
N
Niels 已提交
2144

N
Niels 已提交
2145 2146 2147
                // backspace (0x08)
                case '\b':
                {
N
Niels 已提交
2148
                    o << "\\b";
N
Niels 已提交
2149 2150
                    break;
                }
N
Niels 已提交
2151

N
Niels 已提交
2152 2153 2154
                // formfeed (0x0c)
                case '\f':
                {
N
Niels 已提交
2155
                    o << "\\f";
N
Niels 已提交
2156 2157
                    break;
                }
N
Niels 已提交
2158

N
Niels 已提交
2159 2160 2161
                // newline (0x0a)
                case '\n':
                {
N
Niels 已提交
2162
                    o << "\\n";
N
Niels 已提交
2163 2164
                    break;
                }
N
Niels 已提交
2165

N
Niels 已提交
2166 2167 2168
                // carriage return (0x0d)
                case '\r':
                {
N
Niels 已提交
2169
                    o << "\\r";
N
Niels 已提交
2170 2171
                    break;
                }
N
Niels 已提交
2172

N
Niels 已提交
2173 2174 2175
                // horizontal tab (0x09)
                case '\t':
                {
N
Niels 已提交
2176
                    o << "\\t";
N
Niels 已提交
2177 2178 2179 2180 2181
                    break;
                }

                default:
                {
N
Niels 已提交
2182
                    if (c >= 0 and c <= 0x1f)
N
Niels 已提交
2183 2184 2185
                    {
                        // control characters (everything between 0x00 and 0x1f)
                        // -> create four-digit hex representation
N
Niels 已提交
2186
                        o << "\\u" << std::hex << std::setw(4) << std::setfill('0') << int(c);
N
Niels 已提交
2187 2188 2189 2190
                    }
                    else
                    {
                        // all other characters are added as-is
N
Niels 已提交
2191
                        o << c;
N
Niels 已提交
2192 2193 2194 2195 2196 2197 2198 2199 2200
                    }
                    break;
                }
            }
        }
    }

    /*!
    @brief internal implementation of the serialization function
N
Niels 已提交
2201

N
Niels 已提交
2202 2203 2204 2205
    This function is called by the public member function dump and organizes
    the serializaion internally. The indentation level is propagated as
    additional parameter. In case of arrays and objects, the function is called
    recursively. Note that
N
Niels 已提交
2206

N
Niels 已提交
2207
    - strings and object keys are escaped using escape_string()
N
Niels 已提交
2208
    - integer numbers are converted implictly via operator<<
2209
    - floating-point numbers are converted to a string using "%g" format
N
Niels 已提交
2210

N
Niels 已提交
2211 2212 2213 2214
    @param o               stream to write to
    @param pretty_print    whether the output shall be pretty-printed
    @param indent_step     the indent level
    @param current_indent  the current indent level (only used internally)
N
Niels 已提交
2215
    */
N
Niels 已提交
2216 2217
    void dump(std::ostream& o, const bool pretty_print, const unsigned int indent_step,
              const unsigned int current_indent = 0) const noexcept
N
Niels 已提交
2218
    {
N
Niels 已提交
2219
        // variable to hold indentation for recursive calls
N
Niels 已提交
2220
        unsigned int new_indent = current_indent;
N
Niels 已提交
2221

N
Niels 已提交
2222 2223 2224 2225 2226 2227
        switch (m_type)
        {
            case (value_t::object):
            {
                if (m_value.object->empty())
                {
N
Niels 已提交
2228 2229
                    o << "{}";
                    return;
N
Niels 已提交
2230 2231
                }

N
Niels 已提交
2232
                o << "{";
N
Niels 已提交
2233 2234

                // increase indentation
N
Niels 已提交
2235
                if (pretty_print)
N
Niels 已提交
2236
                {
N
Niels 已提交
2237
                    new_indent += indent_step;
N
Niels 已提交
2238
                    o << "\n";
N
Niels 已提交
2239 2240 2241 2242 2243 2244
                }

                for (auto i = m_value.object->cbegin(); i != m_value.object->cend(); ++i)
                {
                    if (i != m_value.object->cbegin())
                    {
N
Niels 已提交
2245
                        o << (pretty_print ? ",\n" : ",");
N
Niels 已提交
2246
                    }
N
Niels 已提交
2247 2248
                    o << string_t(new_indent, ' ') << "\"";
                    escape_string(o, i->first);
N
Niels 已提交
2249 2250
                    o << "\":" << (pretty_print ? " " : "");
                    i->second.dump(o, pretty_print, indent_step, new_indent);
N
Niels 已提交
2251 2252 2253
                }

                // decrease indentation
N
Niels 已提交
2254
                if (pretty_print)
N
Niels 已提交
2255
                {
N
Niels 已提交
2256
                    new_indent -= indent_step;
N
Niels 已提交
2257
                    o << "\n";
N
Niels 已提交
2258 2259
                }

N
Niels 已提交
2260 2261
                o << string_t(new_indent, ' ') + "}";
                return;
N
Niels 已提交
2262 2263 2264 2265 2266 2267
            }

            case (value_t::array):
            {
                if (m_value.array->empty())
                {
N
Niels 已提交
2268 2269
                    o << "[]";
                    return;
N
Niels 已提交
2270 2271
                }

N
Niels 已提交
2272
                o << "[";
N
Niels 已提交
2273 2274

                // increase indentation
N
Niels 已提交
2275
                if (pretty_print)
N
Niels 已提交
2276
                {
N
Niels 已提交
2277
                    new_indent += indent_step;
N
Niels 已提交
2278
                    o << "\n";
N
Niels 已提交
2279 2280 2281 2282 2283 2284
                }

                for (auto i = m_value.array->cbegin(); i != m_value.array->cend(); ++i)
                {
                    if (i != m_value.array->cbegin())
                    {
N
Niels 已提交
2285
                        o << (pretty_print ? ",\n" : ",");
N
Niels 已提交
2286
                    }
N
Niels 已提交
2287
                    o << string_t(new_indent, ' ');
N
Niels 已提交
2288
                    i->dump(o, pretty_print, indent_step, new_indent);
N
Niels 已提交
2289 2290 2291
                }

                // decrease indentation
N
Niels 已提交
2292
                if (pretty_print)
N
Niels 已提交
2293
                {
N
Niels 已提交
2294
                    new_indent -= indent_step;
N
Niels 已提交
2295
                    o << "\n";
N
Niels 已提交
2296 2297
                }

N
Niels 已提交
2298 2299
                o << string_t(new_indent, ' ') << "]";
                return;
N
Niels 已提交
2300 2301 2302 2303
            }

            case (value_t::string):
            {
N
Niels 已提交
2304 2305 2306 2307
                o << string_t("\"");
                escape_string(o, *m_value.string);
                o << "\"";
                return;
N
Niels 已提交
2308 2309 2310 2311
            }

            case (value_t::boolean):
            {
N
Niels 已提交
2312 2313
                o << (m_value.boolean ? "true" : "false");
                return;
N
Niels 已提交
2314 2315 2316 2317
            }

            case (value_t::number_integer):
            {
N
Niels 已提交
2318 2319
                o << m_value.number_integer;
                return;
N
Niels 已提交
2320 2321 2322 2323
            }

            case (value_t::number_float):
            {
N
Niels 已提交
2324
                // 15 digits of precision allows round-trip IEEE 754
N
Niels 已提交
2325 2326 2327
                // string->double->string; to be safe, we read this value from
                // std::numeric_limits<number_float_t>::digits10
                o << std::setprecision(std::numeric_limits<number_float_t>::digits10) << m_value.number_float;
N
Niels 已提交
2328
                return;
N
Niels 已提交
2329
            }
N
Niels 已提交
2330

N
Niels 已提交
2331 2332
            case (value_t::discarded):
            {
N
Niels 已提交
2333 2334
                o << "<discarded>";
                return;
N
Niels 已提交
2335
            }
N
Niels 已提交
2336

N
Niels 已提交
2337 2338
            default:
            {
N
Niels 已提交
2339 2340
                o << "null";
                return;
N
Niels 已提交
2341
            }
N
Niels 已提交
2342 2343 2344
        }
    }

2345 2346
    /// "equality" comparison for floating point numbers
    template<typename T>
N
Niels 已提交
2347
    static bool approx(const T a, const T b)
2348 2349 2350 2351
    {
        return not (a > b or a < b);
    }

N
Niels 已提交
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363

  private:
    //////////////////////
    // member variables //
    //////////////////////

    /// the type of the current element
    value_t m_type = value_t::null;

    /// the value of the current element
    json_value m_value = {};

N
Niels 已提交
2364

N
Niels 已提交
2365
  private:
N
Niels 已提交
2366 2367 2368 2369
    ///////////////
    // iterators //
    ///////////////

N
Niels 已提交
2370 2371 2372 2373
    /// an iterator value
    union internal_iterator
    {
        /// iterator for JSON objects
N
Niels 已提交
2374
        typename object_t::iterator object_iterator;
N
Niels 已提交
2375
        /// iterator for JSON arrays
N
Niels 已提交
2376
        typename array_t::iterator array_iterator;
N
Niels 已提交
2377
        /// generic iterator for all other value types
N
Niels 已提交
2378
        difference_type generic_iterator;
N
Niels 已提交
2379 2380

        /// default constructor
N
Niels 已提交
2381
        internal_iterator() : generic_iterator(-1) {}
N
Niels 已提交
2382 2383 2384
    };

  public:
N
Niels 已提交
2385 2386
    /// a random access iterator for the basic_json class
    class iterator : public std::iterator<std::random_access_iterator_tag, basic_json>
N
Niels 已提交
2387
    {
2388 2389 2390
        // allow basic_json class to access m_it
        friend class basic_json;

N
Niels 已提交
2391 2392
      public:
        /// the type of the values when the iterator is dereferenced
N
Niels 已提交
2393
        using value_type = typename basic_json::value_type;
N
Niels 已提交
2394
        /// a type to represent differences between iterators
N
Niels 已提交
2395
        using difference_type = typename basic_json::difference_type;
N
Niels 已提交
2396
        /// defines a pointer to the type iterated over (value_type)
N
Niels 已提交
2397
        using pointer = typename basic_json::pointer;
N
Niels 已提交
2398
        /// defines a reference to the type iterated over (value_type)
N
Niels 已提交
2399
        using reference = typename basic_json::reference;
N
Niels 已提交
2400
        /// the category of the iterator
N
Niels 已提交
2401
        using iterator_category = std::bidirectional_iterator_tag;
N
Niels 已提交
2402

2403
        /// default constructor
N
Niels 已提交
2404
        iterator() = default;
2405

N
Niels 已提交
2406
        /// constructor for a given JSON instance
N
Niels 已提交
2407
        iterator(pointer object) noexcept : m_object(object)
N
Niels 已提交
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    m_it.object_iterator = typename object_t::iterator();
                    break;
                }
                case (basic_json::value_t::array):
                {
                    m_it.array_iterator = typename array_t::iterator();
                    break;
                }
                default:
                {
N
Niels 已提交
2423
                    m_it.generic_iterator = -1;
N
Niels 已提交
2424 2425 2426 2427 2428
                    break;
                }
            }
        }

N
Niels 已提交
2429
        /// copy constructor
N
Niels 已提交
2430
        iterator(const iterator& other) noexcept
N
Niels 已提交
2431 2432 2433
            : m_object(other.m_object), m_it(other.m_it)
        {}

N
Niels 已提交
2434
        /// copy assignment
N
Niels 已提交
2435
        iterator& operator=(iterator other) noexcept (
N
Niels 已提交
2436 2437
            std::is_nothrow_move_constructible<pointer>::value and
            std::is_nothrow_move_assignable<pointer>::value and
N
Niels 已提交
2438 2439
            std::is_nothrow_move_constructible<internal_iterator>::value and
            std::is_nothrow_move_assignable<internal_iterator>::value
N
Niels 已提交
2440 2441 2442 2443
        )
        {
            std::swap(m_object, other.m_object);
            std::swap(m_it, other.m_it);
N
Niels 已提交
2444 2445 2446
            return *this;
        }

N
Niels 已提交
2447
      private:
N
Niels 已提交
2448
        /// set the iterator to the first value
N
Niels 已提交
2449
        void set_begin() noexcept
N
Niels 已提交
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    m_it.object_iterator = m_object->m_value.object->begin();
                    break;
                }

                case (basic_json::value_t::array):
                {
                    m_it.array_iterator = m_object->m_value.array->begin();
                    break;
                }

                case (basic_json::value_t::null):
                {
N
Niels 已提交
2467
                    // set to end so begin()==end() is true: null is empty
N
Niels 已提交
2468
                    m_it.generic_iterator = 1;
N
Niels 已提交
2469 2470 2471 2472 2473
                    break;
                }

                default:
                {
N
Niels 已提交
2474
                    m_it.generic_iterator = 0;
N
Niels 已提交
2475 2476 2477 2478 2479 2480
                    break;
                }
            }
        }

        /// set the iterator past the last value
N
Niels 已提交
2481
        void set_end() noexcept
N
Niels 已提交
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    m_it.object_iterator = m_object->m_value.object->end();
                    break;
                }

                case (basic_json::value_t::array):
                {
                    m_it.array_iterator = m_object->m_value.array->end();
                    break;
                }

                default:
                {
N
Niels 已提交
2499
                    m_it.generic_iterator = 1;
N
Niels 已提交
2500 2501 2502 2503 2504
                    break;
                }
            }
        }

N
Niels 已提交
2505
      public:
N
Niels 已提交
2506
        /// return a reference to the value pointed to by the iterator
N
Niels 已提交
2507
        reference operator*()
N
Niels 已提交
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    return m_it.object_iterator->second;
                }

                case (basic_json::value_t::array):
                {
                    return *m_it.array_iterator;
                }

                case (basic_json::value_t::null):
                {
                    throw std::out_of_range("cannot get value");
                }

                default:
                {
N
Niels 已提交
2528
                    if (m_it.generic_iterator == 0)
N
Niels 已提交
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
                    {
                        return *m_object;
                    }
                    else
                    {
                        throw std::out_of_range("cannot get value");
                    }
                }
            }
        }

        /// dereference the iterator
N
Niels 已提交
2541
        pointer operator->()
N
Niels 已提交
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    return &(m_it.object_iterator->second);
                }

                case (basic_json::value_t::array):
                {
                    return &*m_it.array_iterator;
                }

N
Niels 已提交
2555 2556 2557 2558 2559
                case (basic_json::value_t::null):
                {
                    throw std::out_of_range("cannot get value");
                }

N
Niels 已提交
2560 2561
                default:
                {
N
Niels 已提交
2562
                    if (m_it.generic_iterator == 0)
N
Niels 已提交
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
                    {
                        return m_object;
                    }
                    else
                    {
                        throw std::out_of_range("cannot get value");
                    }
                }
            }
        }

        /// post-increment (it++)
N
Niels 已提交
2575
        iterator operator++(int)
N
Niels 已提交
2576
        {
N
Niels 已提交
2577
            auto result = *this;
N
Niels 已提交
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594

            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    m_it.object_iterator++;
                    break;
                }

                case (basic_json::value_t::array):
                {
                    m_it.array_iterator++;
                    break;
                }

                default:
                {
N
Niels 已提交
2595
                    m_it.generic_iterator++;
N
Niels 已提交
2596 2597 2598 2599 2600 2601 2602 2603
                    break;
                }
            }

            return result;
        }

        /// pre-increment (++it)
N
Niels 已提交
2604
        iterator& operator++()
N
Niels 已提交
2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    ++m_it.object_iterator;
                    break;
                }

                case (basic_json::value_t::array):
                {
                    ++m_it.array_iterator;
                    break;
                }

                default:
                {
N
Niels 已提交
2622
                    ++m_it.generic_iterator;
N
Niels 已提交
2623 2624 2625 2626 2627 2628 2629 2630
                    break;
                }
            }

            return *this;
        }

        /// post-decrement (it--)
N
Niels 已提交
2631
        iterator operator--(int)
N
Niels 已提交
2632
        {
N
Niels 已提交
2633
            auto result = *this;
N
Niels 已提交
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650

            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    m_it.object_iterator--;
                    break;
                }

                case (basic_json::value_t::array):
                {
                    m_it.array_iterator--;
                    break;
                }

                default:
                {
N
Niels 已提交
2651
                    m_it.generic_iterator--;
N
Niels 已提交
2652 2653 2654 2655 2656 2657 2658 2659
                    break;
                }
            }

            return result;
        }

        /// pre-decrement (--it)
N
Niels 已提交
2660
        iterator& operator--()
N
Niels 已提交
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    --m_it.object_iterator;
                    break;
                }

                case (basic_json::value_t::array):
                {
                    --m_it.array_iterator;
                    break;
                }

                default:
                {
N
Niels 已提交
2678
                    --m_it.generic_iterator;
N
Niels 已提交
2679 2680 2681 2682 2683 2684 2685 2686
                    break;
                }
            }

            return *this;
        }

        /// comparison: equal
N
Niels 已提交
2687
        bool operator==(const iterator& other) const
N
Niels 已提交
2688
        {
N
Niels 已提交
2689 2690
            // if objects are not the same, the comparison is undefined
            if (m_object != other.m_object)
N
Niels 已提交
2691
            {
N
Niels 已提交
2692
                throw std::domain_error("cannot compare iterators of different containers");
N
Niels 已提交
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714
            }

            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    return (m_it.object_iterator == other.m_it.object_iterator);
                }

                case (basic_json::value_t::array):
                {
                    return (m_it.array_iterator == other.m_it.array_iterator);
                }

                default:
                {
                    return (m_it.generic_iterator == other.m_it.generic_iterator);
                }
            }
        }

        /// comparison: not equal
N
Niels 已提交
2715
        bool operator!=(const iterator& other) const
N
Niels 已提交
2716 2717 2718 2719
        {
            return not operator==(other);
        }

N
Niels 已提交
2720
        /// comparison: smaller
N
Niels 已提交
2721
        bool operator<(const iterator& other) const
N
Niels 已提交
2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
        {
            // if objects are not the same, the comparison is undefined
            if (m_object != other.m_object)
            {
                throw std::domain_error("cannot compare iterators of different containers");
            }

            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    throw std::domain_error("cannot use operator< for object iterators");
                }

                case (basic_json::value_t::array):
                {
                    return (m_it.array_iterator < other.m_it.array_iterator);
                }

                default:
                {
                    return (m_it.generic_iterator < other.m_it.generic_iterator);
                }
            }
        }

        /// comparison: less than or equal
N
Niels 已提交
2749
        bool operator<=(const iterator& other) const
N
Niels 已提交
2750 2751 2752 2753 2754
        {
            return not other.operator < (*this);
        }

        /// comparison: greater than
N
Niels 已提交
2755
        bool operator>(const iterator& other) const
N
Niels 已提交
2756 2757 2758 2759 2760
        {
            return not operator<=(other);
        }

        /// comparison: greater than or equal
N
Niels 已提交
2761
        bool operator>=(const iterator& other) const
N
Niels 已提交
2762 2763 2764 2765 2766
        {
            return not operator<(other);
        }

        /// add to iterator
N
Niels 已提交
2767
        iterator& operator+=(difference_type i)
N
Niels 已提交
2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    throw std::domain_error("cannot use operator+= for object iterators");
                }

                case (basic_json::value_t::array):
                {
                    m_it.array_iterator += i;
                    break;
                }

                default:
                {
                    m_it.generic_iterator += i;
                    break;
                }
            }

            return *this;
        }

        /// subtract from iterator
N
Niels 已提交
2793
        iterator& operator-=(difference_type i)
N
Niels 已提交
2794 2795 2796 2797 2798
        {
            return operator+=(-i);
        }

        /// add to iterator
N
Niels 已提交
2799
        iterator operator+(difference_type i)
N
Niels 已提交
2800 2801 2802 2803 2804 2805 2806
        {
            auto result = *this;
            result += i;
            return result;
        }

        /// subtract from iterator
N
Niels 已提交
2807
        iterator operator-(difference_type i)
N
Niels 已提交
2808 2809 2810 2811 2812 2813 2814
        {
            auto result = *this;
            result -= i;
            return result;
        }

        /// return difference
N
Niels 已提交
2815
        difference_type operator-(const iterator& other) const
N
Niels 已提交
2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    throw std::domain_error("cannot use operator- for object iterators");
                    return 0;
                }

                case (basic_json::value_t::array):
                {
                    return m_it.array_iterator - other.m_it.array_iterator;
                }

                default:
                {
                    return m_it.generic_iterator - other.m_it.generic_iterator;
                }
            }
        }

        /// access to successor
N
Niels 已提交
2838
        reference operator[](difference_type n)
N
Niels 已提交
2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    throw std::domain_error("cannot use operator[] for object iterators");
                }

                case (basic_json::value_t::array):
                {
                    return *(m_it.array_iterator + n);
                }

                case (basic_json::value_t::null):
                {
                    throw std::out_of_range("cannot get value");
                }

                default:
                {
                    if (m_it.generic_iterator == -n)
                    {
                        return *m_object;
                    }
                    else
                    {
                        throw std::out_of_range("cannot get value");
                    }
                }
            }
        }

2871
        /// return the key of an object iterator
N
Niels 已提交
2872
        typename object_t::key_type key() const
N
Niels 已提交
2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    return m_it.object_iterator->first;
                }

                default:
                {
                    throw std::domain_error("cannot use key() for non-object iterators");
                }
            }
        }

2888
        /// return the key of an iterator
N
Niels 已提交
2889
        reference value()
N
Niels 已提交
2890 2891 2892 2893
        {
            return operator*();
        }

N
Niels 已提交
2894 2895 2896 2897
      private:
        /// associated JSON instance
        pointer m_object = nullptr;
        /// the actual iterator of the associated instance
N
Niels 已提交
2898
        internal_iterator m_it;
N
Niels 已提交
2899 2900
    };

N
Niels 已提交
2901 2902
    /// a const random access iterator for the basic_json class
    class const_iterator : public std::iterator<std::random_access_iterator_tag, const basic_json>
N
Niels 已提交
2903
    {
2904 2905 2906
        // allow basic_json class to access m_it
        friend class basic_json;

N
Niels 已提交
2907 2908
      public:
        /// the type of the values when the iterator is dereferenced
N
Niels 已提交
2909
        using value_type = typename basic_json::value_type;
N
Niels 已提交
2910
        /// a type to represent differences between iterators
N
Niels 已提交
2911
        using difference_type = typename basic_json::difference_type;
N
Niels 已提交
2912
        /// defines a pointer to the type iterated over (value_type)
N
Niels 已提交
2913
        using pointer = typename basic_json::const_pointer;
N
Niels 已提交
2914
        /// defines a reference to the type iterated over (value_type)
N
Niels 已提交
2915
        using reference = typename basic_json::const_reference;
N
Niels 已提交
2916
        /// the category of the iterator
N
Niels 已提交
2917
        using iterator_category = std::bidirectional_iterator_tag;
N
Niels 已提交
2918

2919
        /// default constructor
N
Niels 已提交
2920
        const_iterator() = default;
2921

N
Niels 已提交
2922
        /// constructor for a given JSON instance
N
Niels 已提交
2923
        const_iterator(pointer object) noexcept : m_object(object)
N
Niels 已提交
2924 2925 2926 2927 2928
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
N
Niels 已提交
2929
                    m_it.object_iterator = typename object_t::iterator();
N
Niels 已提交
2930 2931 2932 2933
                    break;
                }
                case (basic_json::value_t::array):
                {
N
Niels 已提交
2934
                    m_it.array_iterator = typename array_t::iterator();
N
Niels 已提交
2935 2936 2937 2938
                    break;
                }
                default:
                {
N
Niels 已提交
2939
                    m_it.generic_iterator = -1;
N
Niels 已提交
2940 2941 2942 2943 2944
                    break;
                }
            }
        }

N
Niels 已提交
2945
        /// copy constructor given a nonconst iterator
N
Niels 已提交
2946
        const_iterator(const iterator& other) noexcept : m_object(other.m_object)
N
Niels 已提交
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    m_it.object_iterator = other.m_it.object_iterator;
                    break;
                }

                case (basic_json::value_t::array):
                {
                    m_it.array_iterator = other.m_it.array_iterator;
                    break;
                }

                default:
                {
                    m_it.generic_iterator = other.m_it.generic_iterator;
                    break;
                }
            }
        }
N
Niels 已提交
2969

N
Niels 已提交
2970
        /// copy constructor
N
Niels 已提交
2971
        const_iterator(const const_iterator& other) noexcept
N
Niels 已提交
2972 2973 2974
            : m_object(other.m_object), m_it(other.m_it)
        {}

N
Niels 已提交
2975
        /// copy assignment
N
Niels 已提交
2976
        const_iterator& operator=(const_iterator other) noexcept(
N
Niels 已提交
2977 2978
            std::is_nothrow_move_constructible<pointer>::value and
            std::is_nothrow_move_assignable<pointer>::value and
N
Niels 已提交
2979 2980
            std::is_nothrow_move_constructible<internal_iterator>::value and
            std::is_nothrow_move_assignable<internal_iterator>::value
N
Niels 已提交
2981 2982 2983 2984
        )
        {
            std::swap(m_object, other.m_object);
            std::swap(m_it, other.m_it);
N
Niels 已提交
2985 2986 2987
            return *this;
        }

N
Niels 已提交
2988
      private:
N
Niels 已提交
2989
        /// set the iterator to the first value
N
Niels 已提交
2990
        void set_begin() noexcept
N
Niels 已提交
2991 2992 2993 2994 2995
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
N
Niels 已提交
2996
                    m_it.object_iterator = m_object->m_value.object->begin();
N
Niels 已提交
2997 2998 2999 3000 3001
                    break;
                }

                case (basic_json::value_t::array):
                {
N
Niels 已提交
3002
                    m_it.array_iterator = m_object->m_value.array->begin();
N
Niels 已提交
3003 3004 3005 3006 3007
                    break;
                }

                case (basic_json::value_t::null):
                {
N
Niels 已提交
3008
                    // set to end so begin()==end() is true: null is empty
N
Niels 已提交
3009
                    m_it.generic_iterator = 1;
N
Niels 已提交
3010 3011 3012 3013 3014
                    break;
                }

                default:
                {
N
Niels 已提交
3015
                    m_it.generic_iterator = 0;
N
Niels 已提交
3016 3017 3018 3019 3020 3021
                    break;
                }
            }
        }

        /// set the iterator past the last value
N
Niels 已提交
3022
        void set_end() noexcept
N
Niels 已提交
3023 3024 3025 3026 3027
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
N
Niels 已提交
3028
                    m_it.object_iterator = m_object->m_value.object->end();
N
Niels 已提交
3029 3030 3031 3032 3033
                    break;
                }

                case (basic_json::value_t::array):
                {
N
Niels 已提交
3034
                    m_it.array_iterator = m_object->m_value.array->end();
N
Niels 已提交
3035 3036 3037 3038 3039
                    break;
                }

                default:
                {
N
Niels 已提交
3040
                    m_it.generic_iterator = 1;
N
Niels 已提交
3041 3042 3043 3044 3045
                    break;
                }
            }
        }

N
Niels 已提交
3046
      public:
N
Niels 已提交
3047
        /// return a reference to the value pointed to by the iterator
N
Niels 已提交
3048
        reference operator*() const
N
Niels 已提交
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    return m_it.object_iterator->second;
                }

                case (basic_json::value_t::array):
                {
                    return *m_it.array_iterator;
                }

                case (basic_json::value_t::null):
                {
                    throw std::out_of_range("cannot get value");
                }

                default:
                {
N
Niels 已提交
3069
                    if (m_it.generic_iterator == 0)
N
Niels 已提交
3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081
                    {
                        return *m_object;
                    }
                    else
                    {
                        throw std::out_of_range("cannot get value");
                    }
                }
            }
        }

        /// dereference the iterator
N
Niels 已提交
3082
        pointer operator->() const
N
Niels 已提交
3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    return &(m_it.object_iterator->second);
                }

                case (basic_json::value_t::array):
                {
                    return &*m_it.array_iterator;
                }

                default:
                {
N
Niels 已提交
3098
                    if (m_it.generic_iterator == 0)
N
Niels 已提交
3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
                    {
                        return m_object;
                    }
                    else
                    {
                        throw std::out_of_range("cannot get value");
                    }
                }
            }
        }

        /// post-increment (it++)
N
Niels 已提交
3111
        const_iterator operator++(int)
N
Niels 已提交
3112
        {
N
Niels 已提交
3113
            auto result = *this;
N
Niels 已提交
3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130

            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    m_it.object_iterator++;
                    break;
                }

                case (basic_json::value_t::array):
                {
                    m_it.array_iterator++;
                    break;
                }

                default:
                {
N
Niels 已提交
3131
                    m_it.generic_iterator++;
N
Niels 已提交
3132 3133 3134 3135 3136 3137 3138 3139
                    break;
                }
            }

            return result;
        }

        /// pre-increment (++it)
N
Niels 已提交
3140
        const_iterator& operator++()
N
Niels 已提交
3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    ++m_it.object_iterator;
                    break;
                }

                case (basic_json::value_t::array):
                {
                    ++m_it.array_iterator;
                    break;
                }

                default:
                {
N
Niels 已提交
3158
                    ++m_it.generic_iterator;
N
Niels 已提交
3159 3160 3161 3162 3163 3164 3165 3166
                    break;
                }
            }

            return *this;
        }

        /// post-decrement (it--)
N
Niels 已提交
3167
        const_iterator operator--(int)
N
Niels 已提交
3168
        {
N
Niels 已提交
3169
            auto result = *this;
N
Niels 已提交
3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186

            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    m_it.object_iterator--;
                    break;
                }

                case (basic_json::value_t::array):
                {
                    m_it.array_iterator--;
                    break;
                }

                default:
                {
N
Niels 已提交
3187
                    m_it.generic_iterator--;
N
Niels 已提交
3188 3189 3190 3191 3192 3193 3194 3195
                    break;
                }
            }

            return result;
        }

        /// pre-decrement (--it)
N
Niels 已提交
3196
        const_iterator& operator--()
N
Niels 已提交
3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    --m_it.object_iterator;
                    break;
                }

                case (basic_json::value_t::array):
                {
                    --m_it.array_iterator;
                    break;
                }

                default:
                {
N
Niels 已提交
3214
                    --m_it.generic_iterator;
N
Niels 已提交
3215 3216 3217 3218 3219 3220 3221 3222
                    break;
                }
            }

            return *this;
        }

        /// comparison: equal
N
Niels 已提交
3223
        bool operator==(const const_iterator& other) const
N
Niels 已提交
3224
        {
N
Niels 已提交
3225 3226
            // if objects are not the same, the comparison is undefined
            if (m_object != other.m_object)
N
Niels 已提交
3227
            {
N
Niels 已提交
3228
                throw std::domain_error("cannot compare iterators of different containers");
N
Niels 已提交
3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250
            }

            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    return (m_it.object_iterator == other.m_it.object_iterator);
                }

                case (basic_json::value_t::array):
                {
                    return (m_it.array_iterator == other.m_it.array_iterator);
                }

                default:
                {
                    return (m_it.generic_iterator == other.m_it.generic_iterator);
                }
            }
        }

        /// comparison: not equal
N
Niels 已提交
3251
        bool operator!=(const const_iterator& other) const
N
Niels 已提交
3252 3253 3254 3255
        {
            return not operator==(other);
        }

N
Niels 已提交
3256
        /// comparison: smaller
N
Niels 已提交
3257
        bool operator<(const const_iterator& other) const
N
Niels 已提交
3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
        {
            // if objects are not the same, the comparison is undefined
            if (m_object != other.m_object)
            {
                throw std::domain_error("cannot compare iterators of different containers");
            }

            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    throw std::domain_error("cannot use operator< for object iterators");
                }

                case (basic_json::value_t::array):
                {
                    return (m_it.array_iterator < other.m_it.array_iterator);
                }

                default:
                {
                    return (m_it.generic_iterator < other.m_it.generic_iterator);
                }
            }
        }

        /// comparison: less than or equal
N
Niels 已提交
3285
        bool operator<=(const const_iterator& other) const
N
Niels 已提交
3286 3287 3288 3289 3290
        {
            return not other.operator < (*this);
        }

        /// comparison: greater than
N
Niels 已提交
3291
        bool operator>(const const_iterator& other) const
N
Niels 已提交
3292 3293 3294 3295 3296
        {
            return not operator<=(other);
        }

        /// comparison: greater than or equal
N
Niels 已提交
3297
        bool operator>=(const const_iterator& other) const
N
Niels 已提交
3298 3299 3300 3301 3302
        {
            return not operator<(other);
        }

        /// add to iterator
N
Niels 已提交
3303
        const_iterator& operator+=(difference_type i)
N
Niels 已提交
3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    throw std::domain_error("cannot use operator+= for object iterators");
                }

                case (basic_json::value_t::array):
                {
                    m_it.array_iterator += i;
                    break;
                }

                default:
                {
                    m_it.generic_iterator += i;
                    break;
                }
            }

            return *this;
        }

        /// subtract from iterator
N
Niels 已提交
3329
        const_iterator& operator-=(difference_type i)
N
Niels 已提交
3330 3331 3332 3333 3334
        {
            return operator+=(-i);
        }

        /// add to iterator
N
Niels 已提交
3335
        const_iterator operator+(difference_type i)
N
Niels 已提交
3336 3337 3338 3339 3340 3341 3342
        {
            auto result = *this;
            result += i;
            return result;
        }

        /// subtract from iterator
N
Niels 已提交
3343
        const_iterator operator-(difference_type i)
N
Niels 已提交
3344 3345 3346 3347 3348 3349 3350
        {
            auto result = *this;
            result -= i;
            return result;
        }

        /// return difference
N
Niels 已提交
3351
        difference_type operator-(const const_iterator& other) const
N
Niels 已提交
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    throw std::domain_error("cannot use operator- for object iterators");
                }

                case (basic_json::value_t::array):
                {
                    return m_it.array_iterator - other.m_it.array_iterator;
                }

                default:
                {
                    return m_it.generic_iterator - other.m_it.generic_iterator;
                }
            }
        }

        /// access to successor
N
Niels 已提交
3373
        reference operator[](difference_type n) const
N
Niels 已提交
3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    throw std::domain_error("cannot use operator[] for object iterators");
                }

                case (basic_json::value_t::array):
                {
                    return *(m_it.array_iterator + n);
                }

                case (basic_json::value_t::null):
                {
                    throw std::out_of_range("cannot get value");
                }

                default:
                {
                    if (m_it.generic_iterator == -n)
                    {
                        return *m_object;
                    }
                    else
                    {
                        throw std::out_of_range("cannot get value");
                    }
                }
            }
        }

3406
        /// return the key of an object iterator
N
Niels 已提交
3407
        typename object_t::key_type key() const
N
Niels 已提交
3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    return m_it.object_iterator->first;
                }

                default:
                {
                    throw std::domain_error("cannot use key() for non-object iterators");
                }
            }
        }

3423
        /// return the value of an iterator
N
Niels 已提交
3424
        reference value() const
N
Niels 已提交
3425 3426 3427 3428
        {
            return operator*();
        }

N
Niels 已提交
3429 3430 3431 3432
      private:
        /// associated JSON instance
        pointer m_object = nullptr;
        /// the actual iterator of the associated instance
N
Niels 已提交
3433
        internal_iterator m_it;
N
Niels 已提交
3434 3435
    };

3436
    /// a reverse random access iterator for the basic_json class
N
Niels 已提交
3437
    class reverse_iterator : public std::reverse_iterator<typename basic_json::iterator>
3438 3439
    {
      public:
N
Niels 已提交
3440 3441 3442
        reverse_iterator(const typename
                         std::reverse_iterator<typename basic_json::iterator>::iterator_type&
                         it)
3443 3444 3445
            : std::reverse_iterator<basic_json::iterator>(it) {}

        /// return the key of an object iterator
N
Niels 已提交
3446
        typename object_t::key_type key() const
3447 3448 3449 3450 3451
        {
            return this->base().key();
        }

        /// return the value of an iterator
N
Niels 已提交
3452
        reference value() const
3453 3454 3455 3456 3457 3458
        {
            return this->base().operator * ();
        }
    };

    /// a const reverse random access iterator for the basic_json class
N
Niels 已提交
3459
    class const_reverse_iterator : public std::reverse_iterator<typename basic_json::const_iterator>
3460 3461
    {
      public:
N
Niels 已提交
3462 3463
        const_reverse_iterator(const typename
                               std::reverse_iterator<typename basic_json::const_iterator>::iterator_type& it)
3464 3465 3466
            : std::reverse_iterator<basic_json::const_iterator>(it) {}

        /// return the key of an object iterator
N
Niels 已提交
3467
        typename object_t::key_type key() const
3468 3469 3470 3471 3472
        {
            return this->base().key();
        }

        /// return the value of an iterator
N
Niels 已提交
3473
        const_reference value() const
3474 3475 3476 3477 3478
        {
            return this->base().operator * ();
        }
    };

N
Niels 已提交
3479

N
Niels 已提交
3480
  private:
N
Niels 已提交
3481 3482 3483
    //////////////////////
    // lexer and parser //
    //////////////////////
N
Niels 已提交
3484

N
Niels 已提交
3485 3486 3487 3488 3489 3490 3491
    /*!
    @brief lexical analysis

    This class organizes the lexical analysis during JSON deserialization. The
    core of it is a scanner generated by re2c <http://re2c.org> that processes
    a buffer and recognizes tokens according to RFC 7159 and ECMA-404.
    */
N
Niels 已提交
3492
    class lexer
N
Niels 已提交
3493
    {
N
Niels 已提交
3494
      public:
N
Niels 已提交
3495 3496 3497
        /// token types for the parser
        enum class token_type
        {
N
Niels 已提交
3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511
            uninitialized,    ///< indicating the scanner is uninitialized
            literal_true,     ///< the "true" literal
            literal_false,    ///< the "false" literal
            literal_null,     ///< the "null" literal
            value_string,     ///< a string - use get_string() for actual value
            value_number,     ///< a number - use get_number() for actual value
            begin_array,      ///< the character for array begin "["
            begin_object,     ///< the character for object begin "{"
            end_array,        ///< the character for array end "]"
            end_object,       ///< the character for object end "}"
            name_separator,   ///< the name separator ":"
            value_separator,  ///< the value separator ","
            parse_error,      ///< indicating a parse error
            end_of_input      ///< indicating the end of the input buffer
N
Niels 已提交
3512 3513
        };

N
Niels 已提交
3514
        /// the char type to use in the lexer
N
Niels 已提交
3515
        using lexer_char_t = unsigned char;
N
Niels 已提交
3516

N
Niels 已提交
3517
        /// constructor with a given buffer
N
Niels 已提交
3518
        lexer(const string_t& s) noexcept
N
Niels 已提交
3519
            : m_stream(nullptr), m_buffer(s)
N
Niels 已提交
3520
        {
N
Niels 已提交
3521
            m_content = reinterpret_cast<const lexer_char_t*>(s.c_str());
N
Niels 已提交
3522
            m_start = m_cursor = m_content;
N
Niels 已提交
3523
            m_limit = m_content + s.size();
N
Niels 已提交
3524
        }
N
Niels 已提交
3525
        lexer(std::istream* s) noexcept
N
Niels 已提交
3526 3527 3528 3529 3530 3531 3532
            : m_stream(s)
        {
            getline(*m_stream, m_buffer);
            m_content = reinterpret_cast<const lexer_char_t*>(m_buffer.c_str());
            m_start = m_cursor = m_content;
            m_limit = m_content + m_buffer.size();
        }
N
Niels 已提交
3533

N
Niels 已提交
3534
        /// default constructor
N
Niels 已提交
3535
        lexer() = default;
N
Niels 已提交
3536

N
Niels 已提交
3537 3538 3539
        /*!
        @brief create a string from a Unicode code point

N
Niels 已提交
3540 3541
        @param codepoint1  the code point (can be high surrogate)
        @param codepoint2  the code point (can be low surrogate or 0)
N
Niels 已提交
3542
        @return string representation of the code point
N
Niels 已提交
3543 3544
        @exception std::out_of_range if code point is >0x10ffff
        @exception std::invalid_argument if the low surrogate is invalid
N
Niels 已提交
3545 3546 3547

        @see <http://en.wikipedia.org/wiki/UTF-8#Sample_code>
        */
N
Niels 已提交
3548 3549
        static string_t to_unicode(const std::size_t codepoint1,
                                   const std::size_t codepoint2 = 0)
N
Niels 已提交
3550
        {
N
Niels 已提交
3551
            string_t result;
N
Niels 已提交
3552

N
Niels 已提交
3553
            // calculate the codepoint from the given code points
N
Niels 已提交
3554
            std::size_t codepoint = codepoint1;
N
Niels 已提交
3555 3556

            // check if codepoint1 is a high surrogate
N
Niels 已提交
3557 3558
            if (codepoint1 >= 0xD800 and codepoint1 <= 0xDBFF)
            {
N
Niels 已提交
3559
                // check if codepoint2 is a low surrogate
N
Niels 已提交
3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577
                if (codepoint2 >= 0xDC00 and codepoint2 <= 0xDFFF)
                {
                    codepoint =
                        // high surrogate occupies the most significant 22 bits
                        (codepoint1 << 10)
                        // low surrogate occupies the least significant 15 bits
                        + codepoint2
                        // there is still the 0xD800, 0xDC00 and 0x10000 noise
                        // in the result so we have to substract with:
                        // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
                        - 0x35FDC00;
                }
                else
                {
                    throw std::invalid_argument("missing or wrong low surrogate");
                }
            }

N
Niels 已提交
3578
            if (codepoint < 0x80)
N
Niels 已提交
3579
            {
N
Niels 已提交
3580
                // 1-byte characters: 0xxxxxxx (ASCII)
N
Niels 已提交
3581
                result.append(1, static_cast<typename string_t::value_type>(codepoint));
N
Niels 已提交
3582 3583 3584 3585
            }
            else if (codepoint <= 0x7ff)
            {
                // 2-byte characters: 110xxxxx 10xxxxxx
N
Niels 已提交
3586 3587
                result.append(1, static_cast<typename string_t::value_type>(0xC0 | ((codepoint >> 6) & 0x1F)));
                result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
N
Niels 已提交
3588 3589 3590 3591
            }
            else if (codepoint <= 0xffff)
            {
                // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
N
Niels 已提交
3592 3593 3594
                result.append(1, static_cast<typename string_t::value_type>(0xE0 | ((codepoint >> 12) & 0x0F)));
                result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
                result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
N
Niels 已提交
3595 3596 3597 3598
            }
            else if (codepoint <= 0x10ffff)
            {
                // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
N
Niels 已提交
3599 3600 3601 3602
                result.append(1, static_cast<typename string_t::value_type>(0xF0 | ((codepoint >> 18) & 0x07)));
                result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 12) & 0x3F)));
                result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
                result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
N
Niels 已提交
3603 3604 3605
            }
            else
            {
N
Niels 已提交
3606
                throw std::out_of_range("code points above 0x10FFFF are invalid");
N
Niels 已提交
3607 3608 3609 3610 3611
            }

            return result;
        }

N
Niels 已提交
3612
        /// return name of values of type token_type
N
Niels 已提交
3613
        static std::string token_type_name(token_type t) noexcept
N
cleanup  
Niels 已提交
3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642
        {
            switch (t)
            {
                case (token_type::uninitialized):
                    return "<uninitialized>";
                case (token_type::literal_true):
                    return "true literal";
                case (token_type::literal_false):
                    return "false literal";
                case (token_type::literal_null):
                    return "null literal";
                case (token_type::value_string):
                    return "string literal";
                case (token_type::value_number):
                    return "number literal";
                case (token_type::begin_array):
                    return "[";
                case (token_type::begin_object):
                    return "{";
                case (token_type::end_array):
                    return "]";
                case (token_type::end_object):
                    return "}";
                case (token_type::name_separator):
                    return ":";
                case (token_type::value_separator):
                    return ",";
                case (token_type::end_of_input):
                    return "<end of input>";
N
Niels 已提交
3643 3644
                default:
                    return "<parse error>";
N
cleanup  
Niels 已提交
3645 3646 3647
            }
        }

N
fixes  
Niels 已提交
3648 3649 3650 3651
        /*!
        This function implements a scanner for JSON. It is specified using
        regular expressions that try to follow RFC 7159 and ECMA-404 as close
        as possible. These regular expressions are then translated into a
N
Niels 已提交
3652 3653 3654
        deterministic finite automaton (DFA) by the tool re2c
        <http://re2c.org>. As a result, the translated code for this function
        consists of a large block of code with goto jumps.
N
fixes  
Niels 已提交
3655 3656 3657

        @return the class of the next token read from the buffer
        */
N
Niels 已提交
3658
        token_type scan() noexcept
N
Niels 已提交
3659
        {
N
cleanup  
Niels 已提交
3660
            // pointer for backtracking information
N
Niels 已提交
3661
            m_marker = nullptr;
N
Niels 已提交
3662 3663 3664 3665 3666

            // remember the begin of the token
            m_start = m_cursor;


N
Niels 已提交
3667 3668 3669 3670 3671
            {
                lexer_char_t yych;
                unsigned int yyaccept = 0;
                static const unsigned char yybm[] =
                {
N
Niels 已提交
3672 3673
                    0,   0,   0,   0,   0,   0,   0,   0,
                    0,  32,  32,   0,   0,  32,   0,   0,
N
Niels 已提交
3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    96,  64,   0,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    192, 192, 192, 192, 192, 192, 192, 192,
                    192, 192,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,   0,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                    64,  64,  64,  64,  64,  64,  64,  64,
                };

                if ((m_limit - m_cursor) < 5)
                {
N
Niels 已提交
3708 3709
                    yyfill();    // LCOV_EXCL_LINE;
                }
N
Niels 已提交
3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829
                yych = *m_cursor;
                if (yych <= '9')
                {
                    if (yych <= ' ')
                    {
                        if (yych <= '\n')
                        {
                            if (yych <= 0x00)
                            {
                                goto basic_json_parser_27;
                            }
                            if (yych <= 0x08)
                            {
                                goto basic_json_parser_29;
                            }
                            if (yych >= '\n')
                            {
                                goto basic_json_parser_4;
                            }
                        }
                        else
                        {
                            if (yych == '\r')
                            {
                                goto basic_json_parser_2;
                            }
                            if (yych <= 0x1F)
                            {
                                goto basic_json_parser_29;
                            }
                        }
                    }
                    else
                    {
                        if (yych <= ',')
                        {
                            if (yych == '"')
                            {
                                goto basic_json_parser_26;
                            }
                            if (yych <= '+')
                            {
                                goto basic_json_parser_29;
                            }
                            goto basic_json_parser_14;
                        }
                        else
                        {
                            if (yych <= '-')
                            {
                                goto basic_json_parser_22;
                            }
                            if (yych <= '/')
                            {
                                goto basic_json_parser_29;
                            }
                            if (yych <= '0')
                            {
                                goto basic_json_parser_23;
                            }
                            goto basic_json_parser_25;
                        }
                    }
                }
                else
                {
                    if (yych <= 'm')
                    {
                        if (yych <= '\\')
                        {
                            if (yych <= ':')
                            {
                                goto basic_json_parser_16;
                            }
                            if (yych == '[')
                            {
                                goto basic_json_parser_6;
                            }
                            goto basic_json_parser_29;
                        }
                        else
                        {
                            if (yych <= ']')
                            {
                                goto basic_json_parser_8;
                            }
                            if (yych == 'f')
                            {
                                goto basic_json_parser_21;
                            }
                            goto basic_json_parser_29;
                        }
                    }
                    else
                    {
                        if (yych <= 'z')
                        {
                            if (yych <= 'n')
                            {
                                goto basic_json_parser_18;
                            }
                            if (yych == 't')
                            {
                                goto basic_json_parser_20;
                            }
                            goto basic_json_parser_29;
                        }
                        else
                        {
                            if (yych <= '{')
                            {
                                goto basic_json_parser_10;
                            }
                            if (yych == '}')
                            {
                                goto basic_json_parser_12;
                            }
                            goto basic_json_parser_29;
                        }
                    }
N
Niels 已提交
3830 3831
                }
basic_json_parser_2:
N
Niels 已提交
3832 3833 3834
                ++m_cursor;
                yych = *m_cursor;
                goto basic_json_parser_5;
N
Niels 已提交
3835
basic_json_parser_3:
N
Niels 已提交
3836 3837 3838
                {
                    return scan();
                }
N
Niels 已提交
3839
basic_json_parser_4:
N
Niels 已提交
3840 3841 3842
                ++m_cursor;
                if (m_limit <= m_cursor)
                {
N
Niels 已提交
3843 3844
                    yyfill();    // LCOV_EXCL_LINE;
                }
N
Niels 已提交
3845
                yych = *m_cursor;
N
Niels 已提交
3846
basic_json_parser_5:
N
Niels 已提交
3847 3848 3849 3850 3851
                if (yybm[0 + yych] & 32)
                {
                    goto basic_json_parser_4;
                }
                goto basic_json_parser_3;
N
Niels 已提交
3852
basic_json_parser_6:
N
Niels 已提交
3853 3854 3855 3856
                ++m_cursor;
                {
                    return token_type::begin_array;
                }
N
Niels 已提交
3857
basic_json_parser_8:
N
Niels 已提交
3858 3859 3860 3861
                ++m_cursor;
                {
                    return token_type::end_array;
                }
N
Niels 已提交
3862
basic_json_parser_10:
N
Niels 已提交
3863 3864 3865 3866
                ++m_cursor;
                {
                    return token_type::begin_object;
                }
N
Niels 已提交
3867
basic_json_parser_12:
N
Niels 已提交
3868 3869 3870 3871
                ++m_cursor;
                {
                    return token_type::end_object;
                }
N
Niels 已提交
3872
basic_json_parser_14:
N
Niels 已提交
3873 3874 3875 3876
                ++m_cursor;
                {
                    return token_type::value_separator;
                }
N
Niels 已提交
3877
basic_json_parser_16:
N
Niels 已提交
3878 3879 3880 3881
                ++m_cursor;
                {
                    return token_type::name_separator;
                }
N
Niels 已提交
3882
basic_json_parser_18:
N
Niels 已提交
3883 3884 3885 3886 3887 3888
                yyaccept = 0;
                yych = *(m_marker = ++m_cursor);
                if (yych == 'u')
                {
                    goto basic_json_parser_59;
                }
N
Niels 已提交
3889
basic_json_parser_19:
N
Niels 已提交
3890 3891 3892
                {
                    return token_type::parse_error;
                }
N
Niels 已提交
3893
basic_json_parser_20:
N
Niels 已提交
3894 3895 3896 3897 3898 3899 3900
                yyaccept = 0;
                yych = *(m_marker = ++m_cursor);
                if (yych == 'r')
                {
                    goto basic_json_parser_55;
                }
                goto basic_json_parser_19;
N
Niels 已提交
3901
basic_json_parser_21:
N
Niels 已提交
3902 3903 3904 3905 3906 3907 3908
                yyaccept = 0;
                yych = *(m_marker = ++m_cursor);
                if (yych == 'a')
                {
                    goto basic_json_parser_50;
                }
                goto basic_json_parser_19;
N
Niels 已提交
3909
basic_json_parser_22:
N
Niels 已提交
3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923
                yych = *++m_cursor;
                if (yych <= '/')
                {
                    goto basic_json_parser_19;
                }
                if (yych <= '0')
                {
                    goto basic_json_parser_49;
                }
                if (yych <= '9')
                {
                    goto basic_json_parser_40;
                }
                goto basic_json_parser_19;
N
Niels 已提交
3924
basic_json_parser_23:
N
Niels 已提交
3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944
                yyaccept = 1;
                yych = *(m_marker = ++m_cursor);
                if (yych <= 'D')
                {
                    if (yych == '.')
                    {
                        goto basic_json_parser_42;
                    }
                }
                else
                {
                    if (yych <= 'E')
                    {
                        goto basic_json_parser_43;
                    }
                    if (yych == 'e')
                    {
                        goto basic_json_parser_43;
                    }
                }
N
Niels 已提交
3945
basic_json_parser_24:
N
Niels 已提交
3946 3947 3948
                {
                    return token_type::value_number;
                }
N
Niels 已提交
3949
basic_json_parser_25:
N
Niels 已提交
3950 3951 3952
                yyaccept = 1;
                yych = *(m_marker = ++m_cursor);
                goto basic_json_parser_41;
N
Niels 已提交
3953
basic_json_parser_26:
N
Niels 已提交
3954 3955
                yyaccept = 0;
                yych = *(m_marker = ++m_cursor);
N
Niels 已提交
3956
                if (yych <= 0x0F)
N
Niels 已提交
3957 3958 3959
                {
                    goto basic_json_parser_19;
                }
N
Niels 已提交
3960
                goto basic_json_parser_31;
N
Niels 已提交
3961
basic_json_parser_27:
N
Niels 已提交
3962 3963 3964 3965
                ++m_cursor;
                {
                    return token_type::end_of_input;
                }
N
Niels 已提交
3966
basic_json_parser_29:
N
Niels 已提交
3967 3968
                yych = *++m_cursor;
                goto basic_json_parser_19;
N
Niels 已提交
3969
basic_json_parser_30:
N
Niels 已提交
3970 3971 3972
                ++m_cursor;
                if (m_limit <= m_cursor)
                {
N
Niels 已提交
3973 3974
                    yyfill();    // LCOV_EXCL_LINE;
                }
N
Niels 已提交
3975
                yych = *m_cursor;
N
Niels 已提交
3976
basic_json_parser_31:
N
Niels 已提交
3977 3978
                if (yybm[0 + yych] & 64)
                {
N
Niels 已提交
3979
                    goto basic_json_parser_30;
N
Niels 已提交
3980
                }
N
Niels 已提交
3981
                if (yych <= 0x0F)
N
Niels 已提交
3982
                {
N
Niels 已提交
3983
                    goto basic_json_parser_32;
N
Niels 已提交
3984
                }
N
Niels 已提交
3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003
                if (yych <= '"')
                {
                    goto basic_json_parser_34;
                }
                goto basic_json_parser_33;
basic_json_parser_32:
                m_cursor = m_marker;
                if (yyaccept == 0)
                {
                    goto basic_json_parser_19;
                }
                else
                {
                    goto basic_json_parser_24;
                }
basic_json_parser_33:
                ++m_cursor;
                if (m_limit <= m_cursor)
                {
N
Niels 已提交
4004 4005
                    yyfill();    // LCOV_EXCL_LINE;
                }
N
Niels 已提交
4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078
                yych = *m_cursor;
                if (yych <= 'e')
                {
                    if (yych <= '/')
                    {
                        if (yych == '"')
                        {
                            goto basic_json_parser_30;
                        }
                        if (yych <= '.')
                        {
                            goto basic_json_parser_32;
                        }
                        goto basic_json_parser_30;
                    }
                    else
                    {
                        if (yych <= '\\')
                        {
                            if (yych <= '[')
                            {
                                goto basic_json_parser_32;
                            }
                            goto basic_json_parser_30;
                        }
                        else
                        {
                            if (yych == 'b')
                            {
                                goto basic_json_parser_30;
                            }
                            goto basic_json_parser_32;
                        }
                    }
                }
                else
                {
                    if (yych <= 'q')
                    {
                        if (yych <= 'f')
                        {
                            goto basic_json_parser_30;
                        }
                        if (yych == 'n')
                        {
                            goto basic_json_parser_30;
                        }
                        goto basic_json_parser_32;
                    }
                    else
                    {
                        if (yych <= 's')
                        {
                            if (yych <= 'r')
                            {
                                goto basic_json_parser_30;
                            }
                            goto basic_json_parser_32;
                        }
                        else
                        {
                            if (yych <= 't')
                            {
                                goto basic_json_parser_30;
                            }
                            if (yych <= 'u')
                            {
                                goto basic_json_parser_36;
                            }
                            goto basic_json_parser_32;
                        }
                    }
                }
N
Niels 已提交
4079
basic_json_parser_34:
N
Niels 已提交
4080 4081 4082 4083
                ++m_cursor;
                {
                    return token_type::value_string;
                }
N
Niels 已提交
4084
basic_json_parser_36:
N
Niels 已提交
4085 4086 4087
                ++m_cursor;
                if (m_limit <= m_cursor)
                {
N
Niels 已提交
4088 4089
                    yyfill();    // LCOV_EXCL_LINE;
                }
N
Niels 已提交
4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116
                yych = *m_cursor;
                if (yych <= '@')
                {
                    if (yych <= '/')
                    {
                        goto basic_json_parser_32;
                    }
                    if (yych >= ':')
                    {
                        goto basic_json_parser_32;
                    }
                }
                else
                {
                    if (yych <= 'F')
                    {
                        goto basic_json_parser_37;
                    }
                    if (yych <= '`')
                    {
                        goto basic_json_parser_32;
                    }
                    if (yych >= 'g')
                    {
                        goto basic_json_parser_32;
                    }
                }
N
Niels 已提交
4117
basic_json_parser_37:
N
Niels 已提交
4118 4119 4120
                ++m_cursor;
                if (m_limit <= m_cursor)
                {
N
Niels 已提交
4121 4122
                    yyfill();    // LCOV_EXCL_LINE;
                }
N
Niels 已提交
4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149
                yych = *m_cursor;
                if (yych <= '@')
                {
                    if (yych <= '/')
                    {
                        goto basic_json_parser_32;
                    }
                    if (yych >= ':')
                    {
                        goto basic_json_parser_32;
                    }
                }
                else
                {
                    if (yych <= 'F')
                    {
                        goto basic_json_parser_38;
                    }
                    if (yych <= '`')
                    {
                        goto basic_json_parser_32;
                    }
                    if (yych >= 'g')
                    {
                        goto basic_json_parser_32;
                    }
                }
N
Niels 已提交
4150
basic_json_parser_38:
N
Niels 已提交
4151 4152 4153
                ++m_cursor;
                if (m_limit <= m_cursor)
                {
N
Niels 已提交
4154 4155
                    yyfill();    // LCOV_EXCL_LINE;
                }
N
Niels 已提交
4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182
                yych = *m_cursor;
                if (yych <= '@')
                {
                    if (yych <= '/')
                    {
                        goto basic_json_parser_32;
                    }
                    if (yych >= ':')
                    {
                        goto basic_json_parser_32;
                    }
                }
                else
                {
                    if (yych <= 'F')
                    {
                        goto basic_json_parser_39;
                    }
                    if (yych <= '`')
                    {
                        goto basic_json_parser_32;
                    }
                    if (yych >= 'g')
                    {
                        goto basic_json_parser_32;
                    }
                }
N
Niels 已提交
4183
basic_json_parser_39:
N
Niels 已提交
4184 4185 4186
                ++m_cursor;
                if (m_limit <= m_cursor)
                {
N
Niels 已提交
4187 4188
                    yyfill();    // LCOV_EXCL_LINE;
                }
N
Niels 已提交
4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217
                yych = *m_cursor;
                if (yych <= '@')
                {
                    if (yych <= '/')
                    {
                        goto basic_json_parser_32;
                    }
                    if (yych <= '9')
                    {
                        goto basic_json_parser_30;
                    }
                    goto basic_json_parser_32;
                }
                else
                {
                    if (yych <= 'F')
                    {
                        goto basic_json_parser_30;
                    }
                    if (yych <= '`')
                    {
                        goto basic_json_parser_32;
                    }
                    if (yych <= 'f')
                    {
                        goto basic_json_parser_30;
                    }
                    goto basic_json_parser_32;
                }
N
Niels 已提交
4218
basic_json_parser_40:
N
Niels 已提交
4219 4220 4221 4222
                yyaccept = 1;
                m_marker = ++m_cursor;
                if ((m_limit - m_cursor) < 3)
                {
N
Niels 已提交
4223 4224
                    yyfill();    // LCOV_EXCL_LINE;
                }
N
Niels 已提交
4225
                yych = *m_cursor;
N
Niels 已提交
4226
basic_json_parser_41:
N
Niels 已提交
4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249
                if (yybm[0 + yych] & 128)
                {
                    goto basic_json_parser_40;
                }
                if (yych <= 'D')
                {
                    if (yych != '.')
                    {
                        goto basic_json_parser_24;
                    }
                }
                else
                {
                    if (yych <= 'E')
                    {
                        goto basic_json_parser_43;
                    }
                    if (yych == 'e')
                    {
                        goto basic_json_parser_43;
                    }
                    goto basic_json_parser_24;
                }
N
Niels 已提交
4250
basic_json_parser_42:
N
Niels 已提交
4251 4252 4253 4254 4255 4256 4257 4258 4259 4260
                yych = *++m_cursor;
                if (yych <= '/')
                {
                    goto basic_json_parser_32;
                }
                if (yych <= '9')
                {
                    goto basic_json_parser_47;
                }
                goto basic_json_parser_32;
N
Niels 已提交
4261
basic_json_parser_43:
N
Niels 已提交
4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285
                yych = *++m_cursor;
                if (yych <= ',')
                {
                    if (yych != '+')
                    {
                        goto basic_json_parser_32;
                    }
                }
                else
                {
                    if (yych <= '-')
                    {
                        goto basic_json_parser_44;
                    }
                    if (yych <= '/')
                    {
                        goto basic_json_parser_32;
                    }
                    if (yych <= '9')
                    {
                        goto basic_json_parser_45;
                    }
                    goto basic_json_parser_32;
                }
N
Niels 已提交
4286
basic_json_parser_44:
N
Niels 已提交
4287 4288 4289 4290 4291 4292 4293 4294 4295
                yych = *++m_cursor;
                if (yych <= '/')
                {
                    goto basic_json_parser_32;
                }
                if (yych >= ':')
                {
                    goto basic_json_parser_32;
                }
N
Niels 已提交
4296
basic_json_parser_45:
N
Niels 已提交
4297 4298 4299
                ++m_cursor;
                if (m_limit <= m_cursor)
                {
N
Niels 已提交
4300 4301
                    yyfill();    // LCOV_EXCL_LINE;
                }
N
Niels 已提交
4302 4303 4304 4305 4306 4307 4308 4309 4310 4311
                yych = *m_cursor;
                if (yych <= '/')
                {
                    goto basic_json_parser_24;
                }
                if (yych <= '9')
                {
                    goto basic_json_parser_45;
                }
                goto basic_json_parser_24;
N
Niels 已提交
4312
basic_json_parser_47:
N
Niels 已提交
4313 4314 4315 4316
                yyaccept = 1;
                m_marker = ++m_cursor;
                if ((m_limit - m_cursor) < 3)
                {
N
Niels 已提交
4317 4318
                    yyfill();    // LCOV_EXCL_LINE;
                }
N
Niels 已提交
4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343
                yych = *m_cursor;
                if (yych <= 'D')
                {
                    if (yych <= '/')
                    {
                        goto basic_json_parser_24;
                    }
                    if (yych <= '9')
                    {
                        goto basic_json_parser_47;
                    }
                    goto basic_json_parser_24;
                }
                else
                {
                    if (yych <= 'E')
                    {
                        goto basic_json_parser_43;
                    }
                    if (yych == 'e')
                    {
                        goto basic_json_parser_43;
                    }
                    goto basic_json_parser_24;
                }
N
Niels 已提交
4344
basic_json_parser_49:
N
Niels 已提交
4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366
                yyaccept = 1;
                yych = *(m_marker = ++m_cursor);
                if (yych <= 'D')
                {
                    if (yych == '.')
                    {
                        goto basic_json_parser_42;
                    }
                    goto basic_json_parser_24;
                }
                else
                {
                    if (yych <= 'E')
                    {
                        goto basic_json_parser_43;
                    }
                    if (yych == 'e')
                    {
                        goto basic_json_parser_43;
                    }
                    goto basic_json_parser_24;
                }
N
Niels 已提交
4367
basic_json_parser_50:
N
Niels 已提交
4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386
                yych = *++m_cursor;
                if (yych != 'l')
                {
                    goto basic_json_parser_32;
                }
                yych = *++m_cursor;
                if (yych != 's')
                {
                    goto basic_json_parser_32;
                }
                yych = *++m_cursor;
                if (yych != 'e')
                {
                    goto basic_json_parser_32;
                }
                ++m_cursor;
                {
                    return token_type::literal_false;
                }
N
Niels 已提交
4387
basic_json_parser_55:
N
Niels 已提交
4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401
                yych = *++m_cursor;
                if (yych != 'u')
                {
                    goto basic_json_parser_32;
                }
                yych = *++m_cursor;
                if (yych != 'e')
                {
                    goto basic_json_parser_32;
                }
                ++m_cursor;
                {
                    return token_type::literal_true;
                }
N
Niels 已提交
4402
basic_json_parser_59:
N
Niels 已提交
4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417
                yych = *++m_cursor;
                if (yych != 'l')
                {
                    goto basic_json_parser_32;
                }
                yych = *++m_cursor;
                if (yych != 'l')
                {
                    goto basic_json_parser_32;
                }
                ++m_cursor;
                {
                    return token_type::literal_null;
                }
            }
N
Niels 已提交
4418

N
Niels 已提交
4419 4420 4421 4422

        }

        /// append data from the stream to the internal buffer
N
Niels 已提交
4423
        void yyfill() noexcept
N
Niels 已提交
4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436
        {
            if (not m_stream or not * m_stream)
            {
                return;
            }

            const ssize_t offset_start = m_start - m_content;
            const ssize_t offset_marker = m_marker - m_start;
            const ssize_t offset_cursor = m_cursor - m_start;

            m_buffer.erase(0, static_cast<size_t>(offset_start));
            std::string line;
            std::getline(*m_stream, line);
N
Niels 已提交
4437
            m_buffer += "\n" + line; // add line with newline symbol
N
Niels 已提交
4438 4439 4440 4441 4442 4443

            m_content = reinterpret_cast<const lexer_char_t*>(m_buffer.c_str());
            m_start  = m_content;
            m_marker = m_start + offset_marker;
            m_cursor = m_start + offset_cursor;
            m_limit  = m_start + m_buffer.size() - 1;
N
Niels 已提交
4444 4445
        }

N
Niels 已提交
4446
        /// return string representation of last read token
N
Niels 已提交
4447
        string_t get_token() const noexcept
N
Niels 已提交
4448
        {
N
Niels 已提交
4449 4450
            return string_t(reinterpret_cast<typename string_t::const_pointer>(m_start),
                            static_cast<size_t>(m_cursor - m_start));
N
Niels 已提交
4451 4452 4453
        }

        /*!
N
Niels 已提交
4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469
        @brief return string value for string tokens

        The function iterates the characters between the opening and closing
        quotes of the string value. The complete string is the range
        [m_start,m_cursor). Consequently, we iterate from m_start+1 to
        m_cursor-1.

        We differentiate two cases:

        1. Escaped characters. In this case, a new character is constructed
           according to the nature of the escape. Some escapes create new
           characters (e.g., @c "\\n" is replaced by @c "\n"), some are copied
           as is (e.g., @c "\\\\"). Furthermore, Unicode escapes of the shape
           @c "\\uxxxx" need special care. In this case, to_unicode takes care
           of the construction of the values.
        2. Unescaped characters are copied as is.
N
Niels 已提交
4470 4471

        @return string value of current token without opening and closing quotes
N
Niels 已提交
4472
        @exception std::out_of_range if to_unicode fails
N
Niels 已提交
4473
        */
N
Niels 已提交
4474
        string_t get_string() const
N
Niels 已提交
4475
        {
N
Niels 已提交
4476
            string_t result;
N
Niels 已提交
4477 4478 4479
            result.reserve(static_cast<size_t>(m_cursor - m_start - 2));

            // iterate the result between the quotes
N
Niels 已提交
4480
            for (const lexer_char_t* i = m_start + 1; i < m_cursor - 1; ++i)
N
Niels 已提交
4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517
            {
                // process escaped characters
                if (*i == '\\')
                {
                    // read next character
                    ++i;

                    switch (*i)
                    {
                        // the default escapes
                        case 't':
                        {
                            result += "\t";
                            break;
                        }
                        case 'b':
                        {
                            result += "\b";
                            break;
                        }
                        case 'f':
                        {
                            result += "\f";
                            break;
                        }
                        case 'n':
                        {
                            result += "\n";
                            break;
                        }
                        case 'r':
                        {
                            result += "\r";
                            break;
                        }
                        case '\\':
                        {
N
Niels 已提交
4518
                            result += "\\";
N
Niels 已提交
4519 4520 4521 4522
                            break;
                        }
                        case '/':
                        {
N
Niels 已提交
4523
                            result += "/";
N
Niels 已提交
4524 4525 4526 4527
                            break;
                        }
                        case '"':
                        {
N
Niels 已提交
4528
                            result += "\"";
N
Niels 已提交
4529 4530 4531 4532 4533 4534
                            break;
                        }

                        // unicode
                        case 'u':
                        {
N
Niels 已提交
4535
                            // get code xxxx from uxxxx
N
Niels 已提交
4536 4537
                            auto codepoint = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>(i + 1),
                                                          4).c_str(), nullptr, 16);
N
Niels 已提交
4538

N
Niels 已提交
4539
                            // check if codepoint is a high surrogate
N
Niels 已提交
4540 4541
                            if (codepoint >= 0xD800 and codepoint <= 0xDBFF)
                            {
N
Niels 已提交
4542
                                // make sure there is a subsequent unicode
N
Niels 已提交
4543
                                if ((i + 6 >= m_limit) or * (i + 5) != '\\' or * (i + 6) != 'u')
N
Niels 已提交
4544 4545 4546 4547
                                {
                                    throw std::invalid_argument("missing low surrogate");
                                }

N
Niels 已提交
4548
                                // get code yyyy from uxxxx\uyyyy
N
Niels 已提交
4549 4550
                                auto codepoint2 = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>
                                                               (i + 7), 4).c_str(), nullptr, 16);
N
Niels 已提交
4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561
                                result += to_unicode(codepoint, codepoint2);
                                // skip the next 11 characters (xxxx\uyyyy)
                                i += 11;
                            }
                            else
                            {
                                // add unicode character(s)
                                result += to_unicode(codepoint);
                                // skip the next four characters (xxxx)
                                i += 4;
                            }
N
Niels 已提交
4562 4563 4564 4565 4566 4567 4568 4569
                            break;
                        }
                    }
                }
                else
                {
                    // all other characters are just copied to the end of the
                    // string
N
Niels 已提交
4570
                    result.append(1, static_cast<typename string_t::value_type>(*i));
N
Niels 已提交
4571 4572 4573 4574
                }
            }

            return result;
N
Niels 已提交
4575 4576
        }

N
Niels 已提交
4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593
        /*!
        @brief return number value for number tokens

        This function translates the last token into a floating point number.
        The pointer m_begin points to the beginning of the parsed number. We
        pass this pointer to std::strtod which sets endptr to the first
        character past the converted number. If this pointer is not the same as
        m_cursor, then either more or less characters have been used during the
        comparison. This can happen for inputs like "01" which will be treated
        like number 0 followed by number 1.

        @return the result of the number conversion or NAN if the conversion
        read past the current token. The latter case needs to be treated by the
        caller function.

        @exception std::range_error if passed value is out of range
        */
N
Niels 已提交
4594
        long double get_number() const
N
Niels 已提交
4595 4596
        {
            // conversion
N
Niels 已提交
4597
            typename string_t::value_type* endptr;
N
Niels 已提交
4598 4599
            const auto float_val = std::strtold(reinterpret_cast<typename string_t::const_pointer>(m_start),
                                                &endptr);
N
Niels 已提交
4600

N
Niels 已提交
4601 4602
            // return float_val if the whole number was translated and NAN
            // otherwise
N
Niels 已提交
4603
            return (reinterpret_cast<lexer_char_t*>(endptr) == m_cursor) ? float_val : NAN;
N
Niels 已提交
4604 4605 4606
        }

      private:
N
Niels 已提交
4607 4608
        /// optional input stream
        std::istream* m_stream;
N
fixes  
Niels 已提交
4609
        /// the buffer
N
Niels 已提交
4610 4611
        string_t m_buffer;
        /// the buffer pointer
N
Niels 已提交
4612
        const lexer_char_t* m_content = nullptr;
N
Niels 已提交
4613
        /// pointer to the beginning of the current symbol
N
Niels 已提交
4614
        const lexer_char_t* m_start = nullptr;
N
Niels 已提交
4615 4616
        /// pointer for backtracking information
        const lexer_char_t* m_marker = nullptr;
N
fixes  
Niels 已提交
4617
        /// pointer to the current symbol
N
Niels 已提交
4618
        const lexer_char_t* m_cursor = nullptr;
N
fixes  
Niels 已提交
4619
        /// pointer to the end of the buffer
N
Niels 已提交
4620
        const lexer_char_t* m_limit = nullptr;
N
Niels 已提交
4621 4622
    };

N
Niels 已提交
4623 4624 4625
    /*!
    @brief syntax analysis
    */
N
Niels 已提交
4626 4627 4628 4629
    class parser
    {
      public:
        /// constructor for strings
N
Niels 已提交
4630
        parser(const string_t& s, parser_callback_t cb = nullptr) : callback(cb), m_lexer(s)
N
Niels 已提交
4631 4632 4633 4634 4635 4636
        {
            // read first token
            get_token();
        }

        /// a parser reading from an input stream
N
Niels 已提交
4637
        parser(std::istream& _is, parser_callback_t cb = nullptr) : callback(cb),
N
Niels 已提交
4638
            m_lexer(&_is)
N
Niels 已提交
4639 4640 4641 4642 4643
        {
            // read first token
            get_token();
        }

N
Niels 已提交
4644
        /// public parser interface
N
Niels 已提交
4645
        basic_json parse()
N
Niels 已提交
4646
        {
N
Niels 已提交
4647
            basic_json result = parse_internal(true);
N
Niels 已提交
4648 4649 4650 4651 4652 4653 4654 4655

            expect(lexer::token_type::end_of_input);

            return result;
        }

      private:
        /// the actual parser
N
Niels 已提交
4656
        basic_json parse_internal(bool keep)
N
Niels 已提交
4657
        {
N
Niels 已提交
4658 4659
            auto result = basic_json(value_t::discarded);

N
Niels 已提交
4660 4661 4662 4663
            switch (last_token)
            {
                case (lexer::token_type::begin_object):
                {
N
Niels 已提交
4664
                    if (keep and (not callback or (keep = callback(depth++, parse_event_t::object_start, result))))
N
Niels 已提交
4665 4666
                    {
                        // explicitly set result to object to cope with {}
N
Niels 已提交
4667 4668
                        result.m_type = value_t::object;
                        result.m_value = json_value(value_t::object);
N
Niels 已提交
4669
                    }
N
Niels 已提交
4670 4671 4672 4673 4674 4675 4676

                    // read next token
                    get_token();

                    // closing } -> we are done
                    if (last_token == lexer::token_type::end_object)
                    {
N
Niels 已提交
4677
                        get_token();
N
Niels 已提交
4678
                        if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
N
Niels 已提交
4679 4680 4681
                        {
                            result = basic_json(value_t::discarded);
                        }
N
Niels 已提交
4682
                        return result;
N
Niels 已提交
4683 4684
                    }

N
Niels 已提交
4685 4686 4687
                    // no comma is expected here
                    unexpect(lexer::token_type::value_separator);

N
Niels 已提交
4688 4689 4690
                    // otherwise: parse key-value pairs
                    do
                    {
N
Niels 已提交
4691 4692 4693 4694 4695 4696
                        // ugly, but could be fixed with loop reorganization
                        if (last_token == lexer::token_type::value_separator)
                        {
                            get_token();
                        }

N
Niels 已提交
4697 4698 4699 4700
                        // store key
                        expect(lexer::token_type::value_string);
                        const auto key = m_lexer.get_string();

N
Niels 已提交
4701 4702 4703
                        bool keep_tag = false;
                        if (keep)
                        {
N
Niels 已提交
4704
                            keep_tag = callback ? callback(depth, parse_event_t::key, basic_json(key)) : true;
N
Niels 已提交
4705 4706
                        }

N
Niels 已提交
4707 4708 4709 4710
                        // parse separator (:)
                        get_token();
                        expect(lexer::token_type::name_separator);

4711
                        // parse and add value
N
Niels 已提交
4712
                        get_token();
N
Niels 已提交
4713 4714 4715
                        auto value = parse_internal(keep);
                        if (keep and keep_tag and not value.is_discarded())
                        {
N
Niels 已提交
4716
                            result[key] = std::move(value);
N
Niels 已提交
4717
                        }
N
Niels 已提交
4718
                    }
N
Niels 已提交
4719
                    while (last_token == lexer::token_type::value_separator);
N
Niels 已提交
4720 4721 4722

                    // closing }
                    expect(lexer::token_type::end_object);
N
Niels 已提交
4723
                    get_token();
N
Niels 已提交
4724
                    if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
N
Niels 已提交
4725 4726 4727
                    {
                        result = basic_json(value_t::discarded);
                    }
N
Niels 已提交
4728 4729

                    return result;
N
Niels 已提交
4730 4731 4732 4733
                }

                case (lexer::token_type::begin_array):
                {
N
Niels 已提交
4734
                    if (keep and (not callback or (keep = callback(depth++, parse_event_t::array_start, result))))
N
Niels 已提交
4735 4736
                    {
                        // explicitly set result to object to cope with []
N
Niels 已提交
4737 4738
                        result.m_type = value_t::array;
                        result.m_value = json_value(value_t::array);
N
Niels 已提交
4739
                    }
N
Niels 已提交
4740 4741 4742 4743 4744 4745 4746

                    // read next token
                    get_token();

                    // closing ] -> we are done
                    if (last_token == lexer::token_type::end_array)
                    {
N
Niels 已提交
4747
                        get_token();
N
Niels 已提交
4748
                        if (callback and not callback(--depth, parse_event_t::array_end, result))
N
Niels 已提交
4749 4750 4751
                        {
                            result = basic_json(value_t::discarded);
                        }
N
Niels 已提交
4752
                        return result;
N
Niels 已提交
4753 4754
                    }

N
Niels 已提交
4755 4756 4757
                    // no comma is expected here
                    unexpect(lexer::token_type::value_separator);

N
Niels 已提交
4758 4759 4760
                    // otherwise: parse values
                    do
                    {
N
Niels 已提交
4761 4762 4763 4764 4765
                        // ugly, but could be fixed with loop reorganization
                        if (last_token == lexer::token_type::value_separator)
                        {
                            get_token();
                        }
N
Niels 已提交
4766

N
Niels 已提交
4767 4768 4769 4770
                        // parse value
                        auto value = parse_internal(keep);
                        if (keep and not value.is_discarded())
                        {
N
Niels 已提交
4771
                            result.push_back(std::move(value));
N
Niels 已提交
4772
                        }
N
Niels 已提交
4773
                    }
N
Niels 已提交
4774
                    while (last_token == lexer::token_type::value_separator);
N
Niels 已提交
4775 4776 4777

                    // closing ]
                    expect(lexer::token_type::end_array);
N
Niels 已提交
4778
                    get_token();
N
Niels 已提交
4779
                    if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
N
Niels 已提交
4780 4781 4782
                    {
                        result = basic_json(value_t::discarded);
                    }
N
Niels 已提交
4783 4784

                    return result;
N
Niels 已提交
4785 4786 4787 4788
                }

                case (lexer::token_type::literal_null):
                {
N
Niels 已提交
4789
                    get_token();
N
Niels 已提交
4790
                    result.m_type = value_t::null;
N
Niels 已提交
4791
                    break;
N
Niels 已提交
4792 4793 4794 4795
                }

                case (lexer::token_type::value_string):
                {
N
Niels 已提交
4796
                    const auto s = m_lexer.get_string();
N
Niels 已提交
4797
                    get_token();
N
Niels 已提交
4798 4799
                    result = basic_json(s);
                    break;
N
Niels 已提交
4800 4801 4802 4803
                }

                case (lexer::token_type::literal_true):
                {
N
Niels 已提交
4804
                    get_token();
N
Niels 已提交
4805 4806
                    result.m_type = value_t::boolean;
                    result.m_value = true;
N
Niels 已提交
4807
                    break;
N
Niels 已提交
4808 4809 4810 4811
                }

                case (lexer::token_type::literal_false):
                {
N
Niels 已提交
4812
                    get_token();
N
Niels 已提交
4813 4814
                    result.m_type = value_t::boolean;
                    result.m_value = false;
N
Niels 已提交
4815
                    break;
N
Niels 已提交
4816 4817 4818 4819 4820 4821
                }

                case (lexer::token_type::value_number):
                {
                    auto float_val = m_lexer.get_number();

N
Niels 已提交
4822 4823
                    // NAN is returned if token could not be translated
                    // completely
N
Niels 已提交
4824 4825 4826
                    if (std::isnan(float_val))
                    {
                        throw std::invalid_argument(std::string("parse error - ") +
N
Niels 已提交
4827
                                                    m_lexer.get_token() + " is not a number");
N
Niels 已提交
4828 4829
                    }

N
Niels 已提交
4830 4831
                    get_token();

N
Niels 已提交
4832 4833
                    // check if conversion loses precision
                    const auto int_val = static_cast<number_integer_t>(float_val);
N
Niels 已提交
4834
                    if (approx(float_val, static_cast<long double>(int_val)))
N
Niels 已提交
4835 4836
                    {
                        // we basic_json not lose precision -> return int
N
Niels 已提交
4837 4838
                        result.m_type = value_t::number_integer;
                        result.m_value = int_val;
N
Niels 已提交
4839 4840 4841 4842
                    }
                    else
                    {
                        // we would lose precision -> returnfloat
N
Niels 已提交
4843
                        result.m_type = value_t::number_float;
N
Niels 已提交
4844
                        result.m_value = static_cast<number_float_t>(float_val);
N
Niels 已提交
4845
                    }
N
Niels 已提交
4846
                    break;
N
Niels 已提交
4847 4848 4849 4850
                }

                default:
                {
N
Niels 已提交
4851 4852
                    // the last token was unexpected
                    unexpect(last_token);
N
Niels 已提交
4853 4854
                }
            }
N
Niels 已提交
4855

N
Niels 已提交
4856
            if (keep and callback and not callback(depth, parse_event_t::value, result))
N
Niels 已提交
4857 4858 4859 4860
            {
                result = basic_json(value_t::discarded);
            }
            return result;
N
Niels 已提交
4861 4862 4863
        }

        /// get next token from lexer
N
Niels 已提交
4864
        typename lexer::token_type get_token()
N
Niels 已提交
4865 4866 4867 4868 4869
        {
            last_token = m_lexer.scan();
            return last_token;
        }

N
Niels 已提交
4870
        void expect(typename lexer::token_type t) const
N
Niels 已提交
4871 4872 4873 4874
        {
            if (t != last_token)
            {
                std::string error_msg = "parse error - unexpected \'";
N
Niels 已提交
4875
                error_msg += m_lexer.get_token();
N
cleanup  
Niels 已提交
4876 4877
                error_msg += "\' (" + lexer::token_type_name(last_token);
                error_msg += "); expected " + lexer::token_type_name(t);
N
Niels 已提交
4878 4879 4880 4881
                throw std::invalid_argument(error_msg);
            }
        }

N
Niels 已提交
4882
        void unexpect(typename lexer::token_type t) const
N
Niels 已提交
4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893
        {
            if (t == last_token)
            {
                std::string error_msg = "parse error - unexpected \'";
                error_msg += m_lexer.get_token();
                error_msg += "\' (";
                error_msg += lexer::token_type_name(last_token) + ")";
                throw std::invalid_argument(error_msg);
            }
        }

N
Niels 已提交
4894
      private:
N
Niels 已提交
4895 4896 4897 4898
        /// levels of recursion
        int depth = 0;
        /// callback function
        parser_callback_t callback;
N
Niels 已提交
4899
        /// the type of the last read token
N
Niels 已提交
4900
        typename lexer::token_type last_token = lexer::token_type::uninitialized;
N
Niels 已提交
4901
        /// the lexer
N
Niels 已提交
4902
        lexer m_lexer;
N
Niels 已提交
4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922
    };
};


/////////////
// presets //
/////////////

/// default JSON class
using json = basic_json<>;
}


/////////////////////////
// nonmember functions //
/////////////////////////

// specialization of std::swap, and std::hash
namespace std
{
N
Niels 已提交
4923 4924 4925 4926
/*!
@brief exchanges the values of two JSON objects
@ingroup container
*/
N
Niels 已提交
4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940
template <>
inline void swap(nlohmann::json& j1,
                 nlohmann::json& j2) noexcept(
                     is_nothrow_move_constructible<nlohmann::json>::value and
                     is_nothrow_move_assignable<nlohmann::json>::value
                 )
{
    j1.swap(j2);
}

/// hash value for JSON objects
template <>
struct hash<nlohmann::json>
{
N
Niels 已提交
4941
    /// return a hash value for a JSON object
N
Niels 已提交
4942
    std::size_t operator()(const nlohmann::json& j) const
N
Niels 已提交
4943 4944
    {
        // a naive hashing via the string representation
N
Niels 已提交
4945 4946
        const auto& h = hash<nlohmann::json::string_t>();
        return h(j.dump());
N
Niels 已提交
4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958
    }
};
}

/*!
This operator implements a user-defined string literal for JSON objects. It can
be used by adding \p "_json" to a string literal and returns a JSON object if
no parse error occurred.

@param s  a string representation of a JSON object
@return a JSON object
*/
N
Niels 已提交
4959
inline nlohmann::json operator "" _json(const char* s, std::size_t)
N
Niels 已提交
4960
{
N
Niels 已提交
4961 4962
    return nlohmann::json::parse(reinterpret_cast<nlohmann::json::string_t::value_type*>
                                 (const_cast<char*>(s)));
N
Niels 已提交
4963 4964 4965
}

#endif