json.hpp.re2c 122.1 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
cleanup  
Niels 已提交
12 13

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

/*!
N
Niels 已提交
32
@brief namespace for Niels Lohmann
N
cleanup  
Niels 已提交
33 34 35 36 37
@see https://github.com/nlohmann
*/
namespace nlohmann
{

N
Niels 已提交
38 39 40 41

// Helper to determine whether there's a key_type for T.
// http://stackoverflow.com/a/7728728/266378
template<typename T>
N
Niels 已提交
42
struct has_mapped_type
N
Niels 已提交
43 44
{
  private:
N
Niels 已提交
45
    template<typename C> static char test(typename C::mapped_type*);
N
Niels 已提交
46 47 48 49 50
    template<typename C> static int  test(...);
  public:
    enum { value = sizeof(test<T>(0)) == sizeof(char) };
};

N
cleanup  
Niels 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63
/*!
@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 已提交
64
@tparam NumberFloatType    type for JSON floating-point numbers
N
cleanup  
Niels 已提交
65
                           (@c double by default)
N
Niels 已提交
66
@tparam AllocatorType      type of the allocator to use
N
Niels 已提交
67
                           (@c std::allocator by default)
N
Niels 已提交
68

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

N
Niels 已提交
71 72
@see RFC 7159 <http://rfc7159.net/rfc7159>
@see ECMA 404 <http://www.ecma-international.org/publications/standards/Ecma-404.htm>
N
cleanup  
Niels 已提交
73 74 75 76 77 78 79
*/
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 已提交
80
    class NumberFloatType = double,
N
Niels 已提交
81
    template<typename U> class AllocatorType = std::allocator
N
cleanup  
Niels 已提交
82 83 84 85 86 87 88 89
    >
class basic_json
{
  public:
    /////////////////////
    // container types //
    /////////////////////

N
Niels 已提交
90
    /// the type of elements in a basic_json container
N
cleanup  
Niels 已提交
91
    using value_type = basic_json;
N
Niels 已提交
92

N
Niels 已提交
93
    /// the type of an element reference
N
Niels 已提交
94
    using reference = value_type&;
N
Niels 已提交
95

N
Niels 已提交
96
    /// the type of an element const reference
N
Niels 已提交
97
    using const_reference = const value_type&;
N
Niels 已提交
98

N
Niels 已提交
99
    /// a type to represent differences between iterators
N
Niels 已提交
100 101
    using difference_type = std::ptrdiff_t;

N
Niels 已提交
102
    /// a type to represent container sizes
N
Niels 已提交
103 104 105
    using size_type = std::size_t;

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

N
cleanup  
Niels 已提交
108
    /// the type of an element pointer
N
Niels 已提交
109
    using pointer = typename std::allocator_traits<allocator_type>::pointer;
N
cleanup  
Niels 已提交
110
    /// the type of an element const pointer
N
Niels 已提交
111
    using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
N
Niels 已提交
112

N
Niels 已提交
113 114 115 116 117 118 119 120
    /// 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 已提交
121

N
Niels 已提交
122
    /// returns the allocator associated with the container
N
Niels 已提交
123
    inline static allocator_type get_allocator()
N
Niels 已提交
124 125 126 127 128
    {
        return allocator_type();
    }


N
cleanup  
Niels 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142
    ///////////////////////////
    // JSON value data types //
    ///////////////////////////

    /// a type for an object
    using object_t = ObjectType<StringType, basic_json>;
    /// a type for an array
    using array_t = ArrayType<basic_json>;
    /// 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 已提交
143
    /// a type for a number (floating-point)
N
cleanup  
Niels 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    using number_float_t = NumberFloatType;
    /// a type for list initialization
    using list_init_t = std::initializer_list<basic_json>;


    ////////////////////////
    // 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;
        /// bolean
        boolean_t boolean;
        /// number (integer)
        number_integer_t number_integer;
N
Niels 已提交
166
        /// number (floating-point)
N
cleanup  
Niels 已提交
167 168 169 170 171 172 173 174
        number_float_t number_float;

        /// default constructor (for null values)
        json_value() = default;
        /// constructor for booleans
        json_value(boolean_t v) : boolean(v) {}
        /// constructor for numbers (integer)
        json_value(number_integer_t v) : number_integer(v) {}
N
Niels 已提交
175
        /// constructor for numbers (floating-point)
N
cleanup  
Niels 已提交
176 177 178 179 180 181 182 183 184 185 186
        json_value(number_float_t v) : number_float(v) {}
    };


    /////////////////////////////////
    // JSON value type enumeration //
    /////////////////////////////////

    /// JSON value type enumeration
    enum class value_t : uint8_t
    {
N
Niels 已提交
187 188 189 190 191 192 193
        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)
N
cleanup  
Niels 已提交
194 195
    };

N
Niels 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    /*!
    @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)
    {
        // no type is smaller than itself
        if (lhs == rhs)
        {
            return false;
        }

        switch (lhs)
        {
            case (value_t::null):
            {
                // nulls are smaller than all other types
                return true;
            }

            case (value_t::boolean):
            {
                // only nulls are smaller than booleans
                return (rhs != value_t::null);
            }

            case (value_t::number_float):
            case (value_t::number_integer):
            {
                switch (rhs)
                {
                    // numbers are smaller than objects, arrays, and string
                    case (value_t::object):
                    case (value_t::array):
                    case (value_t::string):
                    {
                        return true;
                    }
N
Niels 已提交
237

N
Niels 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
                    default:
                    {
                        return false;
                    }
                }
            }

            case (value_t::object):
            {
                switch (rhs)
                {
                    // objects are smaller than arrays and string
                    case (value_t::array):
                    case (value_t::string):
                    {
                        return true;
                    }
N
Niels 已提交
255

N
Niels 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
                    default:
                    {
                        return false;
                    }
                }
            }

            case (value_t::array):
            {
                // arrays are smaller than strings
                return (rhs == value_t::string);
            }

            default:
            {
                // a string is not smaller than any other types
                return false;
            }
        }
    }

N
cleanup  
Niels 已提交
277 278 279 280 281

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

N
Niels 已提交
282 283 284 285 286 287
    /*!
    @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
cleanup  
Niels 已提交
288 289 290 291 292 293 294 295 296 297 298 299
    inline basic_json(const value_t value)
        : m_type(value)
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                break;
            }

            case (value_t::object):
            {
N
Niels 已提交
300
                AllocatorType<object_t> alloc;
N
Niels 已提交
301 302
                m_value.object = alloc.allocate(1);
                alloc.construct(m_value.object);
N
cleanup  
Niels 已提交
303 304 305 306 307
                break;
            }

            case (value_t::array):
            {
N
Niels 已提交
308
                AllocatorType<array_t> alloc;
N
Niels 已提交
309 310
                m_value.array = alloc.allocate(1);
                alloc.construct(m_value.array);
N
cleanup  
Niels 已提交
311 312 313 314 315
                break;
            }

            case (value_t::string):
            {
N
Niels 已提交
316
                AllocatorType<string_t> alloc;
N
Niels 已提交
317 318
                m_value.string = alloc.allocate(1);
                alloc.construct(m_value.string, "");
N
cleanup  
Niels 已提交
319 320 321 322 323
                break;
            }

            case (value_t::boolean):
            {
N
Niels 已提交
324
                m_value.boolean = boolean_t(false);
N
cleanup  
Niels 已提交
325 326 327 328 329
                break;
            }

            case (value_t::number_integer):
            {
N
Niels 已提交
330
                m_value.number_integer = number_integer_t(0);
N
cleanup  
Niels 已提交
331 332 333 334 335
                break;
            }

            case (value_t::number_float):
            {
N
Niels 已提交
336
                m_value.number_float = number_float_t(0.0);
N
cleanup  
Niels 已提交
337 338 339 340 341
                break;
            }
        }
    }

N
Niels 已提交
342 343 344 345 346
    /*!
    @brief create a null object (implicitly)
    @ingroup container
    */
    inline basic_json() noexcept = default;
N
cleanup  
Niels 已提交
347 348 349 350 351 352 353 354

    /// create a null object (explicitly)
    inline basic_json(std::nullptr_t) noexcept
        : m_type(value_t::null)
    {}

    /// create an object (explicit)
    inline basic_json(const object_t& value)
N
Niels 已提交
355 356
        : m_type(value_t::object)
    {
N
Niels 已提交
357
        AllocatorType<object_t> alloc;
N
Niels 已提交
358 359 360
        m_value.object = alloc.allocate(1);
        alloc.construct(m_value.object, value);
    }
N
cleanup  
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
cleanup  
Niels 已提交
366 367 368
                  std::is_constructible<basic_json, typename V::mapped_type>::value, int>::type
              = 0>
    inline 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
cleanup  
Niels 已提交
377 378 379

    /// create an array (explicit)
    inline basic_json(const array_t& value)
N
Niels 已提交
380 381
        : m_type(value_t::array)
    {
N
Niels 已提交
382
        AllocatorType<array_t> alloc;
N
Niels 已提交
383 384 385
        m_value.array = alloc.allocate(1);
        alloc.construct(m_value.array, value);
    }
N
cleanup  
Niels 已提交
386 387 388 389 390 391

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

    /// create a string (explicit)
    inline basic_json(const string_t& value)
N
Niels 已提交
410
        : m_type(value_t::string)
N
Niels 已提交
411
    {
N
Niels 已提交
412
        AllocatorType<string_t> alloc;
N
Niels 已提交
413 414 415
        m_value.string = alloc.allocate(1);
        alloc.construct(m_value.string, value);
    }
N
cleanup  
Niels 已提交
416 417 418

    /// create a string (explicit)
    inline basic_json(const typename string_t::value_type* value)
N
Niels 已提交
419
        : m_type(value_t::string)
N
Niels 已提交
420
    {
N
Niels 已提交
421
        AllocatorType<string_t> alloc;
N
Niels 已提交
422 423 424
        m_value.string = alloc.allocate(1);
        alloc.construct(m_value.string, value);
    }
N
cleanup  
Niels 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454

    /// create a string (implicit)
    template <class V, typename
              std::enable_if<
                  std::is_constructible<string_t, V>::value, int>::type
              = 0>
    inline basic_json(const V& value)
        : basic_json(string_t(value))
    {}

    /// create a boolean (explicit)
    inline basic_json(boolean_t value)
        : m_type(value_t::boolean), m_value(value)
    {}

    /// create an integer number (explicit)
    inline basic_json(const number_integer_t& value)
        : m_type(value_t::number_integer), m_value(value)
    {}

    /// 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>
    inline basic_json(const T value) noexcept
        : m_type(value_t::number_integer), m_value(number_integer_t(value))
    {}

N
Niels 已提交
455
    /// create a floating-point number (explicit)
N
cleanup  
Niels 已提交
456 457 458 459
    inline basic_json(const number_float_t& value)
        : m_type(value_t::number_float), m_value(value)
    {}

N
Niels 已提交
460
    /// create a floating-point number (implicit)
N
cleanup  
Niels 已提交
461 462 463 464 465 466 467 468 469
    template<typename T, typename = typename
             std::enable_if<
                 std::is_constructible<number_float_t, T>::value and
                 std::is_floating_point<T>::value>::type
             >
    inline basic_json(const T value) noexcept
        : m_type(value_t::number_float), m_value(number_float_t(value))
    {}

N
Niels 已提交
470
    /// create a container (array or object) from an initializer list
N
Niels 已提交
471 472
    inline basic_json(list_init_t init, bool type_deduction = true,
                      value_t manual_type = value_t::array)
