json.hpp.re2c 81.0 KB
Newer Older
N
cleanup  
Niels 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#ifndef _NLOHMANN_JSON
#define _NLOHMANN_JSON

#include <algorithm>
#include <cassert>
#include <functional>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
N
Niels 已提交
17
#include <cmath>
N
cleanup  
Niels 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

/*!
- ObjectType trick from http://stackoverflow.com/a/9860911
*/
/*
template<typename C, typename=void>
struct container_resizable : std::false_type {};
template<typename C>
struct container_resizable<C, decltype(C().resize(0))> : std::true_type {};
*/

/*!
@see https://github.com/nlohmann
*/
namespace nlohmann
{

/*!
@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 已提交
48
@tparam NumberFloatType    type for JSON floating-point numbers
N
cleanup  
Niels 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
                           (@c double by default)
*/
template <
    template<typename U, typename V, typename... Args> class ObjectType = std::map,
    //template<typename... Args> class ArrayType = std::vector,
    template<typename U, typename... Args> class ArrayType = std::vector,
    class StringType = std::string,
    class BooleanType = bool,
    class NumberIntegerType = int64_t,
    class NumberFloatType = double
    >
class basic_json
{
  public:
    /////////////////////
    // container types //
    /////////////////////

    class iterator;
    class const_iterator;

    /// the type of elements in a basic_json container
    using value_type = basic_json;
    /// the type of an element reference
    using reference = basic_json&;
    /// the type of an element const reference
    using const_reference = const basic_json&;
    /// the type of an element pointer
    using pointer = basic_json*;
    /// the type of an element const pointer
    using const_pointer = const basic_json*;
    /// a type to represent differences between iterators
    using difference_type = std::ptrdiff_t;
    /// a type to represent container sizes
    using size_type = std::size_t;
    /// an iterator for a basic_json container
    using iterator = basic_json::iterator;
    /// a const iterator for a basic_json container
    using const_iterator = basic_json::const_iterator;


    ///////////////////////////
    // 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 已提交
104
    /// a type for a number (floating-point)
N
cleanup  
Niels 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    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 已提交
127
        /// number (floating-point)
N
cleanup  
Niels 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141
        number_float_t number_float;

        /// default constructor (for null values)
        json_value() = default;
        /// constructor for objects
        json_value(object_t* v) : object(v) {}
        /// constructor for arrays
        json_value(array_t* v) : array(v) {}
        /// constructor for strings
        json_value(string_t* v) : string(v) {}
        /// 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 已提交
142
        /// constructor for numbers (floating-point)
N
cleanup  
Niels 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
        json_value(number_float_t v) : number_float(v) {}
    };


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

    /// JSON value type enumeration
    enum class value_t : uint8_t
    {
        /// null value
        null,
        /// object (unordered set of name/value pairs)
        object,
        /// array (ordered collection of values)
        array,
        /// string value
        string,
        /// boolean value
        boolean,
        /// number value (integer)
        number_integer,
N
Niels 已提交
166
        /// number value (floating-point)
N
cleanup  
Niels 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        number_float
    };


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

    /// create an empty value with a given type
    inline basic_json(const value_t value)
        : m_type(value)
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                break;
            }

            case (value_t::object):
            {
                m_value.object = new object_t();
                break;
            }

            case (value_t::array):
            {
                m_value.array = new array_t();
                break;
            }

            case (value_t::string):
            {
N
Niels 已提交
200
                m_value.string = new string_t("");
N
cleanup  
Niels 已提交
201 202 203 204 205
                break;
            }

            case (value_t::boolean):
            {
N
Niels 已提交
206
                m_value.boolean = boolean_t(false);
N
cleanup  
Niels 已提交
207 208 209 210 211
                break;
            }

            case (value_t::number_integer):
            {
N
Niels 已提交
212
                m_value.number_integer = number_integer_t(0);
N
cleanup  
Niels 已提交
213 214 215 216 217
                break;
            }

            case (value_t::number_float):
            {
N
Niels 已提交
218
                m_value.number_float = number_float_t(0.0);
N
cleanup  
Niels 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
                break;
            }
        }
    }

    /// create a null object (implicitly)
    inline basic_json() noexcept
        : m_type(value_t::null)
    {}

    /// 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)
        : m_type(value_t::object), m_value(new object_t(value))
    {}

    /// create an object (implicit)
    template <class V, typename
              std::enable_if<
                  std::is_constructible<string_t, typename V::key_type>::value and
                  std::is_constructible<basic_json, typename V::mapped_type>::value, int>::type
              = 0>
    inline basic_json(const V& value)
        : m_type(value_t::object), m_value(new object_t(value.begin(), value.end()))
    {}

    /// create an array (explicit)
    inline basic_json(const array_t& value)
        : m_type(value_t::array), m_value(new array_t(value))
    {}

    /// 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
                  std::is_constructible<basic_json, typename V::value_type>::value, int>::type
              = 0>
    inline basic_json(const V& value)
        : m_type(value_t::array), m_value(new array_t(value.begin(), value.end()))
    {}

    /// create a string (explicit)
    inline basic_json(const string_t& value)
        : m_type(value_t::string), m_value(new string_t(value))
    {}

    /// create a string (explicit)
    inline basic_json(const typename string_t::value_type* value)
        : m_type(value_t::string), m_value(new string_t(value))
    {}

    /// 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 已提交
304
    /// create a floating-point number (explicit)
N
cleanup  
Niels 已提交
305 306 307 308
    inline basic_json(const number_float_t& value)
        : m_type(value_t::number_float), m_value(value)
    {}

N
Niels 已提交
309
    /// create a floating-point number (implicit)
N
cleanup  
Niels 已提交
310 311 312 313 314 315 316 317 318
    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 已提交
319
    /// create a container (array or object) from an initializer list
N
cleanup  
Niels 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    inline basic_json(list_init_t l, bool type_deduction = true, value_t manual_type = value_t::array)
    {
        // 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
        for (const auto& element : l)
        {
            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 已提交
355
                throw std::logic_error("cannot create JSON object from initializer list");
N
cleanup  
Niels 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
            }
        }

        if (is_object)
        {
            // the initializer list is a list of pairs -> create object
            m_type = value_t::object;
            m_value = new object_t();
            for (auto& element : l)
            {
                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;
            m_value = new array_t(std::move(l));
        }
    }

N
Niels 已提交
377
    /// explicitly create an array from an initializer list
N
cleanup  
Niels 已提交
378 379 380 381 382
    inline static basic_json array(list_init_t l = list_init_t())
    {
        return basic_json(l, false, value_t::array);
    }