N
cleanup  
Niels 已提交
473 474 475 476 477 478
    {
        // the initializer list could describe an object
        bool is_object = true;

        // check if each element is an array with two elements whose first element
        // is a string
N
Niels 已提交
479
        for (const auto& element : init)
N
cleanup  
Niels 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
        {
            if ((element.m_final and element.m_type == value_t::array)
                    or (element.m_type != value_t::array or element.size() != 2
                        or element[0].m_type != value_t::string))
            {
                // 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)
        {
            // mark this object's type as final
            m_final = true;

            // 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 已提交
507
                throw std::logic_error("cannot create JSON object from initializer list");
N
cleanup  
Niels 已提交
508 509 510 511 512 513 514
            }
        }

        if (is_object)
        {
            // the initializer list is a list of pairs -> create object
            m_type = value_t::object;
N
Niels 已提交
515
            AllocatorType<object_t> alloc;
N
Niels 已提交
516 517 518
            m_value.object = alloc.allocate(1);
            alloc.construct(m_value.object);

N
Niels 已提交
519
            for (auto& element : init)
N
cleanup  
Niels 已提交
520 521 522 523 524 525 526 527
            {
                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 已提交
528
            AllocatorType<array_t> alloc;
N
Niels 已提交
529
            m_value.array = alloc.allocate(1);
N
Niels 已提交
530
            alloc.construct(m_value.array, std::move(init));
N
cleanup  
Niels 已提交
531 532 533
        }
    }

N
Niels 已提交
534
    /// explicitly create an array from an initializer list
N
Niels 已提交
535
    inline static basic_json array(list_init_t init = list_init_t())
N
cleanup  
Niels 已提交
536
    {
N
Niels 已提交
537
        return basic_json(init, false, value_t::array);
N
cleanup  
Niels 已提交
538 539
    }

N
Niels 已提交
540
    /// explicitly create an object from an initializer list
N
Niels 已提交
541
    inline static basic_json object(list_init_t init = list_init_t())
N
cleanup  
Niels 已提交
542
    {
N
Niels 已提交
543
        return basic_json(init, false, value_t::object);
N
cleanup  
Niels 已提交
544 545
    }

N
Niels 已提交
546 547 548 549 550 551 552 553
    /// construct an array with count copies of given value
    inline basic_json(size_type count, const basic_json& other)
        : m_type(value_t::array)
    {
        AllocatorType<array_t> alloc;
        m_value.array = alloc.allocate(1);
        alloc.construct(m_value.array, count, other);
    }
N
Niels 已提交
554

N
Niels 已提交
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 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 638 639 640 641 642 643 644 645
    /// construct a JSON container given an iterator range
    template <class T, typename
              std::enable_if<
                  std::is_same<T, basic_json::iterator>::value or
                  std::is_same<T, basic_json::const_iterator>::value
                  , int>::type
              = 0>
    inline basic_json(T first, T last)
    {
        // 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)
        {
            throw std::runtime_error("iterators are not compatible");
        }

        // set the type
        m_type = first.m_object->m_type;

        // check if iterator range is complete for non-compound values
        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:
            {
                AllocatorType<string_t> alloc;
                m_value.string = alloc.allocate(1);
                alloc.construct(m_value.string, *first.m_object->m_value.string);
                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:
            {
                throw std::runtime_error("cannot use construct with iterators from " + first.m_object->type_name());
            }
        }
    }

N
cleanup  
Niels 已提交
646 647 648 649
    ///////////////////////////////////////
    // other constructors and destructor //
    ///////////////////////////////////////

N
Niels 已提交
650 651
    /*!
    @brief copy constructor
N
Niels 已提交
652 653 654

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

N
Niels 已提交
655 656
    @ingroup container
    */
N
cleanup  
Niels 已提交
657 658 659 660 661 662 663 664 665
    inline basic_json(const basic_json& other)
        : m_type(other.m_type)
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                break;
            }
N
Niels 已提交
666

N
cleanup  
Niels 已提交
667 668
            case (value_t::object):
            {
N
Niels 已提交
669
                AllocatorType<object_t> alloc;
N
Niels 已提交
670 671
                m_value.object = alloc.allocate(1);
                alloc.construct(m_value.object, *other.m_value.object);
N
cleanup  
Niels 已提交
672 673
                break;
            }
N
Niels 已提交
674

N
cleanup  
Niels 已提交
675 676
            case (value_t::array):
            {
N
Niels 已提交
677
                AllocatorType<array_t> alloc;
N
Niels 已提交
678 679
                m_value.array = alloc.allocate(1);
                alloc.construct(m_value.array, *other.m_value.array);
N
cleanup  
Niels 已提交
680 681
                break;
            }
N
Niels 已提交
682

N
cleanup  
Niels 已提交
683 684
            case (value_t::string):
            {
N
Niels 已提交
685
                AllocatorType<string_t> alloc;
N
Niels 已提交
686 687
                m_value.string = alloc.allocate(1);
                alloc.construct(m_value.string, *other.m_value.string);
N
cleanup  
Niels 已提交
688 689
                break;
            }
N
Niels 已提交
690

N
cleanup  
Niels 已提交
691 692 693 694 695
            case (value_t::boolean):
            {
                m_value.boolean = other.m_value.boolean;
                break;
            }
N
Niels 已提交
696

N
cleanup  
Niels 已提交
697 698 699 700 701
            case (value_t::number_integer):
            {
                m_value.number_integer = other.m_value.number_integer;
                break;
            }
N
Niels 已提交
702

N
cleanup  
Niels 已提交
703 704 705 706 707 708 709 710 711 712 713 714 715
            case (value_t::number_float):
            {
                m_value.number_float = other.m_value.number_float;
                break;
            }
        }
    }

    /// move constructor
    inline basic_json(basic_json&& other) noexcept
        : m_type(std::move(other.m_type)),
          m_value(std::move(other.m_value))
    {
N
Niels 已提交
716
        // invalidate payload
N
cleanup  
Niels 已提交
717 718 719 720
        other.m_type = value_t::null;
        other.m_value = {};
    }

N
Niels 已提交
721 722 723 724
    /*!
    @brief copy assignment
    @ingroup container
    */
N
Niels 已提交
725 726 727 728 729 730
    inline reference& operator=(basic_json other) noexcept (
        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
cleanup  
Niels 已提交
731
    {
N
Niels 已提交
732
        using std::swap;
N
cleanup  
Niels 已提交
733 734 735 736 737
        std::swap(m_type, other.m_type);
        std::swap(m_value, other.m_value);
        return *this;
    }

N
Niels 已提交
738 739 740 741
    /*!
    @brief destructor
    @ingroup container
    */
N
cleanup  
Niels 已提交
742 743 744 745 746 747
    inline ~basic_json() noexcept
    {
        switch (m_type)
        {
            case (value_t::object):
            {
N
Niels 已提交
748
                AllocatorType<object_t> alloc;
N
Niels 已提交
749 750
                alloc.destroy(m_value.object);
                alloc.deallocate(m_value.object, 1);
N
cleanup  
Niels 已提交
751 752 753
                m_value.object = nullptr;
                break;
            }
N
Niels 已提交
754

N
cleanup  
Niels 已提交
755 756
            case (value_t::array):
            {
N
Niels 已提交
757
                AllocatorType<array_t> alloc;
N
Niels 已提交
758 759
                alloc.destroy(m_value.array);
                alloc.deallocate(m_value.array, 1);
N
cleanup  
Niels 已提交
760 761 762
                m_value.array = nullptr;
                break;
            }
N
Niels 已提交
763

N
cleanup  
Niels 已提交
764 765
            case (value_t::string):
            {
N
Niels 已提交
766
                AllocatorType<string_t> alloc;
N
Niels 已提交
767
                alloc.destroy(m_value.string);
N
Niels 已提交
768
                alloc.deallocate(m_value.string, 1);
N
cleanup  
Niels 已提交
769 770 771
                m_value.string = nullptr;
                break;
            }
N
Niels 已提交
772 773

            default:
N
cleanup  
Niels 已提交
774
            {
N
Niels 已提交
775
                // all other types need no specific destructor
N
cleanup  
Niels 已提交
776 777 778 779 780 781 782 783 784 785 786 787
                break;
            }
        }
    }


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

    /*!
N
Niels 已提交
788 789
    @brief serialization

N
Niels 已提交
790 791 792
    Serialization function for JSON objects. The function tries to mimick
    Python's @p json.dumps() function, and currently supports its @p indent
    parameter.
N
cleanup  
Niels 已提交
793

N
Niels 已提交
794 795 796 797
    @param indent  sif indent is nonnegative, then array elements and object
    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
cleanup  
Niels 已提交
798 799 800

    @see https://docs.python.org/2/library/json.html#json.dump
    */
N
Niels 已提交
801
    inline string_t dump(const int indent = -1) const noexcept
N
cleanup  
Niels 已提交
802 803 804 805 806 807 808 809 810 811 812
    {
        if (indent >= 0)
        {
            return dump(true, static_cast<unsigned int>(indent));
        }
        else
        {
            return dump(false, 0);
        }
    }

N
Niels 已提交
813
    /// return the type of the object (explicit)
N
cleanup  
Niels 已提交
814 815 816 817 818
    inline value_t type() const noexcept
    {
        return m_type;
    }

N
Niels 已提交
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
    // return whether value is null
    inline bool is_null() const noexcept
    {
        return m_type == value_t::null;
    }

    // return whether value is boolean
    inline bool is_boolean() const noexcept
    {
        return m_type == value_t::boolean;
    }

    // return whether value is number
    inline bool is_number() const noexcept
    {
        return (m_type == value_t::number_integer) or (m_type == value_t::number_float);
    }

    // return whether value is object
    inline bool is_object() const noexcept
    {
        return m_type == value_t::object;
    }

    // return whether value is array
    inline bool is_array() const noexcept
    {
        return m_type == value_t::array;
    }

    // return whether value is string
    inline bool is_string() const noexcept
    {
        return m_type == value_t::string;
    }

N
Niels 已提交
855
    /// return the type of the object (implicit)
N
Niels 已提交
856
    inline operator value_t() const noexcept
N
cleanup  
Niels 已提交
857 858 859 860
    {
        return m_type;
    }

N
Niels 已提交
861
  private:
N
cleanup  
Niels 已提交
862 863 864 865
    //////////////////////
    // value conversion //
    //////////////////////

N
Niels 已提交
866
    /// get an object (explicit)
N
cleanup  
Niels 已提交
867 868
    template <class T, typename
              std::enable_if<
N
Niels 已提交
869 870 871 872
                  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>
    inline T get_impl(T*) const
N
cleanup  
Niels 已提交
873 874 875 876
    {
        switch (m_type)
        {
            case (value_t::object):
N
Niels 已提交
877
            {
N
cleanup  
Niels 已提交
878
                return T(m_value.object->begin(), m_value.object->end());
N
Niels 已提交
879
            }
N
cleanup  
Niels 已提交
880
            default:
N
Niels 已提交
881
            {
N
cleanup  
Niels 已提交
882
                throw std::logic_error("cannot cast " + type_name() + " to " + typeid(T).name());
N
Niels 已提交
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
            }
        }
    }

    /// get an object (explicit)
    inline object_t get_impl(object_t*) const
    {
        switch (m_type)
        {
            case (value_t::object):
            {
                return *(m_value.object);
            }
            default:
            {
                throw std::logic_error("cannot cast " + type_name() + " to object");
            }
N
cleanup  
Niels 已提交
900 901 902
        }
    }

N
Niels 已提交
903
    /// get an array (explicit)
N
cleanup  
Niels 已提交
904 905
    template <class T, typename
              std::enable_if<
N
Niels 已提交
906 907 908 909 910 911 912
                  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>
    inline T get_impl(T*) const
N
cleanup  
Niels 已提交
913 914 915 916
    {
        switch (m_type)
        {
            case (value_t::array):
N
Niels 已提交
917 918 919 920 921 922 923 924 925
            {
                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
cleanup  
Niels 已提交
926
            default:
N
Niels 已提交
927
            {
N
cleanup  
Niels 已提交
928
                throw std::logic_error("cannot cast " + type_name() + " to " + typeid(T).name());
N
Niels 已提交
929
            }
N
cleanup  
Niels 已提交
930 931 932
        }
    }

N
Niels 已提交
933 934
    /// get an array (explicit)
    template <class T, typename
N
cleanup  
Niels 已提交
935
              std::enable_if<
N
Niels 已提交
936 937 938 939
                  std::is_convertible<basic_json, T>::value and
                  not std::is_same<basic_json, T>::value
                  , int>::type = 0>
    inline std::vector<T> get_impl(std::vector<T>*) const
N
cleanup  
Niels 已提交
940 941 942
    {
        switch (m_type)
        {
N
Niels 已提交
943 944 945 946 947 948 949 950 951 952 953
            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
cleanup  
Niels 已提交
954
            default:
N
Niels 已提交
955
            {
N
cleanup  
Niels 已提交
956
                throw std::logic_error("cannot cast " + type_name() + " to " + typeid(T).name());
N
Niels 已提交
957
            }
N
cleanup  
Niels 已提交
958 959 960
        }
    }

N
Niels 已提交
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
    /// 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>
    inline T get_impl(T*) const
    {
        switch (m_type)
        {
            case (value_t::array):
            {
                return T(m_value.array->begin(), m_value.array->end());
            }
            default:
            {
                throw std::logic_error("cannot cast " + type_name() + " to " + typeid(T).name());
            }
        }
    }

    inline array_t get_impl(array_t*) const
    {
        switch (m_type)
        {
            case (value_t::array):
            {
                return *(m_value.array);
            }
            default:
            {
                throw std::logic_error("cannot cast " + type_name() + " to array");
            }
        }
    }

    /// get a string (explicit)
N
cleanup  
Niels 已提交
998 999
    template <typename T, typename
              std::enable_if<
N
Niels 已提交
1000 1001 1002
                  std::is_convertible<string_t, T>::value
                  , int>::type = 0>
    inline T get_impl(T*) const
N
cleanup  
Niels 已提交
1003 1004 1005
    {
        switch (m_type)
        {
N
Niels 已提交
1006 1007 1008 1009
            case (value_t::string):
            {
                return *m_value.string;
            }
N
cleanup  
Niels 已提交
1010
            default:
N
Niels 已提交
1011
            {
N
cleanup  
Niels 已提交
1012
                throw std::logic_error("cannot cast " + type_name() + " to " + typeid(T).name());
N
Niels 已提交
1013
            }
N
cleanup  
Niels 已提交
1014 1015 1016
        }
    }

N
Niels 已提交
1017
    /// get a number (explicit)
N
cleanup  
Niels 已提交
1018 1019
    template<typename T, typename
             std::enable_if<
N
Niels 已提交
1020 1021 1022
                 std::is_arithmetic<T>::value
                 , int>::type = 0>
    inline T get_impl(T*) const
N
cleanup  
Niels 已提交
1023 1024 1025 1026
    {
        switch (m_type)
        {
            case (value_t::number_integer):
N
Niels 已提交
1027
            {
N
cleanup  
Niels 已提交
1028
                return static_cast<T>(m_value.number_integer);
N
Niels 已提交
1029
            }
N
cleanup  
Niels 已提交
1030
            case (value_t::number_float):
N
Niels 已提交
1031
            {
N
cleanup  
Niels 已提交
1032
                return static_cast<T>(m_value.number_float);
N
Niels 已提交
1033
            }
N
cleanup  
Niels 已提交
1034
            default:
N
Niels 已提交
1035
            {
N
cleanup  
Niels 已提交
1036
                throw std::logic_error("cannot cast " + type_name() + " to " + typeid(T).name());
N
Niels 已提交
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
            }
        }
    }

    /// get a boolean (explicit)
    inline boolean_t get_impl(boolean_t*) const
    {
        switch (m_type)
        {
            case (value_t::boolean):
            {
                return m_value.boolean;
            }
            default:
            {
                throw std::logic_error("cannot cast " + type_name() + " to " + typeid(boolean_t).name());
            }
N
cleanup  
Niels 已提交
1054 1055 1056
        }
    }

N
Niels 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065
  public:
    /// get a value (explicit)
    // <http://stackoverflow.com/a/8315197/266378>
    template<typename T>
    inline T get() const
    {
        return get_impl(static_cast<T*>(nullptr));
    }

N
Niels 已提交
1066
    /// get a value (implicit)
N
cleanup  
Niels 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    template<typename T>
    inline operator T() const
    {
        return get<T>();
    }


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

    /// access specified element with bounds checking
1079
    inline reference at(size_type idx)
N
cleanup  
Niels 已提交
1080 1081 1082 1083 1084 1085 1086
    {
        // at only works for arrays
        if (m_type != value_t::array)
        {
            throw std::runtime_error("cannot use at with " + type_name());
        }

1087
        return m_value.array->at(idx);
N
cleanup  
Niels 已提交
1088 1089 1090
    }

    /// access specified element with bounds checking
1091
    inline const_reference at(size_type idx) const
N
cleanup  
Niels 已提交
1092 1093 1094 1095 1096 1097 1098
    {
        // at only works for arrays
        if (m_type != value_t::array)
        {
            throw std::runtime_error("cannot use at with " + type_name());
        }

1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
        return m_value.array->at(idx);
    }

    /// access specified element with bounds checking
    inline reference at(const typename object_t::key_type& key)
    {
        // at only works for objects
        if (m_type != value_t::object)
        {
            throw std::runtime_error("cannot use at with " + type_name());
        }

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

    /// access specified element with bounds checking
    inline const_reference at(const typename object_t::key_type& key) const
    {
        // at only works for objects
        if (m_type != value_t::object)
        {
            throw std::runtime_error("cannot use at with " + type_name());
        }

        return m_value.object->at(key);
N
cleanup  
Niels 已提交
1124 1125 1126
    }

    /// access specified element
1127
    inline reference operator[](size_type idx)
N
cleanup  
Niels 已提交
1128
    {
N
Niels 已提交
1129 1130 1131 1132
        // implicitly convert null to object
        if (m_type == value_t::null)
        {
            m_type = value_t::array;
N
Niels 已提交
1133
            AllocatorType<array_t> alloc;
N
Niels 已提交
1134 1135 1136 1137 1138
            m_value.array = alloc.allocate(1);
            alloc.construct(m_value.array);
        }

        // [] only works for arrays
N
cleanup  
Niels 已提交
1139 1140 1141 1142 1143
        if (m_type != value_t::array)
        {
            throw std::runtime_error("cannot use [] with " + type_name());
        }

1144
        for (size_t i = m_value.array->size(); i <= idx; ++i)
N
Niels 已提交
1145 1146 1147 1148
        {
            m_value.array->push_back(basic_json());
        }

1149
        return m_value.array->operator[](idx);
N
cleanup  
Niels 已提交
1150 1151 1152
    }

    /// access specified element
1153
    inline const_reference operator[](size_type idx) const
N
cleanup  
Niels 已提交
1154 1155 1156 1157 1158 1159 1160
    {
        // at only works for arrays
        if (m_type != value_t::array)
        {
            throw std::runtime_error("cannot use [] with " + type_name());
        }

1161
        return m_value.array->operator[](idx);
N
cleanup  
Niels 已提交
1162 1163 1164 1165 1166
    }

    /// access specified element
    inline reference operator[](const typename object_t::key_type& key)
    {
N
Niels 已提交
1167 1168 1169 1170
        // implicitly convert null to object
        if (m_type == value_t::null)
        {
            m_type = value_t::object;
N
Niels 已提交
1171
            AllocatorType<object_t> alloc;
N
Niels 已提交
1172 1173 1174 1175
            m_value.object = alloc.allocate(1);
            alloc.construct(m_value.object);
        }

N
Niels 已提交
1176
        // [] only works for objects
N
cleanup  
Niels 已提交
1177 1178 1179 1180 1181 1182 1183 1184
        if (m_type != value_t::object)
        {
            throw std::runtime_error("cannot use [] with " + type_name());
        }

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

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    /// access specified element
    inline const_reference operator[](const typename object_t::key_type& key) const
    {
        // at only works for objects
        if (m_type != value_t::object)
        {
            throw std::runtime_error("cannot use [] with " + type_name());
        }

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

N
cleanup  
Niels 已提交
1197
    /// access specified element (needed for clang)
N
Niels 已提交
1198
    template<typename T, std::size_t n>
N
cleanup  
Niels 已提交
1199 1200
    inline reference operator[](const T (&key)[n])
    {
N
Niels 已提交
1201 1202 1203 1204
        // implicitly convert null to object
        if (m_type == value_t::null)
        {
            m_type = value_t::object;
N
Niels 已提交
1205
            AllocatorType<object_t> alloc;
N
Niels 已提交
1206 1207 1208 1209
            m_value.object = alloc.allocate(1);
            alloc.construct(m_value.object);
        }

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

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

1219
    /// access specified element (needed for clang)
N
Niels 已提交
1220
    template<typename T, std::size_t n>
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    inline const_reference operator[](const T (&key)[n]) const
    {
        // at only works for objects
        if (m_type != value_t::object)
        {
            throw std::runtime_error("cannot use [] with " + type_name());
        }

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

N
Niels 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
    /// access the first element
    inline reference front()
    {
        return *begin();
    }

    /// access the first element
    inline const_reference front() const
    {
        return *cbegin();
    }

    /// access the last element
    inline reference back()
    {
        auto tmp = end();
        --tmp;
        return *tmp;
    }

    /// access the last element
    inline const_reference back() const
    {
        auto tmp = cend();
        --tmp;
        return *tmp;
    }

1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 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 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
    /// remove element given an iterator
    template <class T, typename
              std::enable_if<
                  std::is_same<T, basic_json::iterator>::value or
                  std::is_same<T, basic_json::const_iterator>::value
                  , int>::type
              = 0>
    inline T erase(T pos)
    {
        // make sure iterator fits the current value
        if (this != pos.m_object or m_type != pos.m_object->m_type)
        {
            throw std::runtime_error("iterator does not fit current value");
        }

        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:
            {
                throw std::runtime_error("cannot use erase with " + type_name());
            }
        }

        return result;
    }

    /// remove elements given an iterator range
    template <class T, typename
              std::enable_if<
                  std::is_same<T, basic_json::iterator>::value or
                  std::is_same<T, basic_json::const_iterator>::value
                  , int>::type
              = 0>
    inline T erase(T first, T last)
    {
        // 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)
        {
            throw std::runtime_error("iterators do not fit current value");
        }

        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:
            {
                throw std::runtime_error("cannot use erase with " + type_name());
            }
        }

        return result;
    }

1383 1384 1385
    /// remove element from an object given a key
    inline size_type erase(const typename object_t::key_type& key)
    {
N
Niels 已提交
1386
        // this erase only works for objects
1387 1388
        if (m_type != value_t::object)
        {
N
Niels 已提交
1389
            throw std::runtime_error("cannot use erase with " + type_name());
1390 1391 1392 1393 1394
        }

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

N
Niels 已提交
1395
    /// remove element from an array given an index
N
Niels 已提交
1396
    inline void erase(const size_type idx)
N
Niels 已提交
1397 1398 1399 1400 1401 1402 1403
    {
        // this erase only works for arrays
        if (m_type != value_t::array)
        {
            throw std::runtime_error("cannot use erase with " + type_name());
        }

N
Niels 已提交
1404
        if (idx >= size())
N
Niels 已提交
1405 1406 1407 1408
        {
            throw std::out_of_range("index out of range");
        }

N
Niels 已提交
1409
        m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
N
Niels 已提交
1410 1411
    }

N
Niels 已提交
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
    /// find an element in an object
    inline iterator find(typename object_t::key_type key)
    {
        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
    inline const_iterator find(typename object_t::key_type key) const
    {
        auto result = cend();

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

        return result;
    }

1438 1439 1440 1441 1442 1443 1444
    /// returns the number of occurrences of a key in an object
    inline size_type count(typename object_t::key_type key) const
    {
        // return 0 for all nonobject types
        return (m_type == value_t::object) ? m_value.object->count(key) : 0;
    }

N
Niels 已提交
1445

N
cleanup  
Niels 已提交
1446 1447 1448 1449
    ///////////////
    // iterators //
    ///////////////

N
Niels 已提交
1450 1451 1452 1453
    /*!
    @brief returns an iterator to the first element
    @ingroup container
    */
N
cleanup  
Niels 已提交
1454 1455 1456 1457 1458 1459 1460
    inline iterator begin() noexcept
    {
        iterator result(this);
        result.set_begin();
        return result;
    }

N
Niels 已提交
1461 1462 1463 1464
    /*!
    @brief returns a const iterator to the first element
    @ingroup container
    */
N
cleanup  
Niels 已提交
1465 1466
    inline const_iterator begin() const noexcept
    {
N
Niels 已提交
1467
        return cbegin();
N
cleanup  
Niels 已提交
1468 1469
    }

N
Niels 已提交
1470 1471 1472 1473
    /*!
    @brief returns a const iterator to the first element
    @ingroup container
    */
N
cleanup  
Niels 已提交
1474 1475 1476 1477 1478 1479 1480
    inline const_iterator cbegin() const noexcept
    {
        const_iterator result(this);
        result.set_begin();
        return result;
    }

N
Niels 已提交
1481 1482 1483 1484
    /*!
    @brief returns an iterator to one past the last element
    @ingroup container
    */
N
cleanup  
Niels 已提交
1485 1486 1487 1488 1489 1490 1491
    inline iterator end() noexcept
    {
        iterator result(this);
        result.set_end();
        return result;
    }

N
Niels 已提交
1492 1493 1494 1495
    /*!
    @brief returns a const iterator to one past the last element
    @ingroup container
    */
N
cleanup  
Niels 已提交
1496 1497
    inline const_iterator end() const noexcept
    {
N
Niels 已提交
1498
        return cend();
N
cleanup  
Niels 已提交
1499 1500
    }

N
Niels 已提交
1501 1502 1503 1504
    /*!
    @brief returns a const iterator to one past the last element
    @ingroup container
    */
N
cleanup  
Niels 已提交
1505 1506 1507 1508 1509 1510 1511
    inline const_iterator cend() const noexcept
    {
        const_iterator result(this);
        result.set_end();
        return result;
    }

N
Niels 已提交
1512 1513 1514 1515
    /*!
    @brief returns a reverse iterator to the first element
    @ingroup reversiblecontainer
    */
N
Niels 已提交
1516 1517 1518 1519 1520
    inline reverse_iterator rbegin() noexcept
    {
        return reverse_iterator(end());
    }

N
Niels 已提交
1521 1522 1523 1524
    /*!
    @brief returns a const reverse iterator to the first element
    @ingroup reversiblecontainer
    */
N
Niels 已提交
1525 1526
    inline const_reverse_iterator rbegin() const noexcept
    {
N
Niels 已提交
1527
        return crbegin();
N
Niels 已提交
1528 1529
    }

N
Niels 已提交
1530 1531 1532 1533
    /*!
    @brief returns a reverse iterator to one past the last element
    @ingroup reversiblecontainer
    */
N
Niels 已提交
1534 1535 1536 1537 1538
    inline reverse_iterator rend() noexcept
    {
        return reverse_iterator(begin());
    }

N
Niels 已提交
1539 1540 1541 1542
    /*!
    @brief returns a const reverse iterator to one past the last element
    @ingroup reversiblecontainer
    */
N
Niels 已提交
1543 1544
    inline const_reverse_iterator rend() const noexcept
    {
N
Niels 已提交
1545
        return crend();
N
Niels 已提交
1546 1547
    }

N
Niels 已提交
1548 1549 1550 1551
    /*!
    @brief returns a const reverse iterator to the first element
    @ingroup reversiblecontainer
    */
N
Niels 已提交
1552 1553 1554 1555 1556
    inline const_reverse_iterator crbegin() const noexcept
    {
        return const_reverse_iterator(cend());
    }

N
Niels 已提交
1557 1558 1559 1560
    /*!
    @brief returns a const reverse iterator to one past the last element
    @ingroup reversiblecontainer
    */
N
Niels 已提交
1561 1562 1563 1564 1565
    inline const_reverse_iterator crend() const noexcept
    {
        return const_reverse_iterator(cbegin());
    }

N
cleanup  
Niels 已提交
1566 1567 1568 1569 1570

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

N
Niels 已提交
1571 1572 1573 1574
    /*!
    @brief checks whether the container is empty
    @ingroup container
    */
N
cleanup  
Niels 已提交
1575 1576 1577 1578 1579 1580 1581 1582
    inline bool empty() const noexcept
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                return true;
            }
N
Niels 已提交
1583

N
cleanup  
Niels 已提交
1584 1585 1586 1587
            case (value_t::array):
            {
                return m_value.array->empty();
            }
N
Niels 已提交
1588

N
cleanup  
Niels 已提交
1589 1590 1591 1592
            case (value_t::object):
            {
                return m_value.object->empty();
            }
N
Niels 已提交
1593

N
Niels 已提交
1594 1595 1596 1597 1598 1599
            default:
            {
                // all other types are nonempty
                return false;
            }
        }
N
cleanup  
Niels 已提交
1600 1601
    }

N
Niels 已提交
1602 1603 1604 1605
    /*!
    @brief returns the number of elements
    @ingroup container
    */
N
cleanup  
Niels 已提交
1606 1607 1608 1609 1610 1611 1612 1613
    inline size_type size() const noexcept
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                return 0;
            }
N
Niels 已提交
1614

N
cleanup  
Niels 已提交
1615 1616 1617 1618
            case (value_t::array):
            {
                return m_value.array->size();
            }
N
Niels 已提交
1619

N
cleanup  
Niels 已提交
1620 1621 1622 1623
            case (value_t::object):
            {
                return m_value.object->size();
            }
N
Niels 已提交
1624

N
Niels 已提交
1625 1626 1627 1628 1629 1630
            default:
            {
                // all other types have size 1
                return 1;
            }
        }
N
cleanup  
Niels 已提交
1631 1632
    }

N
Niels 已提交
1633 1634 1635 1636
    /*!
    @brief returns the maximum possible number of elements
    @ingroup container
    */
N
cleanup  
Niels 已提交
1637 1638 1639 1640 1641 1642 1643 1644
    inline size_type max_size() const noexcept
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                return 0;
            }