N
Niels 已提交
383
    /// explicitly create an object from an initializer list
N
cleanup  
Niels 已提交
384 385
    inline static basic_json object(list_init_t l = list_init_t())
    {
N
Niels 已提交
386
        return basic_json(l, false, value_t::object);
N
cleanup  
Niels 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
    }

    ///////////////////////////////////////
    // other constructors and destructor //
    ///////////////////////////////////////

    /// copy constructor
    inline basic_json(const basic_json& other)
        : m_type(other.m_type)
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                break;
            }
            case (value_t::object):
            {
                m_value.object = new object_t(*other.m_value.object);
                break;
            }
            case (value_t::array):
            {
                m_value.array = new array_t(*other.m_value.array);
                break;
            }
            case (value_t::string):
            {
                m_value.string = new string_t(*other.m_value.string);
                break;
            }
            case (value_t::boolean):
            {
                m_value.boolean = other.m_value.boolean;
                break;
            }
            case (value_t::number_integer):
            {
                m_value.number_integer = other.m_value.number_integer;
                break;
            }
            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 已提交
441
        // invalidate payload
N
cleanup  
Niels 已提交
442 443 444 445 446
        other.m_type = value_t::null;
        other.m_value = {};
    }

    /// copy assignment
N
Niels 已提交
447
    inline reference& operator=(basic_json other) noexcept
N
cleanup  
Niels 已提交
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    {
        std::swap(m_type, other.m_type);
        std::swap(m_value, other.m_value);
        return *this;
    }

    /// destructor
    inline ~basic_json() noexcept
    {
        switch (m_type)
        {
            case (value_t::object):
            {
                delete m_value.object;
                m_value.object = nullptr;
                break;
            }
N
Niels 已提交
465

N
cleanup  
Niels 已提交
466 467 468 469 470 471
            case (value_t::array):
            {
                delete m_value.array;
                m_value.array = nullptr;
                break;
            }
N
Niels 已提交
472

N
cleanup  
Niels 已提交
473 474 475 476 477 478
            case (value_t::string):
            {
                delete m_value.string;
                m_value.string = nullptr;
                break;
            }
N
Niels 已提交
479 480

            default:
N
cleanup  
Niels 已提交
481
            {
N
Niels 已提交
482
                // all other types need no specific destructor
N
cleanup  
Niels 已提交
483 484 485 486 487 488 489 490 491 492 493 494
                break;
            }
        }
    }


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

    /*!
N
Niels 已提交
495 496
    @brief serialization

N
cleanup  
Niels 已提交
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
    Serialization function for JSON objects. The function tries to mimick Python's
    @p json.dumps() function, and currently supports its @p indent parameter.

    @param indent  if 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

    @see https://docs.python.org/2/library/json.html#json.dump
    */
    inline string_t dump(int indent = -1) const noexcept
    {
        if (indent >= 0)
        {
            return dump(true, static_cast<unsigned int>(indent));
        }
        else
        {
            return dump(false, 0);
        }
    }

N
Niels 已提交
519
    /// return the type of the object (explicit)
N
cleanup  
Niels 已提交
520 521 522 523 524
    inline value_t type() const noexcept
    {
        return m_type;
    }

N
Niels 已提交
525
    /// return the type of the object (implicit)
N
cleanup  
Niels 已提交
526 527 528 529 530 531 532 533 534 535
    operator value_t() const noexcept
    {
        return m_type;
    }


    //////////////////////
    // value conversion //
    //////////////////////

N
Niels 已提交
536
    /// get an object (explicit)
N
cleanup  
Niels 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    template <class T, typename
              std::enable_if<
                  std::is_constructible<string_t, typename T::key_type>::value and
                  std::is_constructible<basic_json, typename T::mapped_type>::value, int>::type
              = 0>
    inline T get() const
    {
        switch (m_type)
        {
            case (value_t::object):
                return T(m_value.object->begin(), m_value.object->end());
            default:
                throw std::logic_error("cannot cast " + type_name() + " to " + typeid(T).name());
        }
    }

N
Niels 已提交
553
    /// get an array (explicit)
N
cleanup  
Niels 已提交
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
    template <class T, typename
              std::enable_if<
                  not std::is_same<T, string_t>::value and
                  std::is_constructible<basic_json, typename T::value_type>::value, int>::type
              = 0>
    inline T get() 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());
        }
    }

N
Niels 已提交
570
    /// get a string (explicit)
N
cleanup  
Niels 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
    template <typename T, typename
              std::enable_if<
                  std::is_constructible<T, string_t>::value, int>::type
              = 0>
    inline T get() const
    {
        switch (m_type)
        {
            case (value_t::string):
                return *m_value.string;
            default:
                throw std::logic_error("cannot cast " + type_name() + " to " + typeid(T).name());
        }
    }

N
Niels 已提交
586
    /// get a boolean (explicit)
N
cleanup  
Niels 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
    template <typename T, typename
              std::enable_if<
                  std::is_same<boolean_t, T>::value, int>::type
              = 0>
    inline T get() const
    {
        switch (m_type)
        {
            case (value_t::boolean):
                return m_value.boolean;
            default:
                throw std::logic_error("cannot cast " + type_name() + " to " + typeid(T).name());
        }
    }

N
Niels 已提交
602
    /// get a number (explicit)
N
cleanup  
Niels 已提交
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
    template<typename T, typename
             std::enable_if<
                 not std::is_same<boolean_t, T>::value and
                 std::is_arithmetic<T>::value, int>::type
             = 0>
    inline T get() const
    {
        switch (m_type)
        {
            case (value_t::number_integer):
                return static_cast<T>(m_value.number_integer);
            case (value_t::number_float):
                return static_cast<T>(m_value.number_float);
            default:
                throw std::logic_error("cannot cast " + type_name() + " to " + typeid(T).name());
        }
    }

N
Niels 已提交
621
    /// get a value (implicit)