N
Niels 已提交
1645

N
cleanup  
Niels 已提交
1646 1647 1648 1649
            case (value_t::array):
            {
                return m_value.array->max_size();
            }
N
Niels 已提交
1650

N
cleanup  
Niels 已提交
1651 1652 1653 1654
            case (value_t::object):
            {
                return m_value.object->max_size();
            }
N
Niels 已提交
1655

N
Niels 已提交
1656 1657 1658 1659 1660 1661
            default:
            {
                // all other types have max_size 1
                return 1;
            }
        }
N
cleanup  
Niels 已提交
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
    }


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

    /// clears the contents
    inline void clear() noexcept
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                break;
            }
N
Niels 已提交
1678

N
cleanup  
Niels 已提交
1679 1680
            case (value_t::number_integer):
            {
N
Niels 已提交
1681
                m_value.number_integer = 0;
N
cleanup  
Niels 已提交
1682 1683
                break;
            }
N
Niels 已提交
1684

N
cleanup  
Niels 已提交
1685 1686
            case (value_t::number_float):
            {
N
Niels 已提交
1687
                m_value.number_float = 0.0;
N
cleanup  
Niels 已提交
1688 1689
                break;
            }
N
Niels 已提交
1690

N
cleanup  
Niels 已提交
1691 1692
            case (value_t::boolean):
            {
N
Niels 已提交
1693
                m_value.boolean = false;
N
cleanup  
Niels 已提交
1694 1695
                break;
            }
N
Niels 已提交
1696

N
cleanup  
Niels 已提交
1697 1698 1699 1700 1701
            case (value_t::string):
            {
                m_value.string->clear();
                break;
            }
N
Niels 已提交
1702

N
cleanup  
Niels 已提交
1703 1704 1705 1706 1707
            case (value_t::array):
            {
                m_value.array->clear();
                break;
            }
N
Niels 已提交
1708

N
cleanup  
Niels 已提交
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
            case (value_t::object):
            {
                m_value.object->clear();
                break;
            }
        }
    }

    /// add an object to an array
    inline void push_back(basic_json&& value)
    {
        // push_back only works for null objects or arrays
        if (not(m_type == value_t::null or m_type == value_t::array))
        {
            throw std::runtime_error("cannot add element to " + type_name());
        }

        // transform null object into an array
        if (m_type == value_t::null)
        {
            m_type = value_t::array;
N
Niels 已提交
1730
            AllocatorType<array_t> alloc;
N
Niels 已提交
1731 1732
            m_value.array = alloc.allocate(1);
            alloc.construct(m_value.array);
N
cleanup  
Niels 已提交
1733 1734 1735 1736 1737 1738 1739 1740
        }

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

N
Niels 已提交
1741 1742 1743 1744 1745 1746 1747
    /// add an object to an array
    inline reference operator+=(basic_json&& value)
    {
        push_back(std::move(value));
        return *this;
    }

N
cleanup  
Niels 已提交
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
    /// add an object to an array
    inline void push_back(const basic_json& value)
    {
        // push_back only works for null objects or arrays
        if (not(m_type == value_t::null or m_type == value_t::array))
        {
            throw std::runtime_error("cannot add element to " + type_name());
        }

        // transform null object into an array
        if (m_type == value_t::null)
        {
            m_type = value_t::array;
N
Niels 已提交
1761
            AllocatorType<array_t> alloc;
N
Niels 已提交
1762 1763
            m_value.array = alloc.allocate(1);
            alloc.construct(m_value.array);
N
cleanup  
Niels 已提交
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
        }

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

    /// add an object to an array
    inline reference operator+=(const basic_json& value)
    {
        push_back(value);
        return *this;
    }

    /// add an object to an object
    inline void push_back(const typename object_t::value_type& value)
    {
        // push_back only works for null objects or objects
        if (not(m_type == value_t::null or m_type == value_t::object))
        {
            throw std::runtime_error("cannot add element to " + type_name());
        }

        // transform null object into an object
        if (m_type == value_t::null)
        {
            m_type = value_t::object;
N
Niels 已提交
1790
            AllocatorType<object_t> alloc;
N
Niels 已提交
1791 1792
            m_value.object = alloc.allocate(1);
            alloc.construct(m_value.object);
N
cleanup  
Niels 已提交
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
        }

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

    /// add an object to an object
    inline reference operator+=(const typename object_t::value_type& value)
    {
        push_back(value);
        return operator[](value.first);
    }

N
Niels 已提交
1806 1807 1808 1809
    /*!
    @brief exchanges the values
    @ingroup container
    */
N
Niels 已提交
1810 1811 1812 1813 1814 1815
    inline void swap(reference other) noexcept (
        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
cleanup  
Niels 已提交
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
    {
        std::swap(m_type, other.m_type);
        std::swap(m_value, other.m_value);
    }

    /// swaps the contents
    inline void swap(array_t& other)
    {
        // swap only works for arrays
        if (m_type != value_t::array)
        {
            throw std::runtime_error("cannot use swap with " + type_name());
        }

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

    /// swaps the contents
    inline void swap(object_t& other)
    {
        // swap only works for objects
        if (m_type != value_t::object)
        {
            throw std::runtime_error("cannot use swap with " + type_name());
        }

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

    /// swaps the contents
    inline void swap(string_t& other)
    {
        // swap only works for strings
        if (m_type != value_t::string)
        {
            throw std::runtime_error("cannot use swap with " + type_name());
        }

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


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

N
Niels 已提交
1865 1866 1867 1868
    /*!
    @brief comparison: equal
    @ingroup container
    */
N
Niels 已提交
1869
    friend bool operator==(const_reference lhs, const_reference rhs) noexcept
N
cleanup  
Niels 已提交
1870
    {
F
Florian Weber 已提交
1871 1872 1873
        const auto lhs_type = lhs.type();
        const auto rhs_type = rhs.type();
        if (lhs_type == rhs_type)
N
cleanup  
Niels 已提交
1874
        {
F
Florian Weber 已提交
1875
            switch (lhs_type)
N
cleanup  
Niels 已提交
1876
            {
F
Florian Weber 已提交
1877
                case (value_t::array):
N
cleanup  
Niels 已提交
1878 1879 1880
                {
                    return *lhs.m_value.array == *rhs.m_value.array;
                }
F
Florian Weber 已提交
1881
                case (value_t::object):
N
cleanup  
Niels 已提交
1882 1883 1884
                {
                    return *lhs.m_value.object == *rhs.m_value.object;
                }
F
Florian Weber 已提交
1885
                case (value_t::null):
N
cleanup  
Niels 已提交
1886 1887 1888
                {
                    return true;
                }
F
Florian Weber 已提交
1889
                case (value_t::string):
N
cleanup  
Niels 已提交
1890 1891 1892
                {
                    return *lhs.m_value.string == *rhs.m_value.string;
                }
F
Florian Weber 已提交
1893
                case (value_t::boolean):
N
cleanup  
Niels 已提交
1894 1895 1896
                {
                    return lhs.m_value.boolean == rhs.m_value.boolean;
                }
F
Florian Weber 已提交
1897
                case (value_t::number_integer):
N
cleanup  
Niels 已提交
1898 1899 1900
                {
                    return lhs.m_value.number_integer == rhs.m_value.number_integer;
                }
F
Florian Weber 已提交
1901
                case (value_t::number_float):
N
cleanup  
Niels 已提交
1902
                {
1903
                    return approx(lhs.m_value.number_float, rhs.m_value.number_float);
N
cleanup  
Niels 已提交
1904 1905 1906
                }
            }
        }
F
Florian Weber 已提交
1907 1908 1909 1910 1911 1912 1913 1914 1915 1916
        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
        {
            return lhs.m_value.number_integer ==
                   static_cast<number_integer_t>(rhs.m_value.number_float);
        }
        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
cleanup  
Niels 已提交
1917 1918 1919
        return false;
    }

N
Niels 已提交
1920 1921 1922 1923
    /*!
    @brief comparison: not equal
    @ingroup container
    */
N
Niels 已提交
1924
    friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
N
cleanup  
Niels 已提交
1925 1926 1927 1928 1929
    {
        return not (lhs == rhs);
    }

    /// comparison: less than
N
Niels 已提交
1930
    friend bool operator<(const_reference lhs, const_reference rhs) noexcept
N
cleanup  
Niels 已提交
1931
    {
F
Florian Weber 已提交
1932 1933 1934
        const auto lhs_type = lhs.type();
        const auto rhs_type = rhs.type();
        if (lhs_type == rhs_type)
N
cleanup  
Niels 已提交
1935
        {
F
Florian Weber 已提交
1936
            switch (lhs_type)
N
cleanup  
Niels 已提交
1937
            {
F
Florian Weber 已提交
1938
                case (value_t::array):
N
cleanup  
Niels 已提交
1939
                {
F
Florian Weber 已提交
1940
                    return *lhs.m_value.array < *rhs.m_value.array;
N
cleanup  
Niels 已提交
1941
                }
F
Florian Weber 已提交
1942
                case (value_t::object):
N
cleanup  
Niels 已提交
1943 1944 1945
                {
                    return *lhs.m_value.object < *rhs.m_value.object;
                }
F
Florian Weber 已提交
1946
                case (value_t::null):
N
cleanup  
Niels 已提交
1947 1948 1949
                {
                    return false;
                }
F
Florian Weber 已提交
1950
                case (value_t::string):
N
cleanup  
Niels 已提交
1951 1952 1953
                {
                    return *lhs.m_value.string < *rhs.m_value.string;
                }
F
Florian Weber 已提交
1954
                case (value_t::boolean):
N
cleanup  
Niels 已提交
1955 1956 1957
                {
                    return lhs.m_value.boolean < rhs.m_value.boolean;
                }
F
Florian Weber 已提交
1958
                case (value_t::number_integer):
N
cleanup  
Niels 已提交
1959 1960 1961
                {
                    return lhs.m_value.number_integer < rhs.m_value.number_integer;
                }
F
Florian Weber 已提交
1962
                case (value_t::number_float):
N
cleanup  
Niels 已提交
1963 1964 1965 1966 1967
                {
                    return lhs.m_value.number_float < rhs.m_value.number_float;
                }
            }
        }
F
Florian Weber 已提交
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
        {
            return lhs.m_value.number_integer <
                   static_cast<number_integer_t>(rhs.m_value.number_float);
        }
        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
cleanup  
Niels 已提交
1978

N
Niels 已提交
1979 1980
        // We only reach this line if we cannot compare values. In that case,
        // we compare types.
F
Florian Weber 已提交
1981
        return lhs_type < rhs_type;
N
cleanup  
Niels 已提交
1982 1983 1984
    }

    /// comparison: less than or equal
N
Niels 已提交
1985
    friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
N
cleanup  
Niels 已提交
1986 1987 1988 1989 1990
    {
        return not (rhs < lhs);
    }

    /// comparison: greater than
N
Niels 已提交
1991
    friend bool operator>(const_reference lhs, const_reference rhs) noexcept
N
cleanup  
Niels 已提交
1992 1993 1994 1995 1996
    {
        return not (lhs <= rhs);
    }

    /// comparison: greater than or equal
N
Niels 已提交
1997
    friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
N
cleanup  
Niels 已提交
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
    {
        return not (lhs < rhs);
    }


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

    /// serialize to stream
    friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
    {
N
Niels 已提交
2010 2011 2012 2013
        // read width member and use it as indentation parameter if nonzero
        const int indentation = (o.width() == 0) ? -1 : o.width();

        o << j.dump(indentation);
N
cleanup  
Niels 已提交
2014 2015 2016 2017 2018 2019
        return o;
    }

    /// serialize to stream
    friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
    {
N
Niels 已提交
2020 2021 2022 2023
        // read width member and use it as indentation parameter if nonzero
        const int indentation = (o.width() == 0) ? -1 : o.width();

        o << j.dump(indentation);
N
cleanup  
Niels 已提交
2024 2025 2026 2027
        return o;
    }


N
Niels 已提交
2028 2029 2030 2031 2032
    /////////////////////
    // deserialization //
    /////////////////////

    /// deserialize from string
N
Niels 已提交
2033
    static basic_json parse(const string_t& s)
N
Niels 已提交
2034 2035 2036 2037
    {
        return parser(s).parse();
    }

A
Aaron Burghardt 已提交
2038 2039 2040 2041
    /// deserialize from stream
    static basic_json parse(std::istream& i)
    {
        return parser(i).parse();
N
Niels 已提交
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
    }

    /// 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;
    }


N
cleanup  
Niels 已提交
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
  private:
    ///////////////////////////
    // convenience functions //
    ///////////////////////////

    /// return the type as string
    inline string_t type_name() const noexcept
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                return "null";
            }
N
Niels 已提交
2073

N
cleanup  
Niels 已提交
2074 2075 2076 2077
            case (value_t::object):
            {
                return "object";
            }
N
Niels 已提交
2078

N
cleanup  
Niels 已提交
2079 2080 2081 2082
            case (value_t::array):
            {
                return "array";
            }
N
Niels 已提交
2083

N
cleanup  
Niels 已提交
2084 2085 2086 2087
            case (value_t::string):
            {
                return "string";
            }
N
Niels 已提交
2088

N
cleanup  
Niels 已提交
2089 2090 2091 2092
            case (value_t::boolean):
            {
                return "boolean";
            }
N
Niels 已提交
2093 2094

            default:
N
cleanup  
Niels 已提交
2095 2096 2097 2098 2099 2100
            {
                return "number";
            }
        }
    }

N
Niels 已提交
2101
    /*!
N
Niels 已提交
2102
    @brief escape a string
N
Niels 已提交
2103

N
Niels 已提交
2104 2105 2106 2107 2108 2109 2110
    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.

    @param s  the string to escape
    @return escaped string
N
Niels 已提交
2111
    */
N
Niels 已提交
2112
    static string_t escape_string(const string_t& s) noexcept
N
Niels 已提交
2113 2114 2115 2116 2117
    {
        // create a result string of at least the size than s
        string_t result;
        result.reserve(s.size());

N
Niels 已提交
2118
        for (const auto c : s)
N
Niels 已提交
2119 2120 2121
        {
            switch (c)
            {
N
Niels 已提交
2122
                // quotation mark (0x22)
N
Niels 已提交
2123 2124
                case '"':
                {
N
Niels 已提交
2125
                    result += "\\\"";
N
Niels 已提交
2126 2127
                    break;
                }
N
Niels 已提交
2128

N
Niels 已提交
2129
                // reverse solidus (0x5c)
N
Niels 已提交
2130 2131
                case '\\':
                {
N
Niels 已提交
2132
                    result += "\\\\";
N
Niels 已提交
2133 2134
                    break;
                }
N
Niels 已提交
2135

N
Niels 已提交
2136
                // backspace (0x08)
N
Niels 已提交
2137 2138
                case '\b':
                {
N
Niels 已提交
2139
                    result += "\\b";
N
Niels 已提交
2140 2141
                    break;
                }
N
Niels 已提交
2142

N
Niels 已提交
2143
                // formfeed (0x0c)
N
Niels 已提交
2144 2145
                case '\f':
                {
N
Niels 已提交
2146
                    result += "\\f";
N
Niels 已提交
2147 2148
                    break;
                }
N
Niels 已提交
2149

N
Niels 已提交
2150
                // newline (0x0a)
N
Niels 已提交
2151 2152
                case '\n':
                {
N
Niels 已提交
2153
                    result += "\\n";
N
Niels 已提交
2154 2155
                    break;
                }
N
Niels 已提交
2156

N
Niels 已提交
2157
                // carriage return (0x0d)
N
Niels 已提交
2158 2159
                case '\r':
                {
N
Niels 已提交
2160
                    result += "\\r";
N
Niels 已提交
2161 2162
                    break;
                }
N
Niels 已提交
2163

N
Niels 已提交
2164
                // horizontal tab (0x09)
N
Niels 已提交
2165 2166
                case '\t':
                {
N
Niels 已提交
2167
                    result += "\\t";
N
Niels 已提交
2168 2169
                    break;
                }
N
Niels 已提交
2170

N
Niels 已提交
2171 2172
                default:
                {
N
Niels 已提交
2173
                    if (c >= 0 and c <= 0x1f)
N
Niels 已提交
2174 2175 2176
                    {
                        // control characters (everything between 0x00 and 0x1f)
                        // -> create four-digit hex representation
N
Niels 已提交
2177
                        std::basic_stringstream<typename string_t::value_type> ss;
N
Niels 已提交
2178 2179 2180 2181 2182 2183 2184 2185 2186
                        ss << "\\u" << std::hex << std::setw(4) << std::setfill('0') << int(c);
                        result += ss.str();
                    }
                    else
                    {
                        // all other characters are added as-is
                        result.append(1, c);
                    }
                    break;
N
Niels 已提交
2187 2188 2189 2190 2191 2192 2193
                }
            }
        }

        return result;
    }

N
Niels 已提交
2194

N
cleanup  
Niels 已提交
2195
    /*!
N
Niels 已提交
2196
    @brief internal implementation of the serialization function
N
Niels 已提交
2197

N
Niels 已提交
2198 2199 2200 2201
    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 已提交
2202

N
Niels 已提交
2203
    - strings and object keys are escaped using escape_string()
N
Niels 已提交
2204 2205 2206
    - integer numbers are converted to a string before output using
      std::to_string()
    - floating-point numbers are converted to a string using "%g" format
N
cleanup  
Niels 已提交
2207 2208 2209 2210 2211 2212

    @param prettyPrint    whether the output shall be pretty-printed
    @param indentStep     the indent level
    @param currentIndent  the current indent level (only used internally)
    */
    inline string_t dump(const bool prettyPrint, const unsigned int indentStep,
N
Niels 已提交
2213
                         const unsigned int currentIndent = 0) const noexcept
N
cleanup  
Niels 已提交
2214
    {
N
Niels 已提交
2215 2216 2217
        // variable to hold indentation for recursive calls
        auto new_indent = currentIndent;

N
cleanup  
Niels 已提交
2218
        // helper function to return whitespace as indentation
N
Niels 已提交
2219
        const auto indent = [prettyPrint, &new_indent]()
N
cleanup  
Niels 已提交
2220
        {
N
Niels 已提交
2221
            return prettyPrint ? string_t(new_indent, ' ') : string_t();
N
cleanup  
Niels 已提交
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
        };

        switch (m_type)
        {
            case (value_t::object):
            {
                if (m_value.object->empty())
                {
                    return "{}";
                }

                string_t result = "{";

                // increase indentation
                if (prettyPrint)
                {
N
Niels 已提交
2238
                    new_indent += indentStep;
N
cleanup  
Niels 已提交
2239 2240 2241
                    result += "\n";
                }

N
Niels 已提交
2242
                for (auto i = m_value.object->cbegin(); i != m_value.object->cend(); ++i)
N
cleanup  
Niels 已提交
2243
                {
N
Niels 已提交
2244
                    if (i != m_value.object->cbegin())
N
cleanup  
Niels 已提交
2245 2246 2247
                    {
                        result += prettyPrint ? ",\n" : ",";
                    }
N
Niels 已提交
2248
                    result += indent() + "\"" + escape_string(i->first) + "\":" + (prettyPrint ? " " : "")
N
Niels 已提交
2249
                              + i->second.dump(prettyPrint, indentStep, new_indent);
N
cleanup  
Niels 已提交
2250 2251 2252 2253 2254
                }

                // decrease indentation
                if (prettyPrint)
                {
N
Niels 已提交
2255
                    new_indent -= indentStep;
N
cleanup  
Niels 已提交
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273
                    result += "\n";
                }

                return result + indent() + "}";
            }

            case (value_t::array):
            {
                if (m_value.array->empty())
                {
                    return "[]";
                }

                string_t result = "[";

                // increase indentation
                if (prettyPrint)
                {
N
Niels 已提交
2274
                    new_indent += indentStep;
N
cleanup  
Niels 已提交
2275 2276 2277
                    result += "\n";
                }

N
Niels 已提交
2278
                for (auto i = m_value.array->cbegin(); i != m_value.array->cend(); ++i)
N
cleanup  
Niels 已提交
2279
                {
N
Niels 已提交
2280
                    if (i != m_value.array->cbegin())
N
cleanup  
Niels 已提交
2281 2282 2283
                    {
                        result += prettyPrint ? ",\n" : ",";
                    }
N
Niels 已提交
2284
                    result += indent() + i->dump(prettyPrint, indentStep, new_indent);
N
cleanup  
Niels 已提交
2285 2286 2287 2288 2289
                }

                // decrease indentation
                if (prettyPrint)
                {
N
Niels 已提交
2290
                    new_indent -= indentStep;
N
cleanup  
Niels 已提交
2291 2292 2293 2294 2295 2296 2297 2298
                    result += "\n";
                }

                return result + indent() + "]";
            }

            case (value_t::string):
            {
N
Niels 已提交
2299
                return string_t("\"") + escape_string(*m_value.string) + "\"";
N
cleanup  
Niels 已提交
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
            }

            case (value_t::boolean):
            {
                return m_value.boolean ? "true" : "false";
            }

            case (value_t::number_integer):
            {
                return std::to_string(m_value.number_integer);
            }

            case (value_t::number_float):
            {
N
Niels 已提交
2314 2315 2316
                // 15 digits of precision allows round-trip IEEE 754
                // string->double->string
                const auto sz = static_cast<unsigned int>(std::snprintf(nullptr, 0, "%.15g", m_value.number_float));
N
Niels 已提交
2317
                std::vector<typename string_t::value_type> buf(sz + 1);
N
Niels 已提交
2318 2319
                std::snprintf(&buf[0], buf.size(), "%.15g", m_value.number_float);
                return string_t(buf.data());
N
cleanup  
Niels 已提交
2320
            }
N
Niels 已提交
2321 2322 2323 2324 2325

            default:
            {
                return "null";
            }
N
cleanup  
Niels 已提交
2326 2327 2328
        }
    }

2329 2330 2331 2332 2333 2334 2335
    /// "equality" comparison for floating point numbers
    template<typename T>
    inline static bool approx(const T a, const T b)
    {
        return not (a > b or a < b);
    }

N
cleanup  
Niels 已提交
2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350

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

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

    /// whether the type of JSON object may change later
    bool m_final = false;

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

N
Niels 已提交
2351

N
Niels 已提交
2352
  private:
N
cleanup  
Niels 已提交
2353 2354 2355 2356
    ///////////////
    // iterators //
    ///////////////

N
Niels 已提交
2357
    /// an iterator value
N
Niels 已提交
2358
    template<typename array_iterator_t, typename object_iterator_t>
N
Niels 已提交
2359 2360 2361
    union internal_iterator
    {
        /// iterator for JSON objects
N
Niels 已提交
2362
        object_iterator_t object_iterator;
N
Niels 已提交
2363
        /// iterator for JSON arrays
N
Niels 已提交
2364
        array_iterator_t array_iterator;
N
Niels 已提交
2365
        /// generic iteraotr for all other value types
N
Niels 已提交
2366
        difference_type generic_iterator;
N
Niels 已提交
2367 2368

        /// default constructor
N
Niels 已提交
2369
        internal_iterator() : generic_iterator(-1) {}
N
Niels 已提交
2370 2371 2372
    };

  public:
N
Niels 已提交
2373 2374
    /// a random access iterator for the basic_json class
    class iterator : public std::iterator<std::random_access_iterator_tag, basic_json>
N
cleanup  
Niels 已提交
2375
    {
2376 2377 2378
        // allow basic_json class to access m_it
        friend class basic_json;

N
cleanup  
Niels 已提交
2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390
      public:
        /// the type of the values when the iterator is dereferenced
        using value_type = basic_json::value_type;
        /// a type to represent differences between iterators
        using difference_type = basic_json::difference_type;
        /// defines a pointer to the type iterated over (value_type)
        using pointer = basic_json::pointer;
        /// defines a reference to the type iterated over (value_type)
        using reference = basic_json::reference;
        /// the category of the iterator
        using iterator_category = std::bidirectional_iterator_tag;

2391 2392 2393
        /// default constructor
        inline iterator() = default;

N
cleanup  
Niels 已提交
2394
        /// constructor for a given JSON instance
N
Niels 已提交
2395
        inline iterator(pointer object) noexcept : m_object(object)
N
cleanup  
Niels 已提交
2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410
        {
            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 已提交
2411
                    m_it.generic_iterator = -1;
N
cleanup  
Niels 已提交
2412 2413 2414 2415 2416
                    break;
                }
            }
        }

N
Niels 已提交
2417 2418 2419 2420 2421
        /// copy constructor
        inline iterator(const iterator& other) noexcept
            : m_object(other.m_object), m_it(other.m_it)
        {}

N
cleanup  
Niels 已提交
2422
        /// copy assignment
N
Niels 已提交
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
        inline iterator& operator=(iterator other) noexcept (
            std::is_nothrow_move_constructible<pointer>::value and
            std::is_nothrow_move_assignable<pointer>::value and
            std::is_nothrow_move_constructible<internal_iterator<typename array_t::iterator, typename object_t::iterator>>::value
            and
            std::is_nothrow_move_assignable<internal_iterator<typename array_t::iterator, typename object_t::iterator>>::value
        )
        {
            std::swap(m_object, other.m_object);
            std::swap(m_it, other.m_it);
N
cleanup  
Niels 已提交
2433 2434 2435
            return *this;
        }

N
Niels 已提交
2436
      private:
N
cleanup  
Niels 已提交
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
        /// set the iterator to the first value
        inline void set_begin() noexcept
        {
            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 已提交
2456
                    // set to end so begin()==end() is true: null is empty
N
Niels 已提交
2457
                    m_it.generic_iterator = 1;
N
cleanup  
Niels 已提交
2458 2459 2460 2461 2462
                    break;
                }

                default:
                {
N
Niels 已提交
2463
                    m_it.generic_iterator = 0;
N
cleanup  
Niels 已提交
2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
                    break;
                }
            }
        }

        /// set the iterator past the last value
        inline void set_end() noexcept
        {
            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 已提交
2488
                    m_it.generic_iterator = 1;
N
cleanup  
Niels 已提交
2489 2490 2491 2492 2493
                    break;
                }
            }
        }