N
cleanup  
Niels 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    template<typename T>
    inline operator T() const
    {
        return get<T>();
    }


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

    /// access specified element with bounds checking
    inline reference at(size_type pos)
    {
        // at only works for arrays
        if (m_type != value_t::array)
        {
            throw std::runtime_error("cannot use at with " + type_name());
        }

        return m_value.array->at(pos);
    }

    /// access specified element with bounds checking
    inline const_reference at(size_type pos) const
    {
        // at only works for arrays
        if (m_type != value_t::array)
        {
            throw std::runtime_error("cannot use at with " + type_name());
        }

        return m_value.array->at(pos);
    }

    /// access specified element
    inline reference operator[](size_type pos)
    {
        // at only works for arrays
        if (m_type != value_t::array)
        {
            throw std::runtime_error("cannot use [] with " + type_name());
        }

        return m_value.array->operator[](pos);
    }

    /// access specified element
    inline const_reference operator[](size_type pos) const
    {
        // at only works for arrays
        if (m_type != value_t::array)
        {
            throw std::runtime_error("cannot use [] with " + type_name());
        }

        return m_value.array->operator[](pos);
    }

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

    /// access specified element
    inline reference operator[](const typename object_t::key_type& key)
    {
        // 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);
    }

    /// access specified element (needed for clang)
    template<typename T, size_t n>
    inline reference operator[](const T (&key)[n])
    {
        // 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 已提交
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
    /// 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;
    }


N
cleanup  
Niels 已提交
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
    ///////////////
    // iterators //
    ///////////////

    /// returns an iterator to the beginning of the container
    inline iterator begin() noexcept
    {
        iterator result(this);
        result.set_begin();
        return result;
    }

    /// returns a const iterator to the beginning of the container
    inline const_iterator begin() const noexcept
    {
        const_iterator result(this);
        result.set_begin();
        return result;
    }

    /// returns a const iterator to the beginning of the container
    inline const_iterator cbegin() const noexcept
    {
        const_iterator result(this);
        result.set_begin();
        return result;
    }

    /// returns an iterator to the end of the container
    inline iterator end() noexcept
    {
        iterator result(this);
        result.set_end();
        return result;
    }

    /// returns a const iterator to the end of the container
    inline const_iterator end() const noexcept
    {
        const_iterator result(this);
        result.set_end();
        return result;
    }

    /// returns a const iterator to the end of the container
    inline const_iterator cend() const noexcept
    {
        const_iterator result(this);
        result.set_end();
        return result;
    }


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

    /// checks whether the container is empty
    inline bool empty() const noexcept
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                return true;
            }
N
Niels 已提交
824

N
cleanup  
Niels 已提交
825 826 827 828
            case (value_t::array):
            {
                return m_value.array->empty();
            }
N
Niels 已提交
829

N
cleanup  
Niels 已提交
830 831 832 833
            case (value_t::object):
            {
                return m_value.object->empty();
            }
N
Niels 已提交
834

N
Niels 已提交
835 836 837 838 839 840
            default:
            {
                // all other types are nonempty
                return false;
            }
        }
N
cleanup  
Niels 已提交
841 842 843 844 845 846 847 848 849 850 851
    }

    /// returns the number of elements
    inline size_type size() const noexcept
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                return 0;
            }
N
Niels 已提交
852

N
cleanup  
Niels 已提交
853 854 855 856
            case (value_t::array):
            {
                return m_value.array->size();
            }
N
Niels 已提交
857

N
cleanup  
Niels 已提交
858 859 860 861
            case (value_t::object):
            {
                return m_value.object->size();
            }
N
Niels 已提交
862

N
Niels 已提交
863 864 865 866 867 868
            default:
            {
                // all other types have size 1
                return 1;
            }
        }
N
cleanup  
Niels 已提交
869 870 871 872 873 874 875 876 877 878 879
    }

    /// returns the maximum possible number of elements
    inline size_type max_size() const noexcept
    {
        switch (m_type)
        {
            case (value_t::null):
            {
                return 0;
            }
N
Niels 已提交
880

N
cleanup  
Niels 已提交
881 882 883 884
            case (value_t::array):
            {
                return m_value.array->max_size();
            }
N
Niels 已提交
885

N
cleanup  
Niels 已提交
886 887 888 889
            case (value_t::object):
            {
                return m_value.object->max_size();
            }
N
Niels 已提交
890

N
Niels 已提交
891 892 893 894 895 896
            default:
            {
                // all other types have max_size 1
                return 1;
            }
        }
N
cleanup  
Niels 已提交
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
    }


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

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

N
cleanup  
Niels 已提交
914 915
            case (value_t::number_integer):
            {
N
Niels 已提交
916
                m_value.number_integer = 0;
N
cleanup  
Niels 已提交
917 918
                break;
            }
N
Niels 已提交
919

N
cleanup  
Niels 已提交
920 921
            case (value_t::number_float):
            {
N
Niels 已提交
922
                m_value.number_float = 0.0;
N
cleanup  
Niels 已提交
923 924
                break;
            }
N
Niels 已提交
925

N
cleanup  
Niels 已提交
926 927
            case (value_t::boolean):
            {
N
Niels 已提交
928
                m_value.boolean = false;
N
cleanup  
Niels 已提交
929 930
                break;
            }
N
Niels 已提交
931

N
cleanup  
Niels 已提交
932 933 934 935 936
            case (value_t::string):
            {
                m_value.string->clear();
                break;
            }
N
Niels 已提交
937

N
cleanup  
Niels 已提交
938 939 940 941 942
            case (value_t::array):
            {
                m_value.array->clear();
                break;
            }
N
Niels 已提交
943

N
cleanup  
Niels 已提交
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
            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;
            m_value.array = new array_t;
        }

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

N
Niels 已提交
974 975 976 977 978 979 980
    /// add an object to an array
    inline reference operator+=(basic_json&& value)
    {
        push_back(std::move(value));
        return *this;
    }

N
cleanup  
Niels 已提交
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 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 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 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 1260 1261 1262 1263 1264 1265 1266 1267
    /// 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;
            m_value.array = new array_t;
        }

        // 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;
            m_value.object = new object_t;
        }

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

    /// swaps the contents
    inline void swap(reference other) noexcept
    {
        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 //
    //////////////////////////////////////////

    /// comparison: equal
    friend bool operator==(const_reference lhs, const_reference rhs)
    {
        switch (lhs.type())
        {
            case (value_t::array):
            {
                if (rhs.type() == value_t::array)
                {
                    return *lhs.m_value.array == *rhs.m_value.array;
                }
                break;
            }
            case (value_t::object):
            {
                if (rhs.type() == value_t::object)
                {
                    return *lhs.m_value.object == *rhs.m_value.object;
                }
                break;
            }
            case (value_t::null):
            {
                if (rhs.type() == value_t::null)
                {
                    return true;
                }
                break;
            }
            case (value_t::string):
            {
                if (rhs.type() == value_t::string)
                {
                    return *lhs.m_value.string == *rhs.m_value.string;
                }
                break;
            }
            case (value_t::boolean):
            {
                if (rhs.type() == value_t::boolean)
                {
                    return lhs.m_value.boolean == rhs.m_value.boolean;
                }
                break;
            }
            case (value_t::number_integer):
            {
                if (rhs.type() == value_t::number_integer)
                {
                    return lhs.m_value.number_integer == rhs.m_value.number_integer;
                }
                if (rhs.type() == value_t::number_float)
                {
                    return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_float);
                }
                break;
            }
            case (value_t::number_float):
            {
                if (rhs.type() == value_t::number_integer)
                {
                    return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
                }
                if (rhs.type() == value_t::number_float)
                {
                    return lhs.m_value.number_float == rhs.m_value.number_float;
                }
                break;
            }
        }

        return false;
    }

    /// comparison: not equal
    friend bool operator!=(const_reference lhs, const_reference rhs)
    {
        return not (lhs == rhs);
    }

    /// comparison: less than
    friend bool operator<(const_reference lhs, const_reference rhs)
    {
        switch (lhs.type())
        {
            case (value_t::array):
            {
                if (rhs.type() == value_t::array)
                {
                    return *lhs.m_value.array < *rhs.m_value.array;
                }
                break;
            }
            case (value_t::object):
            {
                if (rhs.type() == value_t::object)
                {
                    return *lhs.m_value.object < *rhs.m_value.object;
                }
                break;
            }
            case (value_t::null):
            {
                if (rhs.type() == value_t::null)
                {
                    return false;
                }
                break;
            }
            case (value_t::string):
            {
                if (rhs.type() == value_t::string)
                {
                    return *lhs.m_value.string < *rhs.m_value.string;
                }
                break;
            }
            case (value_t::boolean):
            {
                if (rhs.type() == value_t::boolean)
                {
                    return lhs.m_value.boolean < rhs.m_value.boolean;
                }
                break;
            }
            case (value_t::number_integer):
            {
                if (rhs.type() == value_t::number_integer)
                {
                    return lhs.m_value.number_integer < rhs.m_value.number_integer;
                }
                if (rhs.type() == value_t::number_float)
                {
                    return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_float);
                }
                break;
            }
            case (value_t::number_float):
            {
                if (rhs.type() == value_t::number_integer)
                {
                    return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
                }
                if (rhs.type() == value_t::number_float)
                {
                    return lhs.m_value.number_float < rhs.m_value.number_float;
                }
                break;
            }
        }

        return false;
    }

    /// comparison: less than or equal
    friend bool operator<=(const_reference lhs, const_reference rhs)
    {
        return not (rhs < lhs);
    }

    /// comparison: greater than
    friend bool operator>(const_reference lhs, const_reference rhs)
    {
        return not (lhs <= rhs);
    }

    /// comparison: greater than or equal
    friend bool operator>=(const_reference lhs, const_reference rhs)
    {
        return not (lhs < rhs);
    }


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

    /// serialize to stream
    friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
    {
N
Niels 已提交
1268 1269 1270 1271
        // 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 已提交
1272 1273 1274 1275 1276 1277
        return o;
    }

    /// serialize to stream
    friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
    {
N
Niels 已提交
1278 1279 1280 1281
        // 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 已提交
1282 1283 1284 1285
        return o;
    }


N
Niels 已提交
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
    /////////////////////
    // deserialization //
    /////////////////////

    /// deserialize from string
    static basic_json parse(const std::string& s)
    {
        return parser(s).parse();
    }

    /// 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 已提交
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
  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 已提交
1325

N
cleanup  
Niels 已提交
1326 1327 1328 1329
            case (value_t::object):
            {
                return "object";
            }
N
Niels 已提交
1330

N
cleanup  
Niels 已提交
1331 1332 1333 1334
            case (value_t::array):
            {
                return "array";
            }
N
Niels 已提交
1335

N
cleanup  
Niels 已提交
1336 1337 1338 1339
            case (value_t::string):
            {
                return "string";
            }
N
Niels 已提交
1340

N
cleanup  
Niels 已提交
1341 1342 1343 1344
            case (value_t::boolean):
            {
                return "boolean";
            }
N
Niels 已提交
1345 1346

            default:
N
cleanup  
Niels 已提交
1347 1348 1349 1350 1351 1352
            {
                return "number";
            }
        }
    }

N
Niels 已提交
1353
    /*!
N
Niels 已提交
1354
    @brief escape a string
N
Niels 已提交
1355

N
Niels 已提交
1356 1357 1358 1359 1360 1361 1362
    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 已提交
1363
    */
N
Niels 已提交
1364
    static string_t escape_string(const string_t& s) noexcept