N
Niels 已提交
2494
      public:
N
cleanup  
Niels 已提交
2495
        /// return a reference to the value pointed to by the iterator
N
Niels 已提交
2496
        inline reference operator*()
N
cleanup  
Niels 已提交
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
        {
            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 已提交
2517
                    if (m_it.generic_iterator == 0)
N
cleanup  
Niels 已提交
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
                    {
                        return *m_object;
                    }
                    else
                    {
                        throw std::out_of_range("cannot get value");
                    }
                }
            }
        }

        /// dereference the iterator
N
Niels 已提交
2530
        inline pointer operator->()
N
cleanup  
Niels 已提交
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543
        {
            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 已提交
2544 2545 2546 2547 2548
                case (basic_json::value_t::null):
                {
                    throw std::out_of_range("cannot get value");
                }

N
cleanup  
Niels 已提交
2549 2550
                default:
                {
N
Niels 已提交
2551
                    if (m_it.generic_iterator == 0)
N
cleanup  
Niels 已提交
2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
                    {
                        return m_object;
                    }
                    else
                    {
                        throw std::out_of_range("cannot get value");
                    }
                }
            }
        }

        /// post-increment (it++)
        inline iterator operator++(int)
        {
N
Niels 已提交
2566
            auto result = *this;
N
cleanup  
Niels 已提交
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583

            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 已提交
2584
                    m_it.generic_iterator++;
N
cleanup  
Niels 已提交
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
                    break;
                }
            }

            return result;
        }

        /// pre-increment (++it)
        inline iterator& operator++()
        {
            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 已提交
2611
                    ++m_it.generic_iterator;
N
cleanup  
Niels 已提交
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
                    break;
                }
            }

            return *this;
        }

        /// post-decrement (it--)
        inline iterator operator--(int)
        {
N
Niels 已提交
2622
            auto result = *this;
N
cleanup  
Niels 已提交
2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639

            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 已提交
2640
                    m_it.generic_iterator--;
N
cleanup  
Niels 已提交
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
                    break;
                }
            }

            return result;
        }

        /// pre-decrement (--it)
        inline iterator& operator--()
        {
            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 已提交
2667
                    --m_it.generic_iterator;
N
cleanup  
Niels 已提交
2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
                    break;
                }
            }

            return *this;
        }

        /// comparison: equal
        inline bool operator==(const iterator& other) const
        {
N
Niels 已提交
2678 2679
            // if objects are not the same, the comparison is undefined
            if (m_object != other.m_object)
N
cleanup  
Niels 已提交
2680
            {
N
Niels 已提交
2681
                throw std::domain_error("cannot compare iterators of different containers");
N
cleanup  
Niels 已提交
2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
            }

            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
        inline bool operator!=(const iterator& other) const
        {
            return not operator==(other);
        }

N
Niels 已提交
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 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 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 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 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
        /// comparison: smaller
        inline bool operator<(const iterator& other) const
        {
            // 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
        inline bool operator<=(const iterator& other) const
        {
            return not other.operator < (*this);
        }

        /// comparison: greater than
        inline bool operator>(const iterator& other) const
        {
            return not operator<=(other);
        }

        /// comparison: greater than or equal
        inline bool operator>=(const iterator& other) const
        {
            return not operator<(other);
        }

        /// add to iterator
        inline iterator& operator+=(difference_type i)
        {
            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
        inline iterator& operator-=(difference_type i)
        {
            return operator+=(-i);
        }

        /// add to iterator
        inline iterator operator+(difference_type i)
        {
            auto result = *this;
            result += i;
            return result;
        }

        /// subtract from iterator
        inline iterator operator-(difference_type i)
        {
            auto result = *this;
            result -= i;
            return result;
        }

        /// return difference
        inline difference_type operator-(const iterator& other) const
        {
            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
        inline reference operator[](difference_type n)
        {
            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");
                    }
                }
            }
        }

2860
        /// return the key of an object iterator
N
Niels 已提交
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876
        inline typename object_t::key_type key() const
        {
            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");
                }
            }
        }

2877
        /// return the key of an iterator
N
Niels 已提交
2878 2879 2880 2881 2882
        inline reference value()
        {
            return operator*();
        }

N
cleanup  
Niels 已提交
2883 2884 2885 2886
      private:
        /// associated JSON instance
        pointer m_object = nullptr;
        /// the actual iterator of the associated instance
N
Niels 已提交
2887
        internal_iterator<typename array_t::iterator, typename object_t::iterator> m_it;
N
cleanup  
Niels 已提交
2888 2889
    };

N
Niels 已提交
2890 2891
    /// 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
cleanup  
Niels 已提交
2892
    {
2893 2894 2895
        // allow basic_json class to access m_it
        friend class basic_json;

N
cleanup  
Niels 已提交
2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907
      public:
        /// the type of the values when the iterator is dereferenced
        using value_type = basic_json::value_type;
        /// a type to represent differences between iterators
        using difference_type = basic_json::difference_type;
        /// defines a pointer to the type iterated over (value_type)
        using pointer = basic_json::const_pointer;
        /// defines a reference to the type iterated over (value_type)
        using reference = basic_json::const_reference;
        /// the category of the iterator
        using iterator_category = std::bidirectional_iterator_tag;

2908 2909 2910
        /// default constructor
        inline const_iterator() = default;

N
cleanup  
Niels 已提交
2911
        /// constructor for a given JSON instance
N
Niels 已提交
2912
        inline const_iterator(pointer object) noexcept : m_object(object)
N
cleanup  
Niels 已提交
2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    m_it.object_iterator = typename object_t::const_iterator();
                    break;
                }
                case (basic_json::value_t::array):
                {
                    m_it.array_iterator = typename array_t::const_iterator();
                    break;
                }
                default:
                {
N
Niels 已提交
2928
                    m_it.generic_iterator = -1;
N
cleanup  
Niels 已提交
2929 2930 2931 2932 2933
                    break;
                }
            }
        }

N
Niels 已提交
2934
        /// copy constructor given a nonconst iterator
N
Niels 已提交
2935
        inline const_iterator(const iterator& other) noexcept : m_object(other.m_object)
N
Niels 已提交
2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957
        {
            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
cleanup  
Niels 已提交
2958

N
Niels 已提交
2959 2960 2961 2962 2963
        /// copy constructor
        inline const_iterator(const const_iterator& other) noexcept
            : m_object(other.m_object), m_it(other.m_it)
        {}

N
cleanup  
Niels 已提交
2964
        /// copy assignment
N
Niels 已提交
2965 2966 2967 2968 2969 2970 2971 2972 2973 2974
        inline const_iterator& operator=(const_iterator other) noexcept(
            std::is_nothrow_move_constructible<pointer>::value and
            std::is_nothrow_move_assignable<pointer>::value and
            std::is_nothrow_move_constructible<internal_iterator<typename array_t::const_iterator, typename object_t::const_iterator>>::value
            and
            std::is_nothrow_move_assignable<internal_iterator<typename array_t::const_iterator, typename object_t::const_iterator>>::value
        )
        {
            std::swap(m_object, other.m_object);
            std::swap(m_it, other.m_it);
N
cleanup  
Niels 已提交
2975 2976 2977
            return *this;
        }

N
Niels 已提交
2978
      private:
N
cleanup  
Niels 已提交
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997
        /// set the iterator to the first value
        inline void set_begin() noexcept
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    m_it.object_iterator = m_object->m_value.object->cbegin();
                    break;
                }

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

                case (basic_json::value_t::null):
                {
N
Niels 已提交
2998
                    // set to end so begin()==end() is true: null is empty
N
Niels 已提交
2999
                    m_it.generic_iterator = 1;
N
cleanup  
Niels 已提交
3000 3001 3002 3003 3004
                    break;
                }

                default:
                {
N
Niels 已提交
3005
                    m_it.generic_iterator = 0;
N
cleanup  
Niels 已提交
3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029
                    break;
                }
            }
        }

        /// set the iterator past the last value
        inline void set_end() noexcept
        {
            switch (m_object->m_type)
            {
                case (basic_json::value_t::object):
                {
                    m_it.object_iterator = m_object->m_value.object->cend();
                    break;
                }

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

                default:
                {
N
Niels 已提交
3030
                    m_it.generic_iterator = 1;
N
cleanup  
Niels 已提交
3031 3032 3033 3034 3035
                    break;
                }
            }
        }

N
Niels 已提交
3036
      public:
N
cleanup  
Niels 已提交
3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058
        /// return a reference to the value pointed to by the iterator
        inline reference operator*() const
        {
            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 已提交
3059
                    if (m_it.generic_iterator == 0)
N
cleanup  
Niels 已提交
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087
                    {
                        return *m_object;
                    }
                    else
                    {
                        throw std::out_of_range("cannot get value");
                    }
                }
            }
        }

        /// dereference the iterator
        inline pointer operator->() const
        {
            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 已提交
3088
                    if (m_it.generic_iterator == 0)
N
cleanup  
Niels 已提交
3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102
                    {
                        return m_object;
                    }
                    else
                    {
                        throw std::out_of_range("cannot get value");
                    }
                }
            }
        }

        /// post-increment (it++)
        inline const_iterator operator++(int)
        {
N
Niels 已提交
3103
            auto result = *this;
N
cleanup  
Niels 已提交
3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120

            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 已提交
3121
                    m_it.generic_iterator++;
N
cleanup  
Niels 已提交
3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147
                    break;
                }
            }

            return result;
        }

        /// pre-increment (++it)
        inline const_iterator& operator++()
        {
            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 已提交
3148
                    ++m_it.generic_iterator;
N
cleanup  
Niels 已提交
3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
                    break;
                }
            }

            return *this;
        }

        /// post-decrement (it--)
        inline const_iterator operator--(int)
        {
N
Niels 已提交
3159
            auto result = *this;
N
cleanup  
Niels 已提交
3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176

            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 已提交
3177
                    m_it.generic_iterator--;
N
cleanup  
Niels 已提交
3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203
                    break;
                }
            }

            return result;
        }

        /// pre-decrement (--it)
        inline const_iterator& operator--()
        {
            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 已提交
3204
                    --m_it.generic_iterator;
N
cleanup  
Niels 已提交
3205 3206 3207 3208 3209 3210 3211 3212 3213 3214
                    break;
                }
            }

            return *this;
        }

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

            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
        inline bool operator!=(const const_iterator& other) const
        {
            return not operator==(other);
        }

N
Niels 已提交
3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 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 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 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 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395
        /// comparison: smaller
        inline bool operator<(const const_iterator& other) const
        {
            // 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
        inline bool operator<=(const const_iterator& other) const
        {
            return not other.operator < (*this);
        }

        /// comparison: greater than
        inline bool operator>(const const_iterator& other) const
        {
            return not operator<=(other);
        }

        /// comparison: greater than or equal
        inline bool operator>=(const const_iterator& other) const
        {
            return not operator<(other);
        }

        /// add to iterator
        inline const_iterator& operator+=(difference_type i)
        {
            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
        inline const_iterator& operator-=(difference_type i)
        {
            return operator+=(-i);
        }

        /// add to iterator
        inline const_iterator operator+(difference_type i)
        {
            auto result = *this;
            result += i;
            return result;
        }

        /// subtract from iterator
        inline const_iterator operator-(difference_type i)
        {
            auto result = *this;
            result -= i;
            return result;
        }

        /// return difference
        inline difference_type operator-(const const_iterator& other) const
        {
            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
        inline reference operator[](difference_type n) const
        {
            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");
                    }
                }
            }
        }

3396
        /// return the key of an object iterator
N
Niels 已提交
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412
        inline typename object_t::key_type key() const
        {
            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");
                }
            }
        }

3413
        /// return the value of an iterator
N
Niels 已提交
3414 3415 3416 3417 3418
        inline reference value() const
        {
            return operator*();
        }

N
cleanup  
Niels 已提交
3419 3420 3421 3422
      private:
        /// associated JSON instance
        pointer m_object = nullptr;
        /// the actual iterator of the associated instance
N
Niels 已提交
3423
        internal_iterator<typename array_t::const_iterator, typename object_t::const_iterator> m_it;
N
cleanup  
Niels 已提交
3424
    };
N
Niels 已提交
3425

3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461
    /// a reverse random access iterator for the basic_json class
    class reverse_iterator : private std::reverse_iterator<basic_json::iterator>
    {
      public:
        inline reverse_iterator(const typename std::reverse_iterator<basic_json::iterator>::iterator_type&
                                it)
            : std::reverse_iterator<basic_json::iterator>(it) {}

        /// return the key of an object iterator
        inline typename object_t::key_type key() const
        {
            return this->base().key();
        }

        /// return the value of an iterator
        inline reference value() const
        {
            return this->base().operator * ();
        }
    };

    /// a const reverse random access iterator for the basic_json class
    class const_reverse_iterator : private std::reverse_iterator<basic_json::const_iterator>
    {
      public:
        inline const_reverse_iterator(const typename
                                      std::reverse_iterator<basic_json::const_iterator>::iterator_type& it)
            : std::reverse_iterator<basic_json::const_iterator>(it) {}

        /// return the key of an object iterator
        inline typename object_t::key_type key() const
        {
            return this->base().key();
        }

        /// return the value of an iterator
N
Niels 已提交
3462
        inline const_reference value() const
3463 3464 3465 3466 3467
        {
            return this->base().operator * ();
        }
    };

N
Niels 已提交
3468

N
Niels 已提交
3469
  private:
N
Niels 已提交
3470 3471 3472
    //////////////////////
    // lexer and parser //
    //////////////////////
N
Niels 已提交
3473

N
Niels 已提交
3474 3475 3476 3477 3478 3479 3480
    /*!
    @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 已提交
3481
    class lexer
N
Niels 已提交
3482
    {
N
Niels 已提交
3483
      public:
N
Niels 已提交
3484 3485 3486
        /// token types for the parser
        enum class token_type
        {
N
Niels 已提交
3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500
            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 已提交
3501 3502
        };

N
Niels 已提交
3503
        /// the char type to use in the lexer
N
Niels 已提交
3504
        using lexer_char_t = unsigned char;
N
Niels 已提交
3505

N
Niels 已提交
3506 3507
        /// constructor with a given buffer
        inline lexer(const string_t& s) noexcept
N
Niels 已提交
3508
            : m_stream(nullptr), m_buffer(s)
N
Niels 已提交
3509
        {
3510
            m_content = reinterpret_cast<const lexer_char_t*>(s.c_str());
N
Niels 已提交
3511
            m_start = m_cursor = m_content;
N
Niels 已提交
3512
            m_limit = m_content + s.size();
N
Niels 已提交
3513
        }
3514
        inline lexer(std::istream* s) noexcept
3515 3516
            : m_stream(s)
        {
3517 3518
            getline(*m_stream, m_buffer);
            m_content = reinterpret_cast<const lexer_char_t*>(m_buffer.c_str());
N
Niels 已提交
3519
            m_start = m_cursor = m_content;
3520
            m_limit = m_content + m_buffer.size();
N
Niels 已提交
3521 3522
        }

N
Niels 已提交
3523
        /// default constructor
N
Niels 已提交
3524 3525
        inline lexer() = default;

N
Niels 已提交
3526 3527 3528
        /*!
        @brief create a string from a Unicode code point

N
Niels 已提交
3529 3530
        @param codepoint1  the code point (can be high surrogate)
        @param codepoint2  the code point (can be low surrogate or 0)
N
Niels 已提交
3531
        @return string representation of the code point
N
Niels 已提交
3532 3533
        @exception std::out_of_range if code point is >0x10ffff
        @exception std::invalid_argument if the low surrogate is invalid
N
Niels 已提交
3534 3535 3536

        @see <http://en.wikipedia.org/wiki/UTF-8#Sample_code>
        */
N
Niels 已提交
3537 3538
        inline static string_t to_unicode(const std::size_t codepoint1,
                                          const std::size_t codepoint2 = 0)
N
Niels 已提交
3539
        {
N
Niels 已提交
3540
            string_t result;
N
Niels 已提交
3541

N
Niels 已提交
3542
            // calculate the codepoint from the given code points
N
Niels 已提交
3543
            std::size_t codepoint = codepoint1;
N
Niels 已提交
3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563
            if (codepoint1 >= 0xD800 and codepoint1 <= 0xDBFF)
            {
                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 已提交
3564 3565
            if (codepoint <= 0x7f)
            {
N
Niels 已提交
3566
                // 1-byte characters: 0xxxxxxx (ASCII)
N
Niels 已提交
3567
                result.append(1, static_cast<typename string_t::value_type>(codepoint));
N
Niels 已提交
3568 3569 3570 3571
            }
            else if (codepoint <= 0x7ff)
            {
                // 2-byte characters: 110xxxxx 10xxxxxx
N
Niels 已提交
3572 3573
                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 已提交
3574 3575 3576 3577
            }
            else if (codepoint <= 0xffff)
            {
                // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
N
Niels 已提交
3578 3579 3580
                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 已提交
3581 3582 3583 3584
            }
            else if (codepoint <= 0x10ffff)
            {
                // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
N
Niels 已提交
3585 3586 3587 3588
                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 已提交
3589 3590 3591
            }
            else
            {
N
Niels 已提交
3592
                throw std::out_of_range("code points above 0x10FFFF are invalid");
N
Niels 已提交
3593 3594 3595 3596 3597
            }

            return result;
        }

N
Niels 已提交
3598 3599
        /// return name of values of type token_type
        inline static std::string token_type_name(token_type t) noexcept
N
cleanup  
Niels 已提交
3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628
        {
            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 已提交
3629 3630
                default:
                    return "<parse error>";
N
cleanup  
Niels 已提交
3631 3632 3633
            }
        }

N
fixes  
Niels 已提交
3634 3635 3636 3637
        /*!
        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 已提交
3638 3639 3640
        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 已提交
3641 3642 3643

        @return the class of the next token read from the buffer
        */
N
Niels 已提交
3644
        inline token_type scan() noexcept
N
Niels 已提交
3645
        {
N
cleanup  
Niels 已提交
3646
            // pointer for backtracking information
3647
            m_marker = nullptr;
N
Niels 已提交
3648 3649 3650 3651 3652 3653 3654 3655 3656

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

            /*!re2c
                re2c:define:YYCTYPE  = lexer_char_t;
                re2c:define:YYCURSOR = m_cursor;
                re2c:define:YYLIMIT  = m_limit;
                re2c:define:YYMARKER = m_marker;
3657 3658
                re2c:define:YYFILL   = "{ yyfill(); }";
                re2c:yyfill:parameter = 0;
N
Niels 已提交
3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 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 3708 3709 3710
                re2c:indent:string   = "    ";
                re2c:indent:top      = 1;
                re2c:labelprefix     = "basic_json_parser_";

                // whitespace
                ws = [ \t\n\r]+;
                ws   { return scan(); }

                // structural characters
                "[" { return token_type::begin_array; }
                "]" { return token_type::end_array; }
                "{" { return token_type::begin_object; }
                "}" { return token_type::end_object; }
                "," { return token_type::value_separator; }
                ":" { return token_type::name_separator; }

                // literal names
                "null"  { return token_type::literal_null; }
                "true"  { return token_type::literal_true; }
                "false" { return token_type::literal_false; }

                // number
                decimal_point = [.];
                digit         = [0-9];
                digit_1_9     = [1-9];
                e             = [eE];
                minus         = [-];
                plus          = [+];
                zero          = [0];
                exp           = e (minus|plus)? digit+;
                frac          = decimal_point digit+;
                int           = (zero|digit_1_9 digit*);
                number        = minus? int frac? exp?;
                number        { return token_type::value_number; }

                // string
                quotation_mark  = [\"];
                escape          = [\\];
                unescaped       = [^\"\\\000];
                single_escaped  = [\"\\/bfnrt];
                unicode_escaped = [u][0-9a-fA-F]{4};
                escaped         = escape (single_escaped | unicode_escaped);
                char            = unescaped | escaped;
                string          = quotation_mark char* quotation_mark;
                string          { return token_type::value_string; }

                // end of file
                '\000'         { return token_type::end_of_input; }

                // anything else is an error
                .              { return token_type::parse_error; }
             */
3711

N
Niels 已提交
3712 3713
        }

3714
        /// append data from the stream to the internal buffer
N
Niels 已提交
3715
        inline void yyfill() noexcept
3716
        {
N
Niels 已提交
3717 3718 3719 3720
            if (not m_stream or not * m_stream)
            {
                return;
            }
3721

N
Niels 已提交
3722 3723 3724
            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;
3725

N
Niels 已提交
3726
            m_buffer.erase(0, static_cast<size_t>(offset_start));
3727 3728 3729
            std::string line;
            std::getline(*m_stream, line);
            m_buffer += line;
3730

3731 3732 3733 3734 3735
            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 已提交
3736 3737
        }

N
Niels 已提交
3738 3739
        /// return string representation of last read token
        inline string_t get_token() const noexcept
N
Niels 已提交
3740
        {
N
Niels 已提交
3741 3742
            return string_t(reinterpret_cast<typename string_t::const_pointer>(m_start),
                            static_cast<size_t>(m_cursor - m_start));
N
Niels 已提交
3743 3744 3745
        }

        /*!
N
Niels 已提交
3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761
        @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 已提交
3762 3763

        @return string value of current token without opening and closing quotes
N
Niels 已提交
3764
        @exception std::out_of_range if to_unicode fails
N
Niels 已提交
3765
        */
N
Niels 已提交
3766
        inline string_t get_string() const