N
Niels 已提交
1365 1366 1367 1368 1369
    {
        // create a result string of at least the size than s
        string_t result;
        result.reserve(s.size());

N
Niels 已提交
1370
        for (const auto c : s)
N
Niels 已提交
1371 1372 1373
        {
            switch (c)
            {
N
Niels 已提交
1374
                // quotation mark (0x22)
N
Niels 已提交
1375 1376
                case '"':
                {
N
Niels 已提交
1377
                    result += "\\\"";
N
Niels 已提交
1378 1379
                    break;
                }
N
Niels 已提交
1380
                // reverse solidus (0x5c)
N
Niels 已提交
1381 1382
                case '\\':
                {
N
Niels 已提交
1383
                    result += "\\\\";
N
Niels 已提交
1384 1385
                    break;
                }
N
Niels 已提交
1386
                // backspace (0x08)
N
Niels 已提交
1387 1388
                case '\b':
                {
N
Niels 已提交
1389
                    result += "\\b";
N
Niels 已提交
1390 1391
                    break;
                }
N
Niels 已提交
1392
                // formfeed (0x0c)
N
Niels 已提交
1393 1394
                case '\f':
                {
N
Niels 已提交
1395
                    result += "\\f";
N
Niels 已提交
1396 1397
                    break;
                }
N
Niels 已提交
1398
                // newline (0x0a)
N
Niels 已提交
1399 1400
                case '\n':
                {
N
Niels 已提交
1401
                    result += "\\n";
N
Niels 已提交
1402 1403
                    break;
                }
N
Niels 已提交
1404
                // carriage return (0x0d)
N
Niels 已提交
1405 1406
                case '\r':
                {
N
Niels 已提交
1407
                    result += "\\r";
N
Niels 已提交
1408 1409
                    break;
                }
N
Niels 已提交
1410
                // horizontal tab (0x09)
N
Niels 已提交
1411 1412
                case '\t':
                {
N
Niels 已提交
1413
                    result += "\\t";
N
Niels 已提交
1414 1415
                    break;
                }
N
Niels 已提交
1416

N
Niels 已提交
1417 1418
                default:
                {
N
Niels 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
                    if (c <= 0x1f)
                    {
                        // control characters (everything between 0x00 and 0x1f)
                        // -> create four-digit hex representation
                        std::stringstream ss;
                        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 已提交
1433 1434 1435 1436 1437 1438 1439
                }
            }
        }

        return result;
    }

N
Niels 已提交
1440

N
cleanup  
Niels 已提交
1441
    /*!
N
Niels 已提交
1442
    @brief internal implementation of the serialization function
N
Niels 已提交
1443

N
Niels 已提交
1444 1445 1446 1447
    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 已提交
1448

N
Niels 已提交
1449 1450
    - strings and object keys are escaped using escape_string()
    - numbers are converted to a string before output using std::to_string()
N
cleanup  
Niels 已提交
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482

    @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,
                         unsigned int currentIndent = 0) const noexcept
    {
        // helper function to return whitespace as indentation
        const auto indent = [prettyPrint, &currentIndent]()
        {
            return prettyPrint ? string_t(currentIndent, ' ') : string_t();
        };

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

                string_t result = "{";

                // increase indentation
                if (prettyPrint)
                {
                    currentIndent += indentStep;
                    result += "\n";
                }

N
Niels 已提交
1483
                for (auto i = m_value.object->cbegin(); i != m_value.object->cend(); ++i)
N
cleanup  
Niels 已提交
1484
                {
N
Niels 已提交
1485
                    if (i != m_value.object->cbegin())
N
cleanup  
Niels 已提交
1486 1487 1488
                    {
                        result += prettyPrint ? ",\n" : ",";
                    }
N
Niels 已提交
1489
                    result += indent() + "\"" + escape_string(i->first) + "\":" + (prettyPrint ? " " : "")
N
cleanup  
Niels 已提交
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
                              + i->second.dump(prettyPrint, indentStep, currentIndent);
                }

                // decrease indentation
                if (prettyPrint)
                {
                    currentIndent -= indentStep;
                    result += "\n";
                }

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

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

                string_t result = "[";

                // increase indentation
                if (prettyPrint)
                {
                    currentIndent += indentStep;
                    result += "\n";
                }

N
Niels 已提交
1519
                for (auto i = m_value.array->cbegin(); i != m_value.array->cend(); ++i)
N
cleanup  
Niels 已提交
1520
                {
N
Niels 已提交
1521
                    if (i != m_value.array->cbegin())
N
cleanup  
Niels 已提交
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
                    {
                        result += prettyPrint ? ",\n" : ",";
                    }
                    result += indent() + i->dump(prettyPrint, indentStep, currentIndent);
                }

                // decrease indentation
                if (prettyPrint)
                {
                    currentIndent -= indentStep;
                    result += "\n";
                }

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

            case (value_t::string):
            {
N
Niels 已提交
1540
                return string_t("\"") + escape_string(*m_value.string) + "\"";
N
cleanup  
Niels 已提交
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
            }

            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):
            {
                return std::to_string(m_value.number_float);
            }
N
Niels 已提交
1557 1558 1559 1560 1561

            default:
            {
                return "null";
            }
N
cleanup  
Niels 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
        }
    }


  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 已提交
1580

N
Niels 已提交
1581
  private:
N
cleanup  
Niels 已提交
1582 1583 1584 1585
    ///////////////
    // iterators //
    ///////////////

N
Niels 已提交
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
    /// values of a generic iterator type of non-container JSON values
    enum class generic_iterator_value
    {
        /// the iterator was not initialized
        uninitialized,
        /// the iterator points to the only value
        begin,
        /// the iterator points past the only value
        end,
        /// the iterator points to an invalid value
        invalid
    };

    /// an iterator value
    union internal_iterator
    {
        /// iterator for JSON objects
        typename object_t::iterator object_iterator;
        /// iterator for JSON arrays
        typename array_t::iterator array_iterator;
        /// generic iteraotr for all other value types
        generic_iterator_value generic_iterator;

        /// default constructor
        internal_iterator() : generic_iterator(generic_iterator_value::uninitialized) {}
        /// constructor for object iterators
        internal_iterator(typename object_t::iterator v) : object_iterator(v) {}
        /// constructor for array iterators
        internal_iterator(typename array_t::iterator v) : array_iterator(v) {}
        /// constructor for generic iterators
        internal_iterator(generic_iterator_value v) : generic_iterator(v) {}
    };

    /// a const iterator value
    union internal_const_iterator
    {
        /// iterator for JSON objects
        typename object_t::const_iterator object_iterator;
        /// iterator for JSON arrays
        typename array_t::const_iterator array_iterator;
        /// generic iteraotr for all other value types
        generic_iterator_value generic_iterator;

        /// default constructor
        internal_const_iterator() : generic_iterator(generic_iterator_value::uninitialized) {}
        /// constructor for object iterators
        internal_const_iterator(typename object_t::iterator v) : object_iterator(v) {}
        /// constructor for array iterators
        internal_const_iterator(typename array_t::iterator v) : array_iterator(v) {}
        /// constructor for generic iterators
        internal_const_iterator(generic_iterator_value v) : generic_iterator(v) {}
    };

  public:
N
cleanup  
Niels 已提交
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
    /// a bidirectional iterator for the basic_json class
    class iterator : public std::iterator<std::bidirectional_iterator_tag, basic_json>
    {
      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;

        /// constructor for a given JSON instance
        inline iterator(pointer object) : m_object(object)
        {
            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:
                {
                    m_it.generic_iterator = generic_iterator_value::uninitialized;
                    break;
                }
            }
        }

        /// copy assignment
        inline iterator& operator=(const iterator& other) noexcept
        {
N
Niels 已提交
1681
            assert(false); // not sure if function will ever be called
N
cleanup  
Niels 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
            m_object = other.m_object;
            m_it = other.m_it;
            return *this;
        }

        /// 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 已提交
1706
                    // set to end so begin()==end() is true: null is empty
N
cleanup  
Niels 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 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 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
                    m_it.generic_iterator = generic_iterator_value::end;
                    break;
                }

                default:
                {
                    m_it.generic_iterator = generic_iterator_value::begin;
                    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:
                {
                    m_it.generic_iterator = generic_iterator_value::end;
                    break;
                }
            }
        }

        /// 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:
                {
                    if (m_it.generic_iterator == generic_iterator_value::begin)
                    {
                        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:
                {
                    if (m_it.generic_iterator == generic_iterator_value::begin)
                    {
                        return m_object;
                    }
                    else
                    {
                        throw std::out_of_range("cannot get value");
                    }
                }
            }
        }

        /// post-increment (it++)
        inline iterator operator++(int)
        {
            iterator result = *this;

            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 已提交
1828 1829 1830 1831 1832 1833 1834 1835
                    if (m_it.generic_iterator == generic_iterator_value::begin)
                    {
                        m_it.generic_iterator = generic_iterator_value::end;
                    }
                    else
                    {
                        m_it.generic_iterator = generic_iterator_value::invalid;
                    }
N
cleanup  
Niels 已提交
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
                    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 已提交
1862 1863 1864 1865 1866 1867 1868 1869
                    if (m_it.generic_iterator == generic_iterator_value::begin)
                    {
                        m_it.generic_iterator = generic_iterator_value::end;
                    }
                    else
                    {
                        m_it.generic_iterator = generic_iterator_value::invalid;
                    }
N
cleanup  
Niels 已提交
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
                    break;
                }
            }

            return *this;
        }

        /// post-decrement (it--)
        inline iterator operator--(int)
        {
            iterator result = *this;

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

N
Niels 已提交
1896 1897 1898 1899 1900 1901
                case (basic_json::value_t::null):
                {
                    m_it.generic_iterator = generic_iterator_value::invalid;
                    break;
                }

N
cleanup  
Niels 已提交
1902 1903
                default:
                {
N
Niels 已提交
1904 1905 1906 1907 1908 1909 1910 1911
                    if (m_it.generic_iterator == generic_iterator_value::end)
                    {
                        m_it.generic_iterator = generic_iterator_value::begin;
                    }
                    else
                    {
                        m_it.generic_iterator = generic_iterator_value::invalid;
                    }
N
cleanup  
Niels 已提交
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
                    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;
                }

N
Niels 已提交
1936 1937 1938 1939 1940 1941
                case (basic_json::value_t::null):
                {
                    m_it.generic_iterator = generic_iterator_value::invalid;
                    break;
                }

N
cleanup  
Niels 已提交
1942 1943
                default:
                {
N
Niels 已提交
1944 1945 1946 1947 1948 1949 1950 1951
                    if (m_it.generic_iterator == generic_iterator_value::end)
                    {
                        m_it.generic_iterator = generic_iterator_value::begin;
                    }
                    else
                    {
                        m_it.generic_iterator = generic_iterator_value::invalid;
                    }
N
cleanup  
Niels 已提交
1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
                    break;
                }
            }

            return *this;
        }

        /// comparison: equal
        inline bool operator==(const iterator& other) const
        {
N
Niels 已提交
1962
            if (m_object != other.m_object or m_object->m_type != other.m_object->m_type)
N
cleanup  
Niels 已提交
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
            {
                return false;
            }

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

      private:
        /// associated JSON instance
        pointer m_object = nullptr;
        /// the actual iterator of the associated instance
        internal_iterator m_it;
    };

    /// a const bidirectional iterator for the basic_json class
    class const_iterator : public std::iterator<std::bidirectional_iterator_tag, const basic_json>
    {
      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;

        /// constructor for a given JSON instance
        inline const_iterator(pointer object) : m_object(object)
        {
            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:
                {
                    m_it.generic_iterator = generic_iterator_value::uninitialized;
                    break;
                }
            }
        }

N
Niels 已提交
2037
        /// copy constructor given a nonconst iterator
N
Niels 已提交
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060
        inline const_iterator(const iterator& other) : m_object(other.m_object)
        {
            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 已提交
2061 2062

        /// copy assignment
N
Niels 已提交
2063
        inline const_iterator& operator=(const const_iterator& other) noexcept
N
cleanup  
Niels 已提交
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
        {
            m_object = other.m_object;
            m_it = other.m_it;
            return *this;
        }

        /// 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 已提交
2089
                    // set to end so begin()==end() is true: null is empty
N
cleanup  
Niels 已提交
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
                    m_it.generic_iterator = generic_iterator_value::end;
                    break;
                }

                default:
                {
                    m_it.generic_iterator = generic_iterator_value::begin;
                    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:
                {
                    m_it.generic_iterator = generic_iterator_value::end;
                    break;
                }
            }
        }

        /// 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:
                {
                    if (m_it.generic_iterator == generic_iterator_value::begin)
                    {
                        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:
                {
                    if (m_it.generic_iterator == generic_iterator_value::begin)
                    {
                        return m_object;
                    }
                    else
                    {
                        throw std::out_of_range("cannot get value");
                    }
                }
            }
        }

        /// post-increment (it++)
        inline const_iterator operator++(int)
        {
            const_iterator result = *this;

            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 已提交
2211 2212 2213 2214 2215 2216 2217 2218
                    if (m_it.generic_iterator == generic_iterator_value::begin)
                    {
                        m_it.generic_iterator = generic_iterator_value::end;
                    }
                    else
                    {
                        m_it.generic_iterator = generic_iterator_value::invalid;
                    }
N
cleanup  
Niels 已提交
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
                    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 已提交
2245 2246 2247 2248 2249 2250 2251 2252
                    if (m_it.generic_iterator == generic_iterator_value::begin)
                    {
                        m_it.generic_iterator = generic_iterator_value::end;
                    }
                    else
                    {
                        m_it.generic_iterator = generic_iterator_value::invalid;
                    }
N
cleanup  
Niels 已提交
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
                    break;
                }
            }

            return *this;
        }

        /// post-decrement (it--)
        inline const_iterator operator--(int)
        {
2263
            const_iterator result = *this;
N
cleanup  
Niels 已提交
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278

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

N
Niels 已提交
2279 2280 2281 2282 2283 2284
                case (basic_json::value_t::null):
                {
                    m_it.generic_iterator = generic_iterator_value::invalid;
                    break;
                }

N
cleanup  
Niels 已提交
2285 2286
                default:
                {
N
Niels 已提交
2287 2288 2289 2290 2291 2292 2293 2294
                    if (m_it.generic_iterator == generic_iterator_value::end)
                    {
                        m_it.generic_iterator = generic_iterator_value::begin;
                    }
                    else
                    {
                        m_it.generic_iterator = generic_iterator_value::invalid;
                    }
N
cleanup  
Niels 已提交
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
                    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;
                }

N
Niels 已提交
2319 2320 2321 2322 2323 2324
                case (basic_json::value_t::null):
                {
                    m_it.generic_iterator = generic_iterator_value::invalid;
                    break;
                }

N
cleanup  
Niels 已提交
2325 2326
                default:
                {
N
Niels 已提交
2327 2328 2329 2330 2331 2332 2333 2334
                    if (m_it.generic_iterator == generic_iterator_value::end)
                    {
                        m_it.generic_iterator = generic_iterator_value::begin;
                    }
                    else
                    {
                        m_it.generic_iterator = generic_iterator_value::invalid;
                    }
N
cleanup  
Niels 已提交
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
                    break;
                }
            }

            return *this;
        }

        /// comparison: equal
        inline bool operator==(const const_iterator& other) const
        {
N
Niels 已提交
2345
            if (m_object != other.m_object or m_object->m_type != other.m_object->m_type)
N
cleanup  
Niels 已提交
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
            {
                return false;
            }

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

      private:
        /// associated JSON instance
        pointer m_object = nullptr;
        /// the actual iterator of the associated instance
        internal_const_iterator m_it;
    };
N
Niels 已提交
2381

N
Niels 已提交
2382

N
Niels 已提交
2383 2384 2385 2386 2387
  private:
    ////////////
    // parser //
    ////////////

N
Niels 已提交
2388
    class lexer
N
Niels 已提交
2389
    {
N
Niels 已提交
2390
      public:
N
Niels 已提交
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405
        /// token types for the parser
        enum class token_type
        {
            uninitialized,
            literal_true,
            literal_false,
            literal_null,
            value_string,
            value_number,
            begin_array,
            begin_object,
            end_array,
            end_object,
            name_separator,
            value_separator,
N
try  
Niels 已提交
2406 2407
            parse_error,
            end_of_input
N
Niels 已提交
2408 2409
        };

N
Niels 已提交
2410 2411 2412 2413 2414 2415 2416 2417
        inline lexer(const char* s) : m_content(s)
        {
            m_start = m_cursor = m_content;
            m_limit = m_content + strlen(m_content);
        }

        inline lexer() = default;

N
cleanup  
Niels 已提交
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452
        inline static std::string token_type_name(token_type t)
        {
            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::parse_error):
                    return "<parse error>";
                case (token_type::end_of_input):
                    return "<end of input>";
            }
        }

N
fixes  
Niels 已提交
2453 2454 2455 2456 2457 2458 2459 2460 2461
        /*!
        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
        deterministic finite automaton (DFA) by the tool RE2C. As a result, the
        translated code for this function consists of a large block of code
        with goto jumps.

        @return the class of the next token read from the buffer
N
Niels 已提交
2462

N
fixes  
Niels 已提交
2463 2464
        @todo Unicode support needs to be checked.
        */
N
Niels 已提交
2465 2466
        inline token_type scan()
        {
N
cleanup  
Niels 已提交
2467 2468 2469 2470
            // pointer for backtracking information
            const char* m_marker = nullptr;

            // remember the begin of the token
N
fixes  
Niels 已提交
2471 2472
            m_start = m_cursor;

N
Niels 已提交
2473
            /*!re2c
N
Niels 已提交
2474
                re2c:define:YYCTYPE     = char;
N
Niels 已提交
2475 2476 2477
                re2c:define:YYCURSOR    = m_cursor;
                re2c:define:YYLIMIT     = m_limit;
                re2c:define:YYMARKER    = m_marker;
N
Niels 已提交
2478
                re2c:indent:string      = "    ";
N
Niels 已提交
2479
                re2c:indent:top         = 1;
N
fixes  
Niels 已提交
2480
                re2c:labelprefix        = "json_parser_";
N
Niels 已提交
2481 2482 2483 2484 2485
                re2c:yyfill:enable      = 0;

                // whitespace
                ws = [ \t\n\r]*;
                ws   { return scan(); }
N
Niels 已提交
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512

                // 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; }
N
Niels 已提交
2513

N
Niels 已提交
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523
                // string
                quotation_mark = [\"];
                escape         = [\\];
                unescaped      = [^\"\\];
                escaped        = escape ([\"\\/bfnrt] | [u][0-9a-fA-F]{4});
                char           = unescaped | escaped;
                string         = quotation_mark char* quotation_mark;
                string         { return token_type::value_string; }

                // end of file
N
fixes  
Niels 已提交
2524
                '\000'         { return token_type::end_of_input; }
N
cleanup  
Niels 已提交
2525 2526 2527

                // anything else is an error
                *              { return token_type::parse_error; }
N
Niels 已提交
2528 2529 2530 2531 2532 2533 2534 2535 2536
             */
        }

        inline std::string get_string_value() const
        {
            return std::string(m_start, static_cast<size_t>(m_cursor - m_start));
        }

        /*!
N
fixes  
Niels 已提交
2537 2538 2539 2540 2541
        The pointer m_start points to the opening quote of the string, and
        m_cursor past the closing quote of the string. We create a std::string
        from the character after the opening quotes (m_begin+1) until the
        character before the closing quotes (hence subtracting 2 characters
        from the pointer difference of the two pointers).
N
Niels 已提交
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553

        @return string value of current token without opening and closing quotes

        @todo Take care of Unicode.
        */
        inline std::string get_string() const
        {
            return std::string(m_start + 1, static_cast<size_t>(m_cursor - m_start - 2));
        }

        inline number_float_t get_number() const
        {
N
fixes  
Niels 已提交
2554 2555 2556 2557 2558 2559 2560
            // 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.
N
Niels 已提交
2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578

            // conversion
            char* endptr;
            const auto float_val = std::strtod(reinterpret_cast<const char*>(m_start), &endptr);

            // check if strtod read beyond the end of the lexem
            if (endptr != m_cursor)
            {
                std::cerr << get_string_value() << std::endl;
                return NAN;
            }
            else
            {
                return float_val;
            }
        }

      private:
N
fixes  
Niels 已提交
2579
        /// the buffer
N
Niels 已提交
2580
        const char* m_content = nullptr;
N
fixes  
Niels 已提交
2581
        /// pointer to he beginning of the current symbol
N
Niels 已提交
2582
        const char* m_start = nullptr;
N
fixes  
Niels 已提交
2583
        /// pointer to the current symbol
N
Niels 已提交
2584
        const char* m_cursor = nullptr;
N
fixes  
Niels 已提交
2585
        /// pointer to the end of the buffer
N
Niels 已提交
2586 2587 2588 2589 2590
        const char* m_limit = nullptr;
    };

    class parser
    {
N
Niels 已提交
2591 2592
      public:
        /// constructor for strings
N
Niels 已提交
2593
        inline parser(const std::string& s) : m_buffer(s), m_lexer(m_buffer.c_str())
N
Niels 已提交
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605
        {
            // read first token
            get_token();
        }

        /// a parser reading from an input stream
        inline parser(std::istream& _is)
        {
            while (_is)
            {
                std::string input_line;
                std::getline(_is, input_line);
N
Niels 已提交
2606
                m_buffer += input_line;
N
Niels 已提交
2607 2608
            }

N
Niels 已提交
2609 2610 2611
            // initializer lexer
            m_lexer = lexer(m_buffer.c_str());

N
Niels 已提交
2612 2613 2614 2615 2616 2617 2618 2619
            // read first token
            get_token();
        }

        inline basic_json parse()
        {
            switch (last_token)
            {
N
Niels 已提交
2620
                case (lexer::token_type::begin_object):
N
Niels 已提交
2621 2622 2623 2624 2625 2626 2627 2628
                {
                    // 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 已提交
2629
                    if (last_token == lexer::token_type::end_object)
N
Niels 已提交
2630 2631 2632 2633 2634 2635 2636 2637
                    {
                        return result;
                    }

                    // otherwise: parse key-value pairs
                    do
                    {
                        // store key
N
Niels 已提交
2638 2639
                        expect(lexer::token_type::value_string);
                        const auto key = m_lexer.get_string();
N
Niels 已提交
2640 2641 2642

                        // parse separator (:)
                        get_token();
N
Niels 已提交
2643
                        expect(lexer::token_type::name_separator);
N
Niels 已提交
2644 2645 2646 2647 2648 2649 2650 2651

                        // parse value
                        get_token();
                        result[key] = parse();

                        // read next character
                        get_token();
                    }
N
Niels 已提交
2652
                    while (last_token == lexer::token_type::value_separator
N
Niels 已提交
2653 2654 2655
                            and get_token() == last_token);

                    // closing }
N
Niels 已提交
2656
                    expect(lexer::token_type::end_object);
N
Niels 已提交
2657 2658 2659 2660

                    return result;
                }

N
Niels 已提交
2661
                case (lexer::token_type::begin_array):
N
Niels 已提交
2662 2663 2664 2665 2666 2667 2668 2669
                {
                    // 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 已提交
2670
                    if (last_token == lexer::token_type::end_array)
N
Niels 已提交
2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
                    {
                        return result;
                    }

                    // otherwise: parse values
                    do
                    {
                        // parse value
                        result.push_back(parse());

                        // read next character
                        get_token();
                    }
N
Niels 已提交
2684
                    while (last_token == lexer::token_type::value_separator
N
Niels 已提交
2685 2686 2687
                            and get_token() == last_token);

                    // closing ]
N
Niels 已提交
2688
                    expect(lexer::token_type::end_array);
N
Niels 已提交
2689 2690 2691 2692

                    return result;
                }

N
Niels 已提交
2693
                case (lexer::token_type::literal_null):
N
Niels 已提交
2694 2695 2696 2697
                {
                    return basic_json(nullptr);
                }

N
Niels 已提交
2698
                case (lexer::token_type::value_string):
N
Niels 已提交
2699
                {
N
Niels 已提交
2700
                    return basic_json(m_lexer.get_string());
N
Niels 已提交
2701 2702
                }

N
Niels 已提交
2703
                case (lexer::token_type::literal_true):
N
Niels 已提交
2704 2705 2706 2707
                {
                    return basic_json(true);
                }

N
Niels 已提交
2708
                case (lexer::token_type::literal_false):
N
Niels 已提交
2709 2710 2711 2712
                {
                    return basic_json(false);
                }

N
Niels 已提交
2713
                case (lexer::token_type::value_number):
N
Niels 已提交
2714
                {
N
Niels 已提交
2715
                    auto float_val = m_lexer.get_number();
N
Niels 已提交
2716

N
Niels 已提交
2717
                    if (std::isnan(float_val))
N
Niels 已提交
2718 2719
                    {
                        throw std::invalid_argument(std::string("parse error - ") +
N
Niels 已提交
2720
                                                    m_lexer.get_string_value() + " is not a number");
N
Niels 已提交
2721 2722 2723
                    }

                    // check if conversion loses precision
N
Niels 已提交
2724
                    const auto int_val = static_cast<number_integer_t>(float_val);
N
Niels 已提交
2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
                    if (float_val == int_val)
                    {
                        // 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 已提交
2740
                    error_msg += m_lexer.get_string_value();
N
Niels 已提交
2741
                    error_msg += "\' (";
N
cleanup  
Niels 已提交
2742
                    error_msg += lexer::token_type_name(last_token) + ")";
N
Niels 已提交
2743 2744 2745 2746 2747 2748
                    throw std::invalid_argument(error_msg);
                }
            }
        }

      private:
N
Niels 已提交
2749 2750
        /// get next token from lexer
        inline typename lexer::token_type get_token()
N
Niels 已提交
2751
        {
N
Niels 已提交
2752 2753
            last_token = m_lexer.scan();
            return last_token;
N
Niels 已提交
2754 2755
        }

N
Niels 已提交
2756
        inline void expect(typename lexer::token_type t) const
N
Niels 已提交
2757 2758 2759 2760
        {
            if (t != last_token)
            {
                std::string error_msg = "parse error - unexpected \'";
N
Niels 已提交
2761
                error_msg += m_lexer.get_string_value();
N
cleanup  
Niels 已提交
2762 2763
                error_msg += "\' (" + lexer::token_type_name(last_token);
                error_msg += "); expected " + lexer::token_type_name(t);
N
Niels 已提交
2764 2765 2766 2767
                throw std::invalid_argument(error_msg);
            }
        }

N
Niels 已提交
2768
      private:
N
Niels 已提交
2769
        /// the buffer
N
Niels 已提交
2770
        std::string m_buffer;
N
Niels 已提交
2771
        /// the type of the last read token
N
Niels 已提交
2772 2773
        typename lexer::token_type last_token = lexer::token_type::uninitialized;
        lexer m_lexer;
N
Niels 已提交
2774
    };
N
cleanup  
Niels 已提交
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
};


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

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

}


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

// specialization of std::swap, and std::hash
namespace std
{
/// swaps the values of two JSON objects
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 已提交
2810
    /// return a hash value for a JSON object
N
Niels 已提交
2811
    inline size_t operator()(const nlohmann::json& j) const
N
cleanup  
Niels 已提交
2812 2813 2814 2815 2816 2817 2818
    {
        // a naive hashing via the string representation
        return hash<std::string>()(j.dump());
    }
};
}

N
Niels 已提交
2819 2820 2821 2822 2823 2824 2825 2826
/*!
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 已提交
2827
inline nlohmann::json operator "" _json(const char* s, std::size_t)
N
Niels 已提交
2828 2829 2830 2831
{
    return nlohmann::json::parse(s);
}

N
cleanup  
Niels 已提交
2832
#endif