N
Niels 已提交
3767
        {
N
Niels 已提交
3768
            string_t result;
N
Niels 已提交
3769 3770 3771
            result.reserve(static_cast<size_t>(m_cursor - m_start - 2));

            // iterate the result between the quotes
N
Niels 已提交
3772
            for (const lexer_char_t* i = m_start + 1; i < m_cursor - 1; ++i)
N
Niels 已提交
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
            {
                // 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 已提交
3810
                            result += "\\";
N
Niels 已提交
3811 3812 3813 3814
                            break;
                        }
                        case '/':
                        {
N
Niels 已提交
3815
                            result += "/";
N
Niels 已提交
3816 3817 3818 3819
                            break;
                        }
                        case '"':
                        {
N
Niels 已提交
3820
                            result += "\"";
N
Niels 已提交
3821 3822 3823 3824 3825 3826
                            break;
                        }

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

                            if (codepoint >= 0xD800 and codepoint <= 0xDBFF)
                            {
N
Niels 已提交
3833
                                // make sure there is a subsequent unicode
N
Niels 已提交
3834
                                if ((i + 6 >= m_limit) or * (i + 5) != '\\' or * (i + 6) != 'u')
N
Niels 已提交
3835 3836 3837 3838
                                {
                                    throw std::invalid_argument("missing low surrogate");
                                }

N
Niels 已提交
3839
                                // get code yyyy from uxxxx\uyyyy
N
Niels 已提交
3840 3841
                                auto codepoint2 = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>
                                                               (i + 7), 4).c_str(), nullptr, 16);
N
Niels 已提交
3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852
                                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 已提交
3853 3854 3855 3856 3857 3858 3859 3860
                            break;
                        }
                    }
                }
                else
                {
                    // all other characters are just copied to the end of the
                    // string
N
Niels 已提交
3861
                    result.append(1, static_cast<typename string_t::value_type>(*i));
N
Niels 已提交
3862 3863 3864 3865
                }
            }

            return result;
N
Niels 已提交
3866 3867
        }

N
Niels 已提交
3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884
        /*!
        @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 已提交
3885 3886 3887
        inline number_float_t get_number() const
        {
            // conversion
N
Niels 已提交
3888 3889
            typename string_t::value_type* endptr;
            const auto float_val = std::strtod(reinterpret_cast<typename string_t::const_pointer>(m_start),
N
Niels 已提交
3890
                                               &endptr);
N
Niels 已提交
3891

N
Niels 已提交
3892 3893
            // return float_val if the whole number was translated and NAN
            // otherwise
N
Niels 已提交
3894
            return (reinterpret_cast<lexer_char_t*>(endptr) == m_cursor) ? float_val : NAN;
N
Niels 已提交
3895 3896 3897
        }

      private:
3898 3899
        /// optional input stream
        std::istream* m_stream;
N
fixes  
Niels 已提交
3900
        /// the buffer
3901 3902
        string_t m_buffer;
        /// the buffer pointer
N
Niels 已提交
3903
        const lexer_char_t* m_content = nullptr;
3904
        /// pointer to the beginning of the current symbol
N
Niels 已提交
3905
        const lexer_char_t* m_start = nullptr;
3906 3907
        /// pointer for backtracking information
        const lexer_char_t* m_marker = nullptr;
N
fixes  
Niels 已提交
3908
        /// pointer to the current symbol
N
Niels 已提交
3909
        const lexer_char_t* m_cursor = nullptr;
N
fixes  
Niels 已提交
3910
        /// pointer to the end of the buffer
N
Niels 已提交
3911
        const lexer_char_t* m_limit = nullptr;
N
Niels 已提交
3912 3913
    };

N
Niels 已提交
3914 3915 3916
    /*!
    @brief syntax analysis
    */
N
Niels 已提交
3917 3918
    class parser
    {
N
Niels 已提交
3919 3920
      public:
        /// constructor for strings
N
Niels 已提交
3921
        inline parser(const string_t& s) : m_lexer(s)
N
Niels 已提交
3922 3923 3924 3925 3926 3927
        {
            // read first token
            get_token();
        }

        /// a parser reading from an input stream
N
Niels 已提交
3928
        inline parser(std::istream& _is) : m_lexer(&_is)
N
Niels 已提交
3929 3930 3931 3932 3933
        {
            // read first token
            get_token();
        }

N
Niels 已提交
3934
        /// public parser interface
N
Niels 已提交
3935
        inline basic_json parse()
N
Niels 已提交
3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946
        {
            basic_json result = parse_internal();

            expect(lexer::token_type::end_of_input);

            return result;
        }

      private:
        /// the actual parser
        inline basic_json parse_internal()
N
Niels 已提交
3947 3948 3949
        {
            switch (last_token)
            {
N
Niels 已提交
3950
                case (lexer::token_type::begin_object):
N
Niels 已提交
3951 3952 3953 3954 3955 3956 3957 3958
                {
                    // explicitly set result to object to cope with {}
                    basic_json result(value_t::object);

                    // read next token
                    get_token();

                    // closing } -> we are done
N
Niels 已提交
3959
                    if (last_token == lexer::token_type::end_object)
N
Niels 已提交
3960
                    {
N
Niels 已提交
3961
                        get_token();
N
Niels 已提交
3962 3963 3964 3965 3966 3967
                        return result;
                    }

                    // otherwise: parse key-value pairs
                    do
                    {
N
Niels 已提交
3968 3969 3970 3971 3972 3973
                        // ugly, but could be fixed with loop reorganization
                        if (last_token == lexer::token_type::value_separator)
                        {
                            get_token();
                        }

N
Niels 已提交
3974
                        // store key
N
Niels 已提交
3975 3976
                        expect(lexer::token_type::value_string);
                        const auto key = m_lexer.get_string();
N
Niels 已提交
3977 3978 3979

                        // parse separator (:)
                        get_token();
N
Niels 已提交
3980
                        expect(lexer::token_type::name_separator);
N
Niels 已提交
3981 3982 3983

                        // parse value
                        get_token();
N
Niels 已提交
3984
                        result[key] = parse_internal();
N
Niels 已提交
3985
                    }
N
Niels 已提交
3986
                    while (last_token == lexer::token_type::value_separator);
N
Niels 已提交
3987 3988

                    // closing }
N
Niels 已提交
3989
                    expect(lexer::token_type::end_object);
N
Niels 已提交
3990
                    get_token();
N
Niels 已提交
3991 3992 3993 3994

                    return result;
                }

N
Niels 已提交
3995
                case (lexer::token_type::begin_array):
N
Niels 已提交
3996 3997 3998 3999 4000 4001 4002 4003
                {
                    // explicitly set result to object to cope with []
                    basic_json result(value_t::array);

                    // read next token
                    get_token();

                    // closing ] -> we are done
N
Niels 已提交
4004
                    if (last_token == lexer::token_type::end_array)
N
Niels 已提交
4005
                    {
N
Niels 已提交
4006
                        get_token();
N
Niels 已提交
4007 4008 4009 4010 4011 4012
                        return result;
                    }

                    // otherwise: parse values
                    do
                    {
N
Niels 已提交
4013 4014 4015 4016 4017
                        // ugly, but could be fixed with loop reorganization
                        if (last_token == lexer::token_type::value_separator)
                        {
                            get_token();
                        }
N
Niels 已提交
4018

N
Niels 已提交
4019 4020
                        // parse value
                        result.push_back(parse_internal());
N
Niels 已提交
4021
                    }
N
Niels 已提交
4022
                    while (last_token == lexer::token_type::value_separator);
N
Niels 已提交
4023 4024

                    // closing ]
N
Niels 已提交
4025
                    expect(lexer::token_type::end_array);
N
Niels 已提交
4026
                    get_token();
N
Niels 已提交
4027 4028 4029 4030

                    return result;
                }

N
Niels 已提交
4031
                case (lexer::token_type::literal_null):
N
Niels 已提交
4032
                {
N
Niels 已提交
4033
                    get_token();
N
Niels 已提交
4034 4035 4036
                    return basic_json(nullptr);
                }

N
Niels 已提交
4037
                case (lexer::token_type::value_string):
N
Niels 已提交
4038
                {
N
Niels 已提交
4039 4040 4041
                    const auto s = m_lexer.get_string();
                    get_token();
                    return basic_json(s);
N
Niels 已提交
4042 4043
                }

N
Niels 已提交
4044
                case (lexer::token_type::literal_true):
N
Niels 已提交
4045
                {
N
Niels 已提交
4046
                    get_token();
N
Niels 已提交
4047 4048 4049
                    return basic_json(true);
                }

N
Niels 已提交
4050
                case (lexer::token_type::literal_false):
N
Niels 已提交
4051
                {
N
Niels 已提交
4052
                    get_token();
N
Niels 已提交
4053 4054 4055
                    return basic_json(false);
                }

N
Niels 已提交
4056
                case (lexer::token_type::value_number):
N
Niels 已提交
4057
                {
N
Niels 已提交
4058
                    auto float_val = m_lexer.get_number();
N
Niels 已提交
4059

N
Niels 已提交
4060 4061
                    // NAN is returned if token could not be translated
                    // completely
N
Niels 已提交
4062
                    if (std::isnan(float_val))
N
Niels 已提交
4063 4064
                    {
                        throw std::invalid_argument(std::string("parse error - ") +
N
Niels 已提交
4065
                                                    m_lexer.get_token() + " is not a number");
N
Niels 已提交
4066 4067
                    }

N
Niels 已提交
4068 4069
                    get_token();

N
Niels 已提交
4070
                    // check if conversion loses precision
N
Niels 已提交
4071
                    const auto int_val = static_cast<number_integer_t>(float_val);
4072
                    if (approx(float_val, static_cast<number_float_t>(int_val)))
N
Niels 已提交
4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086
                    {
                        // we basic_json not lose precision -> return int
                        return basic_json(int_val);
                    }
                    else
                    {
                        // we would lose precision -> returnfloat
                        return basic_json(float_val);
                    }
                }

                default:
                {
                    std::string error_msg = "parse error - unexpected \'";
N
Niels 已提交
4087
                    error_msg += m_lexer.get_token();
N
Niels 已提交
4088
                    error_msg += "\' (";
N
cleanup  
Niels 已提交
4089
                    error_msg += lexer::token_type_name(last_token) + ")";
N
Niels 已提交
4090 4091 4092 4093 4094
                    throw std::invalid_argument(error_msg);
                }
            }
        }

N
Niels 已提交
4095 4096
        /// get next token from lexer
        inline typename lexer::token_type get_token()
N
Niels 已提交
4097
        {
N
Niels 已提交
4098 4099
            last_token = m_lexer.scan();
            return last_token;
N
Niels 已提交
4100 4101
        }

N
Niels 已提交
4102
        inline void expect(typename lexer::token_type t) const
N
Niels 已提交
4103 4104 4105 4106
        {
            if (t != last_token)
            {
                std::string error_msg = "parse error - unexpected \'";
N
Niels 已提交
4107
                error_msg += m_lexer.get_token();
N
cleanup  
Niels 已提交
4108 4109
                error_msg += "\' (" + lexer::token_type_name(last_token);
                error_msg += "); expected " + lexer::token_type_name(t);
N
Niels 已提交
4110 4111 4112 4113
                throw std::invalid_argument(error_msg);
            }
        }

N
Niels 已提交
4114
      private:
N
Niels 已提交
4115
        /// the type of the last read token
N
Niels 已提交
4116
        typename lexer::token_type last_token = lexer::token_type::uninitialized;
N
Niels 已提交
4117
        /// the lexer
N
Niels 已提交
4118
        lexer m_lexer;
N
Niels 已提交
4119
    };
N
cleanup  
Niels 已提交
4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138
};


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

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


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

// specialization of std::swap, and std::hash
namespace std
{
N
Niels 已提交
4139 4140 4141 4142
/*!
@brief exchanges the values of two JSON objects
@ingroup container
*/
N
cleanup  
Niels 已提交
4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156
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 已提交
4157
    /// return a hash value for a JSON object
N
Niels 已提交
4158
    inline std::size_t operator()(const nlohmann::json& j) const
N
cleanup  
Niels 已提交
4159 4160
    {
        // a naive hashing via the string representation
N
Niels 已提交
4161 4162
        const auto& h = hash<nlohmann::json::string_t>();
        return h(j.dump());
N
cleanup  
Niels 已提交
4163 4164 4165 4166
    }
};
}

N
Niels 已提交
4167 4168 4169 4170 4171 4172 4173 4174
/*!
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 已提交
4175
inline nlohmann::json operator "" _json(const char* s, std::size_t)
N
Niels 已提交
4176
{
N
Niels 已提交
4177 4178
    return nlohmann::json::parse(reinterpret_cast<nlohmann::json::string_t::value_type*>
                                 (const_cast<char*>(s)));
N
Niels 已提交
4179 4180
}

N
cleanup  
Niels 已提交
4181
#endif