json.cc 53.4 KB
Newer Older
N
tidy up  
Niels 已提交
1 2 3 4 5 6 7 8 9 10 11
/*!
@file
@copyright The code is licensed under the MIT License
           <http://opensource.org/licenses/MIT>,
           Copyright (c) 2013-2014 Niels Lohmann.

@author Niels Lohmann <http://nlohmann.me>

@see https://github.com/nlohmann/json
*/

N
Niels 已提交
12
#include "json.h"
N
Niels 已提交
13

N
Niels 已提交
14
#include <cctype>     // std::isdigit, std::isspace
N
Niels 已提交
15
#include <cstddef>    // std::size_t
N
Niels 已提交
16 17
#include <stdexcept>  // std::runtime_error
#include <utility>    // std::swap, std::move
N
Niels 已提交
18

N
Niels 已提交
19 20
namespace nlohmann
{
N
Niels 已提交
21 22 23 24 25

///////////////////////////////////
// CONSTRUCTORS OF UNION "value" //
///////////////////////////////////

N
Niels 已提交
26
json::value::value(array_t* _array): array(_array) {}
N
Niels 已提交
27
json::value::value(object_t* object_): object(object_) {}
N
Niels 已提交
28 29 30 31
json::value::value(string_t* _string): string(_string) {}
json::value::value(boolean_t _boolean) : boolean(_boolean) {}
json::value::value(number_t _number) : number(_number) {}
json::value::value(number_float_t _number_float) : number_float(_number_float) {}
N
Niels 已提交
32

N
Niels 已提交
33 34 35 36

/////////////////////////////////
// CONSTRUCTORS AND DESTRUCTOR //
/////////////////////////////////
N
Niels 已提交
37

N
Niels 已提交
38 39
/*!
Construct an empty JSON given the type.
N
Niels 已提交
40

N
Niels 已提交
41
@param t  the type from the @ref json::type enumeration.
N
Niels 已提交
42 43 44

@post Memory for array, object, and string are allocated.
*/
45
json::json(const value_type t)
N
Niels 已提交
46
    : type_(t)
N
Niels 已提交
47
{
N
Niels 已提交
48
    switch (type_)
N
Niels 已提交
49 50 51
    {
        case (value_type::array):
        {
N
Niels 已提交
52
            value_.array = new array_t();
N
Niels 已提交
53 54
            break;
        }
N
Niels 已提交
55 56
        case (value_type::object):
        {
N
Niels 已提交
57
            value_.object = new object_t();
N
Niels 已提交
58 59
            break;
        }
N
Niels 已提交
60 61
        case (value_type::string):
        {
N
Niels 已提交
62
            value_.string = new string_t();
N
Niels 已提交
63 64
            break;
        }
N
Niels 已提交
65 66
        case (value_type::boolean):
        {
N
Niels 已提交
67
            value_.boolean = boolean_t();
N
Niels 已提交
68 69
            break;
        }
N
Niels 已提交
70 71
        case (value_type::number):
        {
N
Niels 已提交
72
            value_.number = number_t();
N
Niels 已提交
73 74
            break;
        }
N
Niels 已提交
75 76
        case (value_type::number_float):
        {
N
Niels 已提交
77
            value_.number_float = number_float_t();
N
Niels 已提交
78 79
            break;
        }
N
Niels 已提交
80
        default:
N
Niels 已提交
81
        {
N
Niels 已提交
82 83 84 85 86
            break;
        }
    }
}

N
Niels 已提交
87 88 89
/*!
Construct a null JSON object.
*/
N
Niels 已提交
90
json::json(std::nullptr_t) noexcept : json()
N
Niels 已提交
91 92 93 94 95 96 97
{}

/*!
Construct a string JSON object.

@param s  a string to initialize the JSON object with
*/
98
json::json(const std::string& s)
N
Niels 已提交
99
    : type_(value_type::string), value_(new string_t(s))
N
Niels 已提交
100 101
{}

102
json::json(std::string&& s)
N
Niels 已提交
103
    : type_(value_type::string), value_(new string_t(std::move(s)))
N
Niels 已提交
104 105
{}

106
json::json(const char* s)
N
Niels 已提交
107
    : type_(value_type::string), value_(new string_t(s))
N
Niels 已提交
108 109
{}

N
Niels 已提交
110
json::json(const bool b) noexcept
N
Niels 已提交
111
    : type_(value_type::boolean), value_(b)
N
Niels 已提交
112 113
{}

N
Niels 已提交
114
json::json(const int i) noexcept
N
Niels 已提交
115
    : type_(value_type::number), value_(i)
N
Niels 已提交
116 117
{}

N
Niels 已提交
118
json::json(const double f) noexcept
N
Niels 已提交
119
    : type_(value_type::number_float), value_(f)
N
Niels 已提交
120 121
{}

122
json::json(const array_t& a)
N
Niels 已提交
123
    : type_(value_type::array), value_(new array_t(a))
N
Niels 已提交
124 125
{}

126
json::json(array_t&& a)
N
Niels 已提交
127
    : type_(value_type::array), value_(new array_t(std::move(a)))
N
Niels 已提交
128 129
{}

130
json::json(const object_t& o)
N
Niels 已提交
131
    : type_(value_type::object), value_(new object_t(o))
N
Niels 已提交
132 133
{}

134
json::json(object_t&& o)
N
Niels 已提交
135
    : type_(value_type::object), value_(new object_t(std::move(o)))
N
Niels 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
{}

/*!
This function is a bit tricky as it uses an initializer list of JSON objects
for both arrays and objects. This is not supported by C++, so we use the
following trick. Both initializer lists for objects and arrays will transform
to a list of JSON objects. The only difference is that in case of an object,
the list will contain JSON array objects with two elements - one for the key
and one for the value. As a result, it is sufficient to check if each element
of the initializer list is an array (1) with two elements (2) whose first
element is of type string (3). If this is the case, we treat the whole
initializer list as list of pairs to construct an object. If not, we pass it
as is to create an array.

@bug With the described approach, we would fail to recognize an array whose
     first element is again an arrays as array.
*/
153
json::json(list_init_t a)
N
Niels 已提交
154 155 156 157 158
{
    // check if each element is an array with two elements whose first element
    // is a string
    for (const auto& element : a)
    {
N
Niels 已提交
159
        if (element.type_ != value_type::array or
N
Niels 已提交
160
                element.size() != 2 or
N
Niels 已提交
161
                element[0].type_ != value_type::string)
N
Niels 已提交
162 163 164
        {

            // the initializer list describes an array
N
Niels 已提交
165 166
            type_ = value_type::array;
            value_ = new array_t(a);
N
Niels 已提交
167 168 169 170 171
            return;
        }
    }

    // the initializer list is a list of pairs
N
Niels 已提交
172 173
    type_ = value_type::object;
    value_ = new object_t();
N
Niels 已提交
174
    for (const json& element : a)
N
Niels 已提交
175 176
    {
        const std::string k = element[0];
N
Niels 已提交
177
        value_.object->emplace(std::make_pair(std::move(k),
N
Niels 已提交
178
                                              std::move(element[1])));
N
Niels 已提交
179 180 181 182 183
    }
}

/*!
A copy constructor for the JSON class.
N
Niels 已提交
184

N
Niels 已提交
185 186
@param o  the JSON object to copy
*/
187
json::json(const json& o)
N
Niels 已提交
188
    : type_(o.type_)
N
Niels 已提交
189
{
N
Niels 已提交
190
    switch (type_)
N
Niels 已提交
191 192 193
    {
        case (value_type::array):
        {
N
Niels 已提交
194
            value_.array = new array_t(*o.value_.array);
N
Niels 已提交
195
            break;
N
Niels 已提交
196
        }
N
Niels 已提交
197 198
        case (value_type::object):
        {
N
Niels 已提交
199
            value_.object = new object_t(*o.value_.object);
N
Niels 已提交
200
            break;
N
Niels 已提交
201
        }
N
Niels 已提交
202 203
        case (value_type::string):
        {
N
Niels 已提交
204
            value_.string = new string_t(*o.value_.string);
N
Niels 已提交
205
            break;
N
Niels 已提交
206
        }
N
Niels 已提交
207 208
        case (value_type::boolean):
        {
N
Niels 已提交
209
            value_.boolean = o.value_.boolean;
N
Niels 已提交
210
            break;
N
Niels 已提交
211
        }
N
Niels 已提交
212 213
        case (value_type::number):
        {
N
Niels 已提交
214
            value_.number = o.value_.number;
N
Niels 已提交
215
            break;
N
Niels 已提交
216
        }
N
Niels 已提交
217 218
        case (value_type::number_float):
        {
N
Niels 已提交
219
            value_.number_float = o.value_.number_float;
N
Niels 已提交
220
            break;
N
Niels 已提交
221
        }
N
Niels 已提交
222
        default:
N
Niels 已提交
223
        {
N
Niels 已提交
224
            break;
N
Niels 已提交
225
        }
N
Niels 已提交
226 227 228
    }
}

N
Niels 已提交
229 230
/*!
A move constructor for the JSON class.
N
Niels 已提交
231

N
Niels 已提交
232 233 234 235
@param o  the JSON object to move

@post The JSON object \p o is invalidated.
*/
N
Niels 已提交
236
json::json(json&& o) noexcept
N
Niels 已提交
237
    : type_(std::move(o.type_)), value_(std::move(o.value_))
N
Niels 已提交
238 239
{
    // invalidate payload
N
Niels 已提交
240 241
    o.type_ = value_type::null;
    o.value_ = {};
N
Niels 已提交
242 243 244 245 246 247 248 249
}

/*!
A copy assignment operator for the JSON class, following the copy-and-swap
idiom.

@param o  A JSON object to assign to this object.
*/
N
Niels 已提交
250
json& json::operator=(json o) noexcept
N
Niels 已提交
251
{
N
Niels 已提交
252 253
    std::swap(type_, o.type_);
    std::swap(value_, o.value_);
N
Niels 已提交
254 255
    return *this;
}
N
Niels 已提交
256

N
Niels 已提交
257
json::~json() noexcept
N
Niels 已提交
258
{
N
Niels 已提交
259
    switch (type_)
N
Niels 已提交
260 261 262
    {
        case (value_type::array):
        {
N
Niels 已提交
263
            delete value_.array;
N
Niels 已提交
264 265
            break;
        }
N
Niels 已提交
266 267
        case (value_type::object):
        {
N
Niels 已提交
268
            delete value_.object;
N
Niels 已提交
269 270
            break;
        }
N
Niels 已提交
271 272
        case (value_type::string):
        {
N
Niels 已提交
273
            delete value_.string;
N
Niels 已提交
274 275
            break;
        }
N
Niels 已提交
276
        default:
N
Niels 已提交
277 278
        {
            // nothing to do for non-pointer types
N
Niels 已提交
279
            break;
N
Niels 已提交
280
        }
N
Niels 已提交
281 282 283
    }
}

N
Niels 已提交
284 285 286 287
/*!
@param s  a string representation of a JSON object
@return a JSON object
*/
N
Niels 已提交
288
json json::parse(const std::string& s)
N
Niels 已提交
289
{
N
Niels 已提交
290
    return parser(s).parse();
N
Niels 已提交
291 292 293 294 295 296
}

/*!
@param s  a string representation of a JSON object
@return a JSON object
*/
N
Niels 已提交
297
json json::parse(const char* s)
N
Niels 已提交
298
{
N
Niels 已提交
299
    return parser(s).parse();
N
Niels 已提交
300 301 302
}


N
Niels 已提交
303
std::string json::type_name() const noexcept
N
Niels 已提交
304
{
N
Niels 已提交
305
    switch (type_)
N
Niels 已提交
306 307 308 309
    {
        case (value_type::array):
        {
            return "array";
N
Niels 已提交
310
        }
N
Niels 已提交
311 312 313
        case (value_type::object):
        {
            return "object";
N
Niels 已提交
314
        }
N
Niels 已提交
315 316 317
        case (value_type::null):
        {
            return "null";
N
Niels 已提交
318
        }
N
Niels 已提交
319 320 321
        case (value_type::string):
        {
            return "string";
N
Niels 已提交
322
        }
N
Niels 已提交
323 324 325
        case (value_type::boolean):
        {
            return "boolean";
N
Niels 已提交
326
        }
N
Niels 已提交
327
        default:
N
Niels 已提交
328 329
        {
            return "number";
N
Niels 已提交
330
        }
N
Niels 已提交
331 332 333 334
    }
}


N
Niels 已提交
335 336 337
///////////////////////////////
// OPERATORS AND CONVERSIONS //
///////////////////////////////
N
Niels 已提交
338

N
Niels 已提交
339 340 341 342 343
/*!
@exception std::logic_error if the function is called for JSON objects whose
    type is not string
*/
template<>
N
Niels 已提交
344
std::string json::get() const
N
Niels 已提交
345
{
N
Niels 已提交
346
    switch (type_)
N
Niels 已提交
347 348
    {
        case (value_type::string):
N
Niels 已提交
349
            return *value_.string;
N
Niels 已提交
350
        default:
N
Niels 已提交
351
            throw std::logic_error("cannot cast " + type_name() + " to JSON string");
N
Niels 已提交
352 353 354
    }
}

N
Niels 已提交
355 356 357 358 359
/*!
@exception std::logic_error if the function is called for JSON objects whose
    type is not number (int or float)
*/
template<>
N
Niels 已提交
360
int json::get() const
N
Niels 已提交
361
{
N
Niels 已提交
362
    switch (type_)
N
Niels 已提交
363 364
    {
        case (value_type::number):
N
Niels 已提交
365
            return value_.number;
N
Niels 已提交
366
        case (value_type::number_float):
N
Niels 已提交
367
            return static_cast<number_t>(value_.number_float);
N
Niels 已提交
368
        default:
N
Niels 已提交
369
            throw std::logic_error("cannot cast " + type_name() + " to JSON number");
N
Niels 已提交
370 371 372
    }
}

N
Niels 已提交
373 374 375 376 377
/*!
@exception std::logic_error if the function is called for JSON objects whose
    type is not number (int or float)
*/
template<>
N
Niels 已提交
378
double json::get() const
N
Niels 已提交
379
{
N
Niels 已提交
380
    switch (type_)
N
Niels 已提交
381 382
    {
        case (value_type::number):
N
Niels 已提交
383
            return static_cast<number_float_t>(value_.number);
N
Niels 已提交
384
        case (value_type::number_float):
N
Niels 已提交
385
            return value_.number_float;
N
Niels 已提交
386
        default:
N
Niels 已提交
387
            throw std::logic_error("cannot cast " + type_name() + " to JSON number");
N
Niels 已提交
388 389 390
    }
}

N
Niels 已提交
391 392 393 394 395
/*!
@exception std::logic_error if the function is called for JSON objects whose
    type is not boolean
*/
template<>
N
Niels 已提交
396
bool json::get() const
N
Niels 已提交
397
{
N
Niels 已提交
398
    switch (type_)
N
Niels 已提交
399 400
    {
        case (value_type::boolean):
N
Niels 已提交
401
            return value_.boolean;
N
Niels 已提交
402
        default:
N
Niels 已提交
403
            throw std::logic_error("cannot cast " + type_name() + " to JSON Boolean");
N
Niels 已提交
404 405 406
    }
}

N
Niels 已提交
407 408 409 410 411
/*!
@exception std::logic_error if the function is called for JSON objects whose
    type is an object
*/
template<>
N
Niels 已提交
412
json::array_t json::get() const
N
Niels 已提交
413
{
N
Niels 已提交
414
    if (type_ == value_type::array)
N
Niels 已提交
415
    {
N
Niels 已提交
416
        return *value_.array;
N
Niels 已提交
417
    }
N
Niels 已提交
418
    if (type_ == value_type::object)
N
Niels 已提交
419
    {
N
Niels 已提交
420
        throw std::logic_error("cannot cast " + type_name() + " to JSON array");
N
Niels 已提交
421 422
    }

N
Niels 已提交
423
    array_t result;
N
Niels 已提交
424 425 426 427
    result.push_back(*this);
    return result;
}

N
Niels 已提交
428 429 430 431 432
/*!
@exception std::logic_error if the function is called for JSON objects whose
    type is not object
*/
template<>
N
Niels 已提交
433
json::object_t json::get() const
N
Niels 已提交
434
{
N
Niels 已提交
435
    if (type_ == value_type::object)
N
Niels 已提交
436
    {
N
Niels 已提交
437
        return *value_.object;
N
Niels 已提交
438 439 440
    }
    else
    {
N
Niels 已提交
441
        throw std::logic_error("cannot cast " + type_name() + " to JSON object");
N
Niels 已提交
442 443 444
    }
}

N
Niels 已提交
445
json::operator const std::string() const
N
Niels 已提交
446 447 448 449
{
    return get<std::string>();
}

N
Niels 已提交
450
json::operator int() const
N
Niels 已提交
451 452 453 454
{
    return get<int>();
}

N
Niels 已提交
455
json::operator double() const
N
Niels 已提交
456 457 458 459
{
    return get<double>();
}

N
Niels 已提交
460
json::operator bool() const
N
Niels 已提交
461 462 463 464
{
    return get<bool>();
}

N
Niels 已提交
465
json::operator array_t() const
N
Niels 已提交
466 467 468 469
{
    return get<array_t>();
}

N
Niels 已提交
470
json::operator object_t() const
N
Niels 已提交
471 472 473 474
{
    return get<object_t>();
}

N
Niels 已提交
475 476 477 478 479 480 481
/*!
Internal implementation of the serialization function.

\param prettyPrint    whether the output shall be pretty-printed
\param indentStep     the indent level
\param currentIndent  the current indent level (only used internally)
*/
N
Niels 已提交
482 483
std::string json::dump(const bool prettyPrint, const unsigned int indentStep,
                       unsigned int currentIndent) const noexcept
N
Niels 已提交
484
{
N
Niels 已提交
485 486 487 488 489 490
    // helper function to return whitespace as indentation
    const auto indent = [prettyPrint, &currentIndent]()
    {
        return prettyPrint ? std::string(currentIndent, ' ') : std::string();
    };

N
Niels 已提交
491
    switch (type_)
N
Niels 已提交
492 493 494
    {
        case (value_type::string):
        {
N
Niels 已提交
495
            return std::string("\"") + *value_.string + "\"";
N
Niels 已提交
496 497
        }

N
Niels 已提交
498 499
        case (value_type::boolean):
        {
N
Niels 已提交
500
            return value_.boolean ? "true" : "false";
N
Niels 已提交
501 502
        }

N
Niels 已提交
503 504
        case (value_type::number):
        {
N
Niels 已提交
505
            return std::to_string(value_.number);
N
Niels 已提交
506 507
        }

N
Niels 已提交
508 509
        case (value_type::number_float):
        {
N
Niels 已提交
510
            return std::to_string(value_.number_float);
N
Niels 已提交
511 512
        }

N
Niels 已提交
513 514
        case (value_type::array):
        {
N
Niels 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527
            if (value_.array->empty())
            {
                return "[]";
            }

            std::string result = "[";

            // increase indentation
            if (prettyPrint)
            {
                currentIndent += indentStep;
                result += "\n";
            }
N
Niels 已提交
528

N
Niels 已提交
529
            for (array_t::const_iterator i = value_.array->begin(); i != value_.array->end(); ++i)
N
Niels 已提交
530
            {
N
Niels 已提交
531
                if (i != value_.array->begin())
N
Niels 已提交
532
                {
N
Niels 已提交
533
                    result += prettyPrint ? ",\n" : ", ";
N
Niels 已提交
534
                }
N
Niels 已提交
535 536 537 538 539 540 541 542
                result += indent() + i->dump(prettyPrint, indentStep, currentIndent);
            }

            // decrease indentation
            if (prettyPrint)
            {
                currentIndent -= indentStep;
                result += "\n";
N
Niels 已提交
543 544
            }

N
Niels 已提交
545
            return result + indent() + "]";
N
Niels 已提交
546 547
        }

N
Niels 已提交
548 549
        case (value_type::object):
        {
N
Niels 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562
            if (value_.object->empty())
            {
                return "{}";
            }

            std::string result = "{";

            // increase indentation
            if (prettyPrint)
            {
                currentIndent += indentStep;
                result += "\n";
            }
N
Niels 已提交
563

N
Niels 已提交
564
            for (object_t::const_iterator i = value_.object->begin(); i != value_.object->end(); ++i)
N
Niels 已提交
565
            {
N
Niels 已提交
566
                if (i != value_.object->begin())
N
Niels 已提交
567
                {
N
Niels 已提交
568
                    result += prettyPrint ? ",\n" : ", ";
N
Niels 已提交
569
                }
N
Niels 已提交
570 571 572 573 574 575 576 577 578
                result += indent() + "\"" + i->first + "\": " + i->second.dump(prettyPrint, indentStep,
                          currentIndent);
            }

            // decrease indentation
            if (prettyPrint)
            {
                currentIndent -= indentStep;
                result += "\n";
N
Niels 已提交
579 580
            }

N
Niels 已提交
581
            return result + indent() + "}";
N
Niels 已提交
582
        }
N
Niels 已提交
583 584 585 586 587 588

        // actually only value_type::null - but making the compiler happy
        default:
        {
            return "null";
        }
N
Niels 已提交
589 590 591
    }
}

N
Niels 已提交
592 593 594 595 596 597 598 599 600 601 602
/*!
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
*/
N
Niels 已提交
603
std::string json::dump(int indent) const noexcept
N
Niels 已提交
604 605 606 607 608 609 610 611 612 613 614
{
    if (indent >= 0)
    {
        return dump(true, static_cast<unsigned int>(indent));
    }
    else
    {
        return dump(false, 0);
    }
}

N
Niels 已提交
615

N
Niels 已提交
616 617 618
///////////////////////////////////////////
// ADDING ELEMENTS TO OBJECTS AND ARRAYS //
///////////////////////////////////////////
N
Niels 已提交
619

N
Niels 已提交
620
json& json::operator+=(const json& o)
N
Niels 已提交
621
{
N
Niels 已提交
622 623 624 625
    push_back(o);
    return *this;
}

N
Niels 已提交
626
json& json::operator+=(const std::string& s)
N
Niels 已提交
627
{
N
Niels 已提交
628
    push_back(json(s));
N
Niels 已提交
629 630 631
    return *this;
}

N
Niels 已提交
632
json& json::operator+=(const char* s)
N
Niels 已提交
633
{
N
Niels 已提交
634
    push_back(json(s));
N
Niels 已提交
635 636 637
    return *this;
}

N
Niels 已提交
638
json& json::operator+=(std::nullptr_t)
N
Niels 已提交
639
{
N
Niels 已提交
640
    push_back(json());
N
Niels 已提交
641 642 643
    return *this;
}

N
Niels 已提交
644
json& json::operator+=(bool b)
N
Niels 已提交
645
{
N
Niels 已提交
646
    push_back(json(b));
N
Niels 已提交
647 648 649
    return *this;
}

N
Niels 已提交
650 651 652 653 654 655
/*!
Adds a number (int) to the current object. This is done by wrapping the number
into a JSON and call push_back for this.

@param i  A number (int) to add to the array.
*/
N
Niels 已提交
656
json& json::operator+=(int i)
N
Niels 已提交
657
{
N
Niels 已提交
658
    push_back(json(i));
N
Niels 已提交
659 660 661
    return *this;
}

N
Niels 已提交
662 663 664 665 666 667
/*!
Adds a number (float) to the current object. This is done by wrapping the
number into a JSON and call push_back for this.

@param f  A number (float) to add to the array.
*/
N
Niels 已提交
668
json& json::operator+=(double f)
N
Niels 已提交
669
{
N
Niels 已提交
670
    push_back(json(f));
N
Niels 已提交
671 672 673
    return *this;
}

N
Niels 已提交
674
/*!
N
Niels 已提交
675
@todo comment me
N
Niels 已提交
676
*/
N
Niels 已提交
677
json& json::operator+=(const object_t::value_type& p)
N
Niels 已提交
678 679 680 681 682
{
    return operator[](p.first) = p.second;
}

/*!
N
Niels 已提交
683
@todo comment me
N
Niels 已提交
684
*/
N
Niels 已提交
685
json& json::operator+=(list_init_t a)
N
Niels 已提交
686 687 688 689
{
    push_back(a);
    return *this;
}
N
Niels 已提交
690

N
Niels 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704
/*!
This function implements the actual "adding to array" function and is called
by all other push_back or operator+= functions. If the function is called for
an array, the passed element is added to the array.

@param o  The element to add to the array.

@pre  The JSON object is an array or null.
@post The JSON object is an array whose last element is the passed element o.
@exception std::runtime_error  The function was called for a JSON type that
             does not support addition to an array (e.g., int or string).

@note Null objects are silently transformed into an array before the addition.
*/
N
Niels 已提交
705
void json::push_back(const json& o)
N
Niels 已提交
706 707
{
    // push_back only works for null objects or arrays
N
Niels 已提交
708
    if (not(type_ == value_type::null or type_ == value_type::array))
N
Niels 已提交
709
    {
N
Niels 已提交
710
        throw std::runtime_error("cannot add element to " + type_name());
N
Niels 已提交
711 712
    }

N
Niels 已提交
713
    // transform null object into an array
N
Niels 已提交
714
    if (type_ == value_type::null)
N
Niels 已提交
715
    {
N
Niels 已提交
716 717
        type_ = value_type::array;
        value_.array = new array_t;
N
Niels 已提交
718 719
    }

N
Niels 已提交
720
    // add element to array
N
Niels 已提交
721
    value_.array->push_back(o);
N
Niels 已提交
722 723
}

N
Niels 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
/*!
This function implements the actual "adding to array" function and is called
by all other push_back or operator+= functions. If the function is called for
an array, the passed element is added to the array using move semantics.

@param o  The element to add to the array.

@pre  The JSON object is an array or null.
@post The JSON object is an array whose last element is the passed element o.
@post The element o is destroyed.
@exception std::runtime_error  The function was called for a JSON type that
             does not support addition to an array (e.g., int or string).

@note Null objects are silently transformed into an array before the addition.
@note This function applies move semantics for the given element.
*/
N
Niels 已提交
740
void json::push_back(json&& o)
N
Niels 已提交
741 742
{
    // push_back only works for null objects or arrays
N
Niels 已提交
743
    if (not(type_ == value_type::null or type_ == value_type::array))
N
Niels 已提交
744
    {
N
Niels 已提交
745
        throw std::runtime_error("cannot add element to " + type_name());
N
Niels 已提交
746 747 748
    }

    // transform null object into an array
N
Niels 已提交
749
    if (type_ == value_type::null)
N
Niels 已提交
750
    {
N
Niels 已提交
751 752
        type_ = value_type::array;
        value_.array = new array_t;
N
Niels 已提交
753 754 755
    }

    // add element to array (move semantics)
N
Niels 已提交
756
    value_.array->emplace_back(std::move(o));
N
Niels 已提交
757
    // invalidate object
N
Niels 已提交
758
    o.type_ = value_type::null;
N
Niels 已提交
759 760
}

N
Niels 已提交
761
void json::push_back(const std::string& s)
N
Niels 已提交
762
{
N
Niels 已提交
763
    push_back(json(s));
N
Niels 已提交
764 765
}

N
Niels 已提交
766
void json::push_back(const char* s)
N
Niels 已提交
767
{
N
Niels 已提交
768
    push_back(json(s));
N
Niels 已提交
769 770
}

N
Niels 已提交
771
void json::push_back(std::nullptr_t)
N
Niels 已提交
772
{
N
Niels 已提交
773
    push_back(json());
N
Niels 已提交
774 775
}

N
Niels 已提交
776
void json::push_back(bool b)
N
Niels 已提交
777
{
N
Niels 已提交
778
    push_back(json(b));
N
Niels 已提交
779 780
}

N
Niels 已提交
781 782 783 784 785 786
/*!
Adds a number (int) to the current object. This is done by wrapping the number
into a JSON and call push_back for this.

@param i  A number (int) to add to the array.
*/
N
Niels 已提交
787
void json::push_back(int i)
N
Niels 已提交
788
{
N
Niels 已提交
789
    push_back(json(i));
N
Niels 已提交
790 791
}

N
Niels 已提交
792 793 794 795 796 797
/*!
Adds a number (float) to the current object. This is done by wrapping the
number into a JSON and call push_back for this.

@param f  A number (float) to add to the array.
*/
N
Niels 已提交
798
void json::push_back(double f)
N
Niels 已提交
799
{
N
Niels 已提交
800
    push_back(json(f));
N
Niels 已提交
801 802
}

N
Niels 已提交
803
/*!
N
Niels 已提交
804
@todo comment me
N
Niels 已提交
805
*/
N
Niels 已提交
806
void json::push_back(const object_t::value_type& p)
N
Niels 已提交
807 808 809 810 811
{
    operator[](p.first) = p.second;
}

/*!
N
Niels 已提交
812
@todo comment me
N
Niels 已提交
813
*/
N
Niels 已提交
814
void json::push_back(list_init_t a)
N
Niels 已提交
815 816 817 818 819 820 821
{
    bool is_array = false;

    // check if each element is an array with two elements whose first element
    // is a string
    for (const auto& element : a)
    {
N
Niels 已提交
822
        if (element.type_ != value_type::array or
N
Niels 已提交
823
                element.size() != 2 or
N
Niels 已提交
824
                element[0].type_ != value_type::string)
N
Niels 已提交
825 826 827 828 829 830 831 832 833
        {
            // the initializer list describes an array
            is_array = true;
            break;
        }
    }

    if (is_array)
    {
N
Niels 已提交
834
        for (const json& element : a)
N
Niels 已提交
835 836 837 838 839 840
        {
            push_back(element);
        }
    }
    else
    {
N
Niels 已提交
841
        for (const json& element : a)
N
Niels 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
        {
            const object_t::value_type tmp {element[0].get<std::string>(), element[1]};
            push_back(tmp);
        }
    }
}

/*!
This operator realizes read/write access to array elements given an integer
index.  Bounds will not be checked.

@note The "index" variable should be of type size_t as it is compared against
      size() and used in the at() function. However, the compiler will have
      problems in case integer literals are used. In this case, an implicit
      conversion to both size_t and JSON is possible. Therefore, we use int as
      type and convert it to size_t where necessary.

@param index  the index of the element to return from the array
@return reference to element for the given index

@pre Object is an array.
@exception std::domain_error if object is not an array
*/
N
Niels 已提交
865
json& json::operator[](const int index)
N
Niels 已提交
866 867
{
    // this [] operator only works for arrays
N
Niels 已提交
868
    if (type_ != value_type::array)
N
Niels 已提交
869 870
    {
        throw std::domain_error("cannot add entry with index " +
N
Niels 已提交
871
                                std::to_string(index) + " to " + type_name());
N
Niels 已提交
872 873
    }

N
Niels 已提交
874
    // return reference to element from array at given index
N
Niels 已提交
875
    return (*value_.array)[static_cast<std::size_t>(index)];
N
Niels 已提交
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
}

/*!
This operator realizes read-only access to array elements given an integer
index.  Bounds will not be checked.

@note The "index" variable should be of type size_t as it is compared against
      size() and used in the at() function. However, the compiler will have
      problems in case integer literals are used. In this case, an implicit
      conversion to both size_t and JSON is possible. Therefore, we use int as
      type and convert it to size_t where necessary.

@param index  the index of the element to return from the array
@return read-only reference to element for the given index

@pre Object is an array.
@exception std::domain_error if object is not an array
*/
N
Niels 已提交
894
const json& json::operator[](const int index) const
N
Niels 已提交
895 896
{
    // this [] operator only works for arrays
N
Niels 已提交
897
    if (type_ != value_type::array)
N
Niels 已提交
898 899
    {
        throw std::domain_error("cannot get entry with index " +
N
Niels 已提交
900
                                std::to_string(index) + " from " + type_name());
N
Niels 已提交
901 902
    }

N
Niels 已提交
903
    // return element from array at given index
N
Niels 已提交
904
    return (*value_.array)[static_cast<std::size_t>(index)];
N
Niels 已提交
905 906
}

N
Niels 已提交
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
/*!
This function realizes read/write access to array elements given an integer
index. Bounds will be checked.

@note The "index" variable should be of type size_t as it is compared against
      size() and used in the at() function. However, the compiler will have
      problems in case integer literals are used. In this case, an implicit
      conversion to both size_t and JSON is possible. Therefore, we use int as
      type and convert it to size_t where necessary.

@param index  the index of the element to return from the array
@return reference to element for the given index

@pre Object is an array.
@exception std::domain_error if object is not an array
@exception std::out_of_range if index is out of range (via std::vector::at)
*/
N
Niels 已提交
924
json& json::at(const int index)
N
Niels 已提交
925 926
{
    // this function only works for arrays
N
Niels 已提交
927
    if (type_ != value_type::array)
N
Niels 已提交
928 929
    {
        throw std::domain_error("cannot add entry with index " +
N
Niels 已提交
930
                                std::to_string(index) + " to " + type_name());
N
Niels 已提交
931 932
    }

N
Niels 已提交
933
    // return reference to element from array at given index
N
Niels 已提交
934
    return value_.array->at(static_cast<std::size_t>(index));
N
Niels 已提交
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
}

/*!
This operator realizes read-only access to array elements given an integer
index. Bounds will be checked.

@note The "index" variable should be of type size_t as it is compared against
      size() and used in the at() function. However, the compiler will have
      problems in case integer literals are used. In this case, an implicit
      conversion to both size_t and JSON is possible. Therefore, we use int as
      type and convert it to size_t where necessary.

@param index  the index of the element to return from the array
@return read-only reference to element for the given index

@pre Object is an array.
@exception std::domain_error if object is not an array
@exception std::out_of_range if index is out of range (via std::vector::at)
*/
N
Niels 已提交
954
const json& json::at(const int index) const
N
Niels 已提交
955 956
{
    // this function only works for arrays
N
Niels 已提交
957
    if (type_ != value_type::array)
N
Niels 已提交
958 959
    {
        throw std::domain_error("cannot get entry with index " +
N
Niels 已提交
960
                                std::to_string(index) + " from " + type_name());
N
Niels 已提交
961 962
    }

N
Niels 已提交
963
    // return element from array at given index
N
Niels 已提交
964
    return value_.array->at(static_cast<std::size_t>(index));
N
Niels 已提交
965 966
}

N
Niels 已提交
967
/*!
N
Niels 已提交
968
@copydoc json::operator[](const char* key)
N
Niels 已提交
969
*/
N
Niels 已提交
970
json& json::operator[](const std::string& key)
N
Niels 已提交
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
{
    return operator[](key.c_str());
}

/*!
This operator realizes read/write access to object elements given a string
key.

@param key  the key index of the element to return from the object
@return reference to a JSON object for the given key (null if key does not
        exist)

@pre  Object is an object or a null object.
@post null objects are silently converted to objects.

@exception std::domain_error if object is not an object (or null)
*/
N
Niels 已提交
988
json& json::operator[](const char* key)
N
Niels 已提交
989 990
{
    // implicitly convert null to object
N
Niels 已提交
991
    if (type_ == value_type::null)
N
Niels 已提交
992
    {
N
Niels 已提交
993 994
        type_ = value_type::object;
        value_.object = new object_t;
N
Niels 已提交
995 996
    }

N
Niels 已提交
997
    // this [] operator only works for objects
N
Niels 已提交
998
    if (type_ != value_type::object)
N
Niels 已提交
999 1000
    {
        throw std::domain_error("cannot add entry with key " +
N
Niels 已提交
1001
                                std::string(key) + " to " + type_name());
N
Niels 已提交
1002 1003
    }

N
Niels 已提交
1004
    // if the key does not exist, create it
N
Niels 已提交
1005
    if (value_.object->find(key) == value_.object->end())
N
Niels 已提交
1006
    {
N
Niels 已提交
1007
        (*value_.object)[key] = json();
N
Niels 已提交
1008 1009
    }

N
Niels 已提交
1010
    // return reference to element from array at given index
N
Niels 已提交
1011
    return (*value_.object)[key];
N
Niels 已提交
1012 1013
}

N
Niels 已提交
1014 1015 1016
/*!
This operator realizes read-only access to object elements given a string
key.
N
Niels 已提交
1017

N
Niels 已提交
1018 1019
@param key  the key index of the element to return from the object
@return read-only reference to element for the given key
N
Niels 已提交
1020

N
Niels 已提交
1021 1022 1023 1024
@pre Object is an object.
@exception std::domain_error if object is not an object
@exception std::out_of_range if key is not found in object
*/
N
Niels 已提交
1025
const json& json::operator[](const std::string& key) const
N
Niels 已提交
1026 1027
{
    // this [] operator only works for objects
N
Niels 已提交
1028
    if (type_ != value_type::object)
N
Niels 已提交
1029
    {
N
Niels 已提交
1030
        throw std::domain_error("cannot get entry with key " +
N
Niels 已提交
1031
                                std::string(key) + " from " + type_name());
N
Niels 已提交
1032 1033
    }

N
Niels 已提交
1034
    // search for the key
N
Niels 已提交
1035
    const auto it = value_.object->find(key);
N
Niels 已提交
1036 1037

    // make sure the key exists in the object
N
Niels 已提交
1038
    if (it == value_.object->end())
N
Niels 已提交
1039 1040
    {
        throw std::out_of_range("key " + key + " not found");
N
Niels 已提交
1041 1042
    }

N
Niels 已提交
1043 1044 1045 1046 1047
    // return element from array at given key
    return it->second;
}

/*!
N
Niels 已提交
1048
@copydoc json::at(const char* key)
N
Niels 已提交
1049
*/
N
Niels 已提交
1050
json& json::at(const std::string& key)
N
Niels 已提交
1051 1052
{
    return at(key.c_str());
N
Niels 已提交
1053 1054
}

N
Niels 已提交
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
/*!
This function realizes read/write access to object elements given a string
key.

@param key  the key index of the element to return from the object
@return reference to a JSON object for the given key (exception if key does not
        exist)

@pre  Object is an object.

@exception std::domain_error if object is not an object
@exception std::out_of_range if key was not found (via std::map::at)
*/
N
Niels 已提交
1068
json& json::at(const char* key)
N
Niels 已提交
1069 1070
{
    // this function operator only works for objects
N
Niels 已提交
1071
    if (type_ != value_type::object)
N
Niels 已提交
1072 1073
    {
        throw std::domain_error("cannot add entry with key " +
N
Niels 已提交
1074
                                std::string(key) + " to " + type_name());
N
Niels 已提交
1075 1076
    }

N
Niels 已提交
1077
    // return reference to element from array at given index
N
Niels 已提交
1078
    return value_.object->at(key);
N
Niels 已提交
1079 1080
}

N
Niels 已提交
1081
/*!
N
Niels 已提交
1082
@copydoc json::at(const char *key) const
N
Niels 已提交
1083
*/
N
Niels 已提交
1084
const json& json::at(const std::string& key) const
N
Niels 已提交
1085 1086 1087 1088
{
    return at(key.c_str());
}

N
Niels 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
/*!
This operator realizes read-only access to object elements given a string
key.

@param key  the key index of the element to return from the object
@return read-only reference to element for the given key

@pre Object is an object.
@exception std::domain_error if object is not an object
@exception std::out_of_range if key is not found (via std::map::at)
*/
N
Niels 已提交
1100
const json& json::at(const char* key) const
N
Niels 已提交
1101 1102
{
    // this [] operator only works for objects
N
Niels 已提交
1103
    if (type_ != value_type::object)
N
Niels 已提交
1104 1105
    {
        throw std::domain_error("cannot get entry with key " +
N
Niels 已提交
1106
                                std::string(key) + " from " + type_name());
N
Niels 已提交
1107
    }
N
Niels 已提交
1108 1109

    // return element from array at given key
N
Niels 已提交
1110
    return value_.object->at(key);
N
Niels 已提交
1111 1112
}

N
Niels 已提交
1113

N
Niels 已提交
1114 1115 1116 1117 1118 1119 1120 1121 1122
/*!
Returns the size of the JSON object.

@return the size of the JSON object; the size is the number of elements in
        compounds (array and object), 1 for value types (true, false, number,
        string), and 0 for null.

@invariant The size is reported as 0 if and only if empty() would return true.
*/
N
Niels 已提交
1123
std::size_t json::size() const noexcept
N
Niels 已提交
1124
{
N
Niels 已提交
1125
    switch (type_)
N
Niels 已提交
1126 1127 1128
    {
        case (value_type::array):
        {
N
Niels 已提交
1129
            return value_.array->size();
N
Niels 已提交
1130
        }
N
Niels 已提交
1131 1132
        case (value_type::object):
        {
N
Niels 已提交
1133
            return value_.object->size();
N
Niels 已提交
1134
        }
N
Niels 已提交
1135 1136
        case (value_type::null):
        {
N
Niels 已提交
1137
            return 0;
N
Niels 已提交
1138
        }
N
Niels 已提交
1139
        default:
N
Niels 已提交
1140
        {
N
Niels 已提交
1141
            return 1;
N
Niels 已提交
1142
        }
N
Niels 已提交
1143 1144 1145
    }
}

N
Niels 已提交
1146 1147 1148 1149 1150 1151 1152 1153 1154
/*!
Returns whether a JSON object is empty.

@return true for null objects and empty compounds (array and object); false
        for value types (true, false, number, string) and filled compounds
        (array and object).

@invariant Empty would report true if and only if size() would return 0.
*/
N
Niels 已提交
1155
bool json::empty() const noexcept
N
Niels 已提交
1156
{
N
Niels 已提交
1157
    switch (type_)
N
Niels 已提交
1158 1159 1160
    {
        case (value_type::array):
        {
N
Niels 已提交
1161
            return value_.array->empty();
N
Niels 已提交
1162
        }
N
Niels 已提交
1163 1164
        case (value_type::object):
        {
N
Niels 已提交
1165
            return value_.object->empty();
N
Niels 已提交
1166
        }
N
Niels 已提交
1167 1168
        case (value_type::null):
        {
N
Niels 已提交
1169
            return true;
N
Niels 已提交
1170
        }
N
Niels 已提交
1171
        default:
N
Niels 已提交
1172
        {
N
Niels 已提交
1173
            return false;
N
Niels 已提交
1174
        }
N
Niels 已提交
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    }
}

/*!
Removes all elements from compounds and resets values to default.

@invariant Clear will set any value type to its default value which is empty
           for compounds, false for booleans, 0 for integer numbers, and 0.0
           for floating numbers.
*/
N
Niels 已提交
1185
void json::clear() noexcept
N
Niels 已提交
1186
{
N
Niels 已提交
1187
    switch (type_)
N
Niels 已提交
1188 1189 1190
    {
        case (value_type::array):
        {
N
Niels 已提交
1191
            value_.array->clear();
N
Niels 已提交
1192
            break;
N
Niels 已提交
1193
        }
N
Niels 已提交
1194 1195
        case (value_type::object):
        {
N
Niels 已提交
1196
            value_.object->clear();
N
Niels 已提交
1197
            break;
N
Niels 已提交
1198
        }
N
Niels 已提交
1199 1200
        case (value_type::string):
        {
N
Niels 已提交
1201
            value_.string->clear();
N
Niels 已提交
1202 1203 1204 1205
            break;
        }
        case (value_type::boolean):
        {
N
Niels 已提交
1206
            value_.boolean = {};
N
Niels 已提交
1207 1208 1209 1210
            break;
        }
        case (value_type::number):
        {
N
Niels 已提交
1211
            value_.number = {};
N
Niels 已提交
1212 1213 1214 1215
            break;
        }
        case (value_type::number_float):
        {
N
Niels 已提交
1216
            value_.number_float = {};
N
Niels 已提交
1217 1218
            break;
        }
N
Niels 已提交
1219
        default:
N
Niels 已提交
1220 1221
        {
            break;
N
Niels 已提交
1222
        }
N
Niels 已提交
1223 1224 1225
    }
}

N
Niels 已提交
1226
json::value_type json::type() const noexcept
N
Niels 已提交
1227
{
N
Niels 已提交
1228
    return type_;
N
Niels 已提交
1229 1230
}

N
Niels 已提交
1231
json::iterator json::find(const std::string& key)
N
Niels 已提交
1232
{
N
Niels 已提交
1233 1234 1235
    return find(key.c_str());
}

N
Niels 已提交
1236
json::const_iterator json::find(const std::string& key) const
N
Niels 已提交
1237
{
N
Niels 已提交
1238 1239 1240
    return find(key.c_str());
}

N
Niels 已提交
1241
json::iterator json::find(const char* key)
N
Niels 已提交
1242
{
N
Niels 已提交
1243
    if (type_ != value_type::object)
N
Niels 已提交
1244
    {
N
Niels 已提交
1245
        return end();
N
Niels 已提交
1246 1247 1248
    }
    else
    {
N
Niels 已提交
1249 1250
        const object_t::iterator i = value_.object->find(key);
        if (i != value_.object->end())
N
Niels 已提交
1251
        {
N
Niels 已提交
1252
            json::iterator result(this);
N
Niels 已提交
1253
            delete result.oi_;
1254
            result.oi_ = nullptr;
N
Niels 已提交
1255
            result.oi_ = new object_t::iterator(i);
N
Niels 已提交
1256
            return result;
N
Niels 已提交
1257 1258 1259
        }
        else
        {
N
Niels 已提交
1260 1261 1262 1263 1264
            return end();
        }
    }
}

N
Niels 已提交
1265
json::const_iterator json::find(const char* key) const
N
Niels 已提交
1266
{
N
Niels 已提交
1267
    if (type_ != value_type::object)
N
Niels 已提交
1268
    {
N
Niels 已提交
1269
        return end();
N
Niels 已提交
1270 1271 1272
    }
    else
    {
N
Niels 已提交
1273 1274
        const object_t::const_iterator i = value_.object->find(key);
        if (i != value_.object->end())
N
Niels 已提交
1275
        {
N
Niels 已提交
1276
            json::const_iterator result(this);
N
Niels 已提交
1277
            delete result.oi_;
1278
            result.oi_ = nullptr;
N
Niels 已提交
1279
            result.oi_ = new object_t::const_iterator(i);
N
Niels 已提交
1280
            return result;
N
Niels 已提交
1281 1282 1283
        }
        else
        {
N
Niels 已提交
1284 1285 1286 1287 1288
            return end();
        }
    }
}

N
Niels 已提交
1289
bool json::operator==(const json& o) const noexcept
N
Niels 已提交
1290
{
N
Niels 已提交
1291
    switch (type_)
N
Niels 已提交
1292 1293 1294
    {
        case (value_type::array):
        {
N
Niels 已提交
1295
            if (o.type_ == value_type::array)
N
Niels 已提交
1296
            {
N
Niels 已提交
1297
                return *value_.array == *o.value_.array;
N
Niels 已提交
1298
            }
N
Niels 已提交
1299
            break;
N
Niels 已提交
1300
        }
N
Niels 已提交
1301 1302
        case (value_type::object):
        {
N
Niels 已提交
1303
            if (o.type_ == value_type::object)
N
Niels 已提交
1304
            {
N
Niels 已提交
1305
                return *value_.object == *o.value_.object;
N
Niels 已提交
1306
            }
N
Niels 已提交
1307
            break;
N
Niels 已提交
1308
        }
N
Niels 已提交
1309 1310
        case (value_type::null):
        {
N
Niels 已提交
1311
            if (o.type_ == value_type::null)
N
Niels 已提交
1312
            {
N
Niels 已提交
1313 1314
                return true;
            }
N
Niels 已提交
1315
            break;
N
Niels 已提交
1316
        }
N
Niels 已提交
1317 1318
        case (value_type::string):
        {
N
Niels 已提交
1319
            if (o.type_ == value_type::string)
N
Niels 已提交
1320
            {
N
Niels 已提交
1321
                return *value_.string == *o.value_.string;
N
Niels 已提交
1322
            }
N
Niels 已提交
1323
            break;
N
Niels 已提交
1324
        }
N
Niels 已提交
1325 1326
        case (value_type::boolean):
        {
N
Niels 已提交
1327
            if (o.type_ == value_type::boolean)
N
Niels 已提交
1328
            {
N
Niels 已提交
1329
                return value_.boolean == o.value_.boolean;
N
Niels 已提交
1330
            }
N
Niels 已提交
1331
            break;
N
Niels 已提交
1332
        }
N
Niels 已提交
1333 1334
        case (value_type::number):
        {
N
Niels 已提交
1335
            if (o.type_ == value_type::number)
N
Niels 已提交
1336
            {
N
Niels 已提交
1337
                return value_.number == o.value_.number;
1338
            }
N
Niels 已提交
1339
            if (o.type_ == value_type::number_float)
N
Niels 已提交
1340
            {
N
Niels 已提交
1341
                return value_.number == static_cast<number_t>(o.value_.number_float);
N
Niels 已提交
1342
            }
N
Niels 已提交
1343
            break;
N
Niels 已提交
1344
        }
N
Niels 已提交
1345 1346
        case (value_type::number_float):
        {
N
Niels 已提交
1347
            if (o.type_ == value_type::number)
N
Niels 已提交
1348
            {
N
Niels 已提交
1349
                return value_.number_float == static_cast<number_float_t>(o.value_.number);
1350
            }
N
Niels 已提交
1351
            if (o.type_ == value_type::number_float)
N
Niels 已提交
1352
            {
N
Niels 已提交
1353
                return value_.number_float == o.value_.number_float;
N
Niels 已提交
1354
            }
N
Niels 已提交
1355
            break;
N
Niels 已提交
1356 1357 1358 1359 1360 1361
        }
    }

    return false;
}

N
Niels 已提交
1362
bool json::operator!=(const json& o) const noexcept
N
Niels 已提交
1363
{
N
Niels 已提交
1364 1365
    return not operator==(o);
}
N
Niels 已提交
1366 1367


N
Niels 已提交
1368
json::iterator json::begin() noexcept
N
Niels 已提交
1369
{
N
Niels 已提交
1370
    return json::iterator(this);
N
Niels 已提交
1371 1372
}

N
Niels 已提交
1373
json::iterator json::end() noexcept
N
Niels 已提交
1374
{
N
Niels 已提交
1375
    return json::iterator();
N
Niels 已提交
1376 1377
}

N
Niels 已提交
1378
json::const_iterator json::begin() const noexcept
N
Niels 已提交
1379
{
N
Niels 已提交
1380
    return json::const_iterator(this);
N
Niels 已提交
1381 1382
}

N
Niels 已提交
1383
json::const_iterator json::end() const noexcept
N
Niels 已提交
1384
{
N
Niels 已提交
1385
    return json::const_iterator();
N
Niels 已提交
1386 1387
}

N
Niels 已提交
1388
json::const_iterator json::cbegin() const noexcept
N
Niels 已提交
1389
{
N
Niels 已提交
1390
    return json::const_iterator(this);
N
Niels 已提交
1391 1392
}

N
Niels 已提交
1393
json::const_iterator json::cend() const noexcept
N
Niels 已提交
1394
{
N
Niels 已提交
1395
    return json::const_iterator();
N
Niels 已提交
1396 1397 1398
}


N
Niels 已提交
1399
json::iterator::iterator(json* j) : object_(j)
N
Niels 已提交
1400
{
N
Niels 已提交
1401
    if (object_ != nullptr)
N
Niels 已提交
1402
    {
1403
        if (object_->type_ == json::value_type::array)
N
Niels 已提交
1404
        {
N
Niels 已提交
1405
            vi_ = new array_t::iterator(object_->value_.array->begin());
N
Niels 已提交
1406
        }
1407
        if (object_->type_ == json::value_type::object)
N
Niels 已提交
1408
        {
N
Niels 已提交
1409
            oi_ = new object_t::iterator(object_->value_.object->begin());
N
Niels 已提交
1410 1411
        }
    }
N
Niels 已提交
1412 1413
}

N
Niels 已提交
1414
json::iterator::iterator(const json::iterator& o) : object_(o.object_)
N
Niels 已提交
1415
{
N
Niels 已提交
1416
    if (object_ != nullptr)
N
Niels 已提交
1417
    {
1418
        if (object_->type_ == json::value_type::array)
N
Niels 已提交
1419
        {
N
Niels 已提交
1420
            vi_ = new array_t::iterator(*(o.vi_));
N
Niels 已提交
1421
        }
1422
        if (object_->type_ == json::value_type::object)
N
Niels 已提交
1423
        {
N
Niels 已提交
1424
            oi_ = new object_t::iterator(*(o.oi_));
N
Niels 已提交
1425
        }
N
Niels 已提交
1426
    }
N
Niels 已提交
1427 1428
}

N
Niels 已提交
1429
json::iterator::~iterator()
N
Niels 已提交
1430
{
N
Niels 已提交
1431 1432
    delete vi_;
    delete oi_;
N
Niels 已提交
1433 1434
}

N
Niels 已提交
1435
json::iterator& json::iterator::operator=(json::iterator o)
N
Niels 已提交
1436
{
N
Niels 已提交
1437 1438 1439
    std::swap(object_, o.object_);
    std::swap(vi_, o.vi_);
    std::swap(oi_, o.oi_);
N
Niels 已提交
1440 1441 1442
    return *this;
}

N
Niels 已提交
1443
bool json::iterator::operator==(const json::iterator& o) const
N
Niels 已提交
1444
{
N
Niels 已提交
1445
    if (object_ != o.object_)
N
Niels 已提交
1446 1447 1448 1449
    {
        return false;
    }

N
Niels 已提交
1450
    if (object_ != nullptr)
N
Niels 已提交
1451
    {
1452
        if (object_->type_ == json::value_type::array)
N
Niels 已提交
1453
        {
N
Niels 已提交
1454
            return (vi_ == o.vi_);
N
Niels 已提交
1455
        }
1456
        if (object_->type_ == json::value_type::object)
N
Niels 已提交
1457
        {
N
Niels 已提交
1458
            return (oi_ == o.oi_);
N
Niels 已提交
1459 1460
        }
    }
N
Niels 已提交
1461

N
Niels 已提交
1462
    return true;
N
Niels 已提交
1463 1464
}

N
Niels 已提交
1465
bool json::iterator::operator!=(const json::iterator& o) const
N
Niels 已提交
1466 1467
{
    return not operator==(o);
N
Niels 已提交
1468 1469
}

N
Niels 已提交
1470
json::iterator& json::iterator::operator++()
N
Niels 已提交
1471
{
N
Niels 已提交
1472
    // iterator cannot be incremented
N
Niels 已提交
1473
    if (object_ == nullptr)
N
Niels 已提交
1474
    {
N
Niels 已提交
1475 1476 1477
        return *this;
    }

N
Niels 已提交
1478
    switch (object_->type_)
N
Niels 已提交
1479
    {
1480
        case (json::value_type::array):
N
Niels 已提交
1481
        {
N
Niels 已提交
1482
            if (++(*vi_) == object_->value_.array->end())
N
Niels 已提交
1483
            {
N
Niels 已提交
1484
                object_ = nullptr;
N
Niels 已提交
1485 1486 1487
            }
            break;
        }
1488
        case (json::value_type::object):
N
Niels 已提交
1489
        {
N
Niels 已提交
1490
            if (++(*oi_) == object_->value_.object->end())
N
Niels 已提交
1491
            {
N
Niels 已提交
1492
                object_ = nullptr;
N
Niels 已提交
1493 1494 1495
            }
            break;
        }
N
Niels 已提交
1496
        default:
N
Niels 已提交
1497
        {
N
Niels 已提交
1498
            object_ = nullptr;
N
Niels 已提交
1499 1500 1501 1502 1503
        }
    }
    return *this;
}

N
Niels 已提交
1504
json& json::iterator::operator*() const
N
Niels 已提交
1505
{
N
Niels 已提交
1506
    // dereferencing end() is an error
N
Niels 已提交
1507
    if (object_ == nullptr)
N
Niels 已提交
1508
    {
N
Niels 已提交
1509 1510 1511
        throw std::runtime_error("cannot get value");
    }

N
Niels 已提交
1512
    switch (object_->type_)
N
Niels 已提交
1513
    {
1514
        case (json::value_type::array):
N
Niels 已提交
1515
        {
N
Niels 已提交
1516
            return **vi_;
N
Niels 已提交
1517
        }
1518
        case (json::value_type::object):
N
Niels 已提交
1519
        {
N
Niels 已提交
1520
            return (*oi_)->second;
N
Niels 已提交
1521
        }
N
Niels 已提交
1522
        default:
N
Niels 已提交
1523
        {
N
Niels 已提交
1524
            return *object_;
N
Niels 已提交
1525
        }
N
Niels 已提交
1526 1527 1528
    }
}

N
Niels 已提交
1529
json* json::iterator::operator->() const
N
Niels 已提交
1530
{
N
Niels 已提交
1531
    // dereferencing end() is an error
N
Niels 已提交
1532
    if (object_ == nullptr)
N
Niels 已提交
1533
    {
N
Niels 已提交
1534 1535 1536
        throw std::runtime_error("cannot get value");
    }

N
Niels 已提交
1537
    switch (object_->type_)
N
Niels 已提交
1538
    {
1539
        case (json::value_type::array):
N
Niels 已提交
1540
        {
N
Niels 已提交
1541
            return &(**vi_);
N
Niels 已提交
1542
        }
1543
        case (json::value_type::object):
N
Niels 已提交
1544
        {
N
Niels 已提交
1545
            return &((*oi_)->second);
N
Niels 已提交
1546
        }
N
Niels 已提交
1547
        default:
N
Niels 已提交
1548
        {
N
Niels 已提交
1549
            return object_;
N
Niels 已提交
1550
        }
N
Niels 已提交
1551 1552 1553
    }
}

N
Niels 已提交
1554
std::string json::iterator::key() const
N
Niels 已提交
1555
{
1556
    if (object_ != nullptr and object_->type_ == json::value_type::object)
N
Niels 已提交
1557
    {
N
Niels 已提交
1558
        return (*oi_)->first;
N
Niels 已提交
1559 1560 1561 1562
    }
    else
    {
        throw std::out_of_range("cannot get key");
N
Niels 已提交
1563 1564 1565
    }
}

N
Niels 已提交
1566
json& json::iterator::value() const
N
Niels 已提交
1567
{
N
Niels 已提交
1568
    // dereferencing end() is an error
N
Niels 已提交
1569
    if (object_ == nullptr)
N
Niels 已提交
1570 1571
    {
        throw std::out_of_range("cannot get value");
N
Niels 已提交
1572 1573
    }

N
Niels 已提交
1574
    switch (object_->type_)
N
Niels 已提交
1575
    {
1576
        case (json::value_type::array):
N
Niels 已提交
1577
        {
N
Niels 已提交
1578
            return **vi_;
N
Niels 已提交
1579
        }
1580
        case (json::value_type::object):
N
Niels 已提交
1581
        {
N
Niels 已提交
1582
            return (*oi_)->second;
N
Niels 已提交
1583
        }
N
Niels 已提交
1584
        default:
N
Niels 已提交
1585
        {
N
Niels 已提交
1586
            return *object_;
N
Niels 已提交
1587
        }
N
Niels 已提交
1588 1589 1590 1591
    }
}


N
Niels 已提交
1592
json::const_iterator::const_iterator(const json* j) : object_(j)
N
Niels 已提交
1593
{
N
Niels 已提交
1594
    if (object_ != nullptr)
N
Niels 已提交
1595
    {
1596
        if (object_->type_ == json::value_type::array)
N
Niels 已提交
1597
        {
N
Niels 已提交
1598
            vi_ = new array_t::const_iterator(object_->value_.array->begin());
N
Niels 已提交
1599
        }
1600
        if (object_->type_ == json::value_type::object)
N
Niels 已提交
1601
        {
N
Niels 已提交
1602
            oi_ = new object_t::const_iterator(object_->value_.object->begin());
N
Niels 已提交
1603 1604
        }
    }
N
Niels 已提交
1605 1606
}

N
Niels 已提交
1607
json::const_iterator::const_iterator(const json::const_iterator& o) : object_(o.object_)
N
Niels 已提交
1608
{
N
Niels 已提交
1609
    if (object_ != nullptr)
N
Niels 已提交
1610
    {
1611
        if (object_->type_ == json::value_type::array)
N
Niels 已提交
1612
        {
N
Niels 已提交
1613
            vi_ = new array_t::const_iterator(*(o.vi_));
N
Niels 已提交
1614
        }
1615
        if (object_->type_ == json::value_type::object)
N
Niels 已提交
1616
        {
N
Niels 已提交
1617
            oi_ = new object_t::const_iterator(*(o.oi_));
N
Niels 已提交
1618 1619
        }
    }
N
Niels 已提交
1620 1621
}

N
Niels 已提交
1622
json::const_iterator::const_iterator(const json::iterator& o) : object_(o.object_)
N
Niels 已提交
1623
{
N
Niels 已提交
1624
    if (object_ != nullptr)
N
Niels 已提交
1625
    {
1626
        if (object_->type_ == json::value_type::array)
N
Niels 已提交
1627
        {
N
Niels 已提交
1628
            vi_ = new array_t::const_iterator(*(o.vi_));
N
Niels 已提交
1629
        }
1630
        if (object_->type_ == json::value_type::object)
N
Niels 已提交
1631
        {
N
Niels 已提交
1632
            oi_ = new object_t::const_iterator(*(o.oi_));
N
Niels 已提交
1633 1634
        }
    }
N
Niels 已提交
1635 1636
}

N
Niels 已提交
1637
json::const_iterator::~const_iterator()
N
Niels 已提交
1638
{
N
Niels 已提交
1639 1640
    delete vi_;
    delete oi_;
N
Niels 已提交
1641 1642
}

N
Niels 已提交
1643
json::const_iterator& json::const_iterator::operator=(json::const_iterator o)
N
Niels 已提交
1644
{
N
Niels 已提交
1645 1646 1647
    std::swap(object_, o.object_);
    std::swap(vi_, o.vi_);
    std::swap(oi_, o.oi_);
N
Niels 已提交
1648 1649 1650
    return *this;
}

N
Niels 已提交
1651
bool json::const_iterator::operator==(const json::const_iterator& o) const
N
Niels 已提交
1652
{
N
Niels 已提交
1653
    if (object_ != o.object_)
N
Niels 已提交
1654 1655 1656 1657
    {
        return false;
    }

N
Niels 已提交
1658
    if (object_ != nullptr)
N
Niels 已提交
1659
    {
1660
        if (object_->type_ == json::value_type::array)
N
Niels 已提交
1661
        {
N
Niels 已提交
1662
            return (vi_ == o.vi_);
N
Niels 已提交
1663
        }
1664
        if (object_->type_ == json::value_type::object)
N
Niels 已提交
1665
        {
N
Niels 已提交
1666
            return (oi_ == o.oi_);
N
Niels 已提交
1667
        }
N
Niels 已提交
1668
    }
N
Niels 已提交
1669

N
Niels 已提交
1670
    return true;
N
Niels 已提交
1671 1672
}

N
Niels 已提交
1673
bool json::const_iterator::operator!=(const json::const_iterator& o) const
N
Niels 已提交
1674 1675
{
    return not operator==(o);
N
Niels 已提交
1676 1677
}

N
Niels 已提交
1678
json::const_iterator& json::const_iterator::operator++()
N
Niels 已提交
1679
{
N
Niels 已提交
1680
    // iterator cannot be incremented
N
Niels 已提交
1681
    if (object_ == nullptr)
N
Niels 已提交
1682
    {
N
Niels 已提交
1683 1684 1685
        return *this;
    }

N
Niels 已提交
1686
    switch (object_->type_)
N
Niels 已提交
1687
    {
1688
        case (json::value_type::array):
N
Niels 已提交
1689
        {
N
Niels 已提交
1690
            if (++(*vi_) == object_->value_.array->end())
N
Niels 已提交
1691
            {
N
Niels 已提交
1692
                object_ = nullptr;
N
Niels 已提交
1693 1694 1695
            }
            break;
        }
1696
        case (json::value_type::object):
N
Niels 已提交
1697
        {
N
Niels 已提交
1698
            if (++(*oi_) == object_->value_.object->end())
N
Niels 已提交
1699
            {
N
Niels 已提交
1700
                object_ = nullptr;
N
Niels 已提交
1701 1702 1703
            }
            break;
        }
N
Niels 已提交
1704
        default:
N
Niels 已提交
1705
        {
N
Niels 已提交
1706
            object_ = nullptr;
N
Niels 已提交
1707 1708 1709 1710 1711
        }
    }
    return *this;
}

N
Niels 已提交
1712
const json& json::const_iterator::operator*() const
N
Niels 已提交
1713
{
N
Niels 已提交
1714
    // dereferencing end() is an error
N
Niels 已提交
1715
    if (object_ == nullptr)
N
Niels 已提交
1716
    {
N
Niels 已提交
1717 1718 1719
        throw std::runtime_error("cannot get value");
    }

N
Niels 已提交
1720
    switch (object_->type_)
N
Niels 已提交
1721
    {
1722
        case (json::value_type::array):
N
Niels 已提交
1723
        {
N
Niels 已提交
1724
            return **vi_;
N
Niels 已提交
1725
        }
1726
        case (json::value_type::object):
N
Niels 已提交
1727
        {
N
Niels 已提交
1728
            return (*oi_)->second;
N
Niels 已提交
1729
        }
N
Niels 已提交
1730
        default:
N
Niels 已提交
1731
        {
N
Niels 已提交
1732
            return *object_;
N
Niels 已提交
1733
        }
N
Niels 已提交
1734 1735 1736
    }
}

N
Niels 已提交
1737
const json* json::const_iterator::operator->() const
N
Niels 已提交
1738
{
N
Niels 已提交
1739
    // dereferencing end() is an error
N
Niels 已提交
1740
    if (object_ == nullptr)
N
Niels 已提交
1741
    {
N
Niels 已提交
1742 1743 1744
        throw std::runtime_error("cannot get value");
    }

N
Niels 已提交
1745
    switch (object_->type_)
N
Niels 已提交
1746
    {
1747
        case (json::value_type::array):
N
Niels 已提交
1748
        {
N
Niels 已提交
1749
            return &(**vi_);
N
Niels 已提交
1750
        }
1751
        case (json::value_type::object):
N
Niels 已提交
1752
        {
N
Niels 已提交
1753
            return &((*oi_)->second);
N
Niels 已提交
1754
        }
N
Niels 已提交
1755
        default:
N
Niels 已提交
1756
        {
N
Niels 已提交
1757
            return object_;
N
Niels 已提交
1758
        }
N
Niels 已提交
1759 1760 1761
    }
}

N
Niels 已提交
1762
std::string json::const_iterator::key() const
N
Niels 已提交
1763
{
1764
    if (object_ != nullptr and object_->type_ == json::value_type::object)
N
Niels 已提交
1765
    {
N
Niels 已提交
1766
        return (*oi_)->first;
N
Niels 已提交
1767 1768 1769 1770
    }
    else
    {
        throw std::out_of_range("cannot get key");
N
Niels 已提交
1771 1772 1773
    }
}

N
Niels 已提交
1774
const json& json::const_iterator::value() const
N
Niels 已提交
1775
{
N
Niels 已提交
1776
    // dereferencing end() is an error
N
Niels 已提交
1777
    if (object_ == nullptr)
N
Niels 已提交
1778 1779
    {
        throw std::out_of_range("cannot get value");
N
Niels 已提交
1780 1781
    }

N
Niels 已提交
1782
    switch (object_->type_)
N
Niels 已提交
1783
    {
1784
        case (json::value_type::array):
N
Niels 已提交
1785
        {
N
Niels 已提交
1786
            return **vi_;
N
Niels 已提交
1787
        }
1788
        case (json::value_type::object):
N
Niels 已提交
1789
        {
N
Niels 已提交
1790
            return (*oi_)->second;
N
Niels 已提交
1791
        }
N
Niels 已提交
1792
        default:
N
Niels 已提交
1793
        {
N
Niels 已提交
1794
            return *object_;
N
Niels 已提交
1795
        }
N
Niels 已提交
1796 1797
    }
}
N
Niels 已提交
1798 1799 1800 1801 1802 1803 1804 1805 1806


/*!
Initialize the JSON parser given a string \p s.

@note After initialization, the function @ref parse has to be called manually.

@param s  string to parse

N
Niels 已提交
1807
@post \p s is copied to the buffer @ref buffer_ and the first character is
N
Niels 已提交
1808 1809
      read. Whitespace is skipped.
*/
N
Niels 已提交
1810
json::parser::parser(const char* s)
N
Niels 已提交
1811
    :  buffer_(s)
N
Niels 已提交
1812 1813 1814 1815 1816 1817
{
    // read first character
    next();
}

/*!
N
Niels 已提交
1818
@copydoc json::parser::parser(const char* s)
N
Niels 已提交
1819
*/
N
Niels 已提交
1820
json::parser::parser(const std::string& s)
N
Niels 已提交
1821
    : buffer_(s)
N
Niels 已提交
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
{
    // read first character
    next();
}

/*!
Initialize the JSON parser given an input stream \p _is.

@note After initialization, the function @ref parse has to be called manually.

\param _is input stream to parse

N
Niels 已提交
1834
@post \p _is is copied to the buffer @ref buffer_ and the firsr character is
N
Niels 已提交
1835 1836 1837
      read. Whitespace is skipped.

*/
N
Niels 已提交
1838
json::parser::parser(std::istream& _is)
N
Niels 已提交
1839
{
N
Niels 已提交
1840 1841
    while (_is)
    {
N
Niels 已提交
1842
        std::string input_line;
N
Niels 已提交
1843
        std::getline(_is, input_line);
N
Niels 已提交
1844
        buffer_ += input_line;
N
Niels 已提交
1845
    }
N
Niels 已提交
1846 1847 1848 1849 1850

    // read first character
    next();
}

N
Niels 已提交
1851
json json::parser::parse()
N
Niels 已提交
1852
{
N
Niels 已提交
1853
    switch (current_)
N
Niels 已提交
1854 1855 1856 1857
    {
        case ('{'):
        {
            // explicitly set result to object to cope with {}
N
Niels 已提交
1858
            json result(value_type::object);
N
Niels 已提交
1859 1860 1861 1862

            next();

            // process nonempty object
N
Niels 已提交
1863
            if (current_ != '}')
N
Niels 已提交
1864 1865 1866 1867
            {
                do
                {
                    // key
N
cleanup  
Niels 已提交
1868
                    auto key = parseString();
N
Niels 已提交
1869 1870 1871 1872 1873

                    // colon
                    expect(':');

                    // value
N
Niels 已提交
1874
                    result[std::move(key)] = parse();
N
cleanup  
Niels 已提交
1875
                    key.clear();
N
Niels 已提交
1876
                }
N
Niels 已提交
1877
                while (current_ == ',' and next());
N
Niels 已提交
1878 1879 1880 1881 1882
            }

            // closing brace
            expect('}');

N
Niels 已提交
1883
            return result;
N
Niels 已提交
1884 1885 1886 1887 1888
        }

        case ('['):
        {
            // explicitly set result to array to cope with []
N
Niels 已提交
1889
            json result(value_type::array);
N
Niels 已提交
1890 1891 1892 1893

            next();

            // process nonempty array
N
Niels 已提交
1894
            if (current_ != ']')
N
Niels 已提交
1895 1896 1897
            {
                do
                {
N
Niels 已提交
1898
                    result.push_back(parse());
N
Niels 已提交
1899
                }
N
Niels 已提交
1900
                while (current_ == ',' and next());
N
Niels 已提交
1901 1902 1903 1904 1905
            }

            // closing bracket
            expect(']');

N
Niels 已提交
1906
            return result;
N
Niels 已提交
1907 1908 1909 1910
        }

        case ('\"'):
        {
N
Niels 已提交
1911
            return json(parseString());
N
Niels 已提交
1912 1913 1914 1915 1916
        }

        case ('t'):
        {
            parseTrue();
N
Niels 已提交
1917
            return json(true);
N
Niels 已提交
1918 1919 1920 1921 1922
        }

        case ('f'):
        {
            parseFalse();
N
Niels 已提交
1923
            return json(false);
N
Niels 已提交
1924 1925 1926 1927 1928
        }

        case ('n'):
        {
            parseNull();
N
Niels 已提交
1929
            return json();
N
Niels 已提交
1930 1931
        }

N
cleanup  
Niels 已提交
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
        case ('-'):
        case ('0'):
        case ('1'):
        case ('2'):
        case ('3'):
        case ('4'):
        case ('5'):
        case ('6'):
        case ('7'):
        case ('8'):
        case ('9'):
N
Niels 已提交
1943
        {
N
cleanup  
Niels 已提交
1944
            // remember position of number's first character
N
Niels 已提交
1945
            const auto _firstpos_ = pos_ - 1;
N
cleanup  
Niels 已提交
1946

N
Niels 已提交
1947 1948 1949
            while (next() and (std::isdigit(current_) || current_ == '.'
                               || current_ == 'e' || current_ == 'E'
                               || current_ == '+' || current_ == '-'));
N
cleanup  
Niels 已提交
1950 1951

            try
N
Niels 已提交
1952
            {
N
Niels 已提交
1953
                const auto float_val = std::stod(buffer_.substr(_firstpos_, pos_ - _firstpos_));
N
cleanup  
Niels 已提交
1954
                const auto int_val = static_cast<int>(float_val);
N
Niels 已提交
1955

N
cleanup  
Niels 已提交
1956 1957
                // check if conversion loses precision
                if (float_val == int_val)
N
Niels 已提交
1958
                {
N
cleanup  
Niels 已提交
1959
                    // we would not lose precision -> int
N
Niels 已提交
1960
                    return json(int_val);
N
Niels 已提交
1961
                }
N
cleanup  
Niels 已提交
1962
                else
N
Niels 已提交
1963
                {
N
cleanup  
Niels 已提交
1964
                    // we would lose precision -> float
N
Niels 已提交
1965
                    return json(float_val);
N
Niels 已提交
1966 1967
                }
            }
N
cleanup  
Niels 已提交
1968
            catch (...)
N
Niels 已提交
1969
            {
N
cleanup  
Niels 已提交
1970
                error("error translating " +
N
Niels 已提交
1971
                      buffer_.substr(_firstpos_, pos_ - _firstpos_) + " to number");
N
Niels 已提交
1972 1973
            }
        }
N
cleanup  
Niels 已提交
1974 1975 1976 1977 1978

        default:
        {
            error("unexpected character");
        }
N
Niels 已提交
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
    }
}

/*!
This function reads the next character from the buffer while ignoring all
trailing whitespace. If another character could be read, the function returns
true. If the end of the buffer is reached, false is returned.

@return whether another non-whitespace character could be read

N
Niels 已提交
1989
@post current_ holds the next character
N
Niels 已提交
1990
*/
N
Niels 已提交
1991
bool json::parser::next()
N
Niels 已提交
1992
{
N
Niels 已提交
1993
    if (pos_ == buffer_.size())
N
Niels 已提交
1994 1995 1996 1997
    {
        return false;
    }

N
Niels 已提交
1998
    current_ = buffer_[pos_++];
N
Niels 已提交
1999 2000

    // skip trailing whitespace
N
Niels 已提交
2001
    while (std::isspace(current_))
N
Niels 已提交
2002
    {
N
Niels 已提交
2003
        if (pos_ == buffer_.size())
N
Niels 已提交
2004 2005 2006 2007
        {
            return false;
        }

N
Niels 已提交
2008
        current_ = buffer_[pos_++];
N
Niels 已提交
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
    }

    return true;
}

/*!
This function encapsulates the error reporting functions of the parser class.
It throws a \p std::invalid_argument exception with a description where the
error occurred (given as the number of characters read), what went wrong (using
the error message \p msg), and the last read token.

@param msg  an error message
@return <em>This function does not return.</em>

@exception std::invalid_argument whenever the function is called
*/
N
Niels 已提交
2025
void json::parser::error(const std::string& msg)
N
Niels 已提交
2026 2027
{
    throw std::invalid_argument("parse error at position " +
N
Niels 已提交
2028 2029
                                std::to_string(pos_) + ": " + msg +
                                ", last read: '" + current_ + "'");
N
Niels 已提交
2030 2031 2032 2033 2034 2035 2036 2037
}

/*!
Parses a string after opening quotes (\p ") where read.

@return the parsed string

@pre  An opening quote \p " was read in the main parse function @ref parse.
N
Niels 已提交
2038
      pos_ is the position after the opening quote.
N
Niels 已提交
2039 2040

@post The character after the closing quote \p " is the current character @ref
N
Niels 已提交
2041
      current_. Whitespace is skipped.
N
Niels 已提交
2042 2043 2044

@todo Unicode escapes such as \uxxxx are missing - see
      https://github.com/nlohmann/json/issues/12
N
Niels 已提交
2045
*/
N
Niels 已提交
2046
std::string json::parser::parseString()
N
Niels 已提交
2047
{
R
Raphael Isemann 已提交
2048 2049 2050 2051
    // true if and only if the amount of backslashes before the current
    // character is even
    bool evenAmountOfBackslashes = true;

2052 2053 2054
    // the result of the parse process
    std::string result;

R
Raphael Isemann 已提交
2055
    // iterate with pos_ over the whole string
N
Niels 已提交
2056 2057
    for (; pos_ < buffer_.size(); pos_++)
    {
R
Raphael Isemann 已提交
2058 2059
        char currentChar = buffer_[pos_];

2060
        // uneven amount of backslashes means the user wants to escape something
N
Niels 已提交
2061 2062
        if (!evenAmountOfBackslashes)
        {
2063
            // slash, backslash and quote are copied as is
N
Niels 已提交
2064 2065
            if (currentChar == '/' or currentChar == '\\' or currentChar == '"')
            {
2066
                result += currentChar;
N
Niels 已提交
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
            }
            else
            {
                // all other characters are replaced by their respective
                // special character
                switch (currentChar)
                {
                    case 't':
                    {
                        result += '\t';
                        break;
                    }
                    case 'b':
                    {
                        result += '\b';
                        break;
                    }
                    case 'f':
                    {
                        result += '\f';
                        break;
                    }
                    case 'n':
                    {
                        result += '\n';
                        break;
                    }
                    case 'r':
                    {
                        result += '\r';
                        break;
                    }
                    default:
                    {
                        error("expected one of \\, /, b, f, n, r, t behind backslash.");
                    }
2103 2104 2105
                }
                // TODO implement \uXXXX
            }
N
Niels 已提交
2106 2107 2108 2109 2110
        }
        else
        {
            if (currentChar == '"')
            {
2111 2112
                // currentChar is a quote, so we found the end of the string

R
Raphael Isemann 已提交
2113 2114 2115 2116 2117
                // set pos_ behind the trailing quote
                pos_++;
                // find next char to parse
                next();

2118 2119
                // bring the result of the parsing process back to the caller
                return result;
N
Niels 已提交
2120 2121 2122 2123 2124 2125
            }
            else if (currentChar != '\\')
            {
                // All non-backslash characters are added to the end of the
                // result string. The only backslashes we want in the result
                // are the ones that are escaped (which happens above).
2126
                result += currentChar;
R
Raphael Isemann 已提交
2127 2128
            }
        }
N
Niels 已提交
2129

N
Niels 已提交
2130 2131 2132 2133
        // remember if we have an even amount of backslashes before the current
        // character
        if (currentChar == '\\')
        {
R
Raphael Isemann 已提交
2134
            // jump between even/uneven for each backslash we encounter
N
Niels 已提交
2135 2136 2137 2138 2139 2140 2141
            evenAmountOfBackslashes = not evenAmountOfBackslashes;
        }
        else
        {
            // zero backslashes are also an even number, so as soon as we
            // encounter a non-backslash the chain of backslashes breaks and
            // we start again from zero
R
Raphael Isemann 已提交
2142 2143
            evenAmountOfBackslashes = true;
        }
N
Niels 已提交
2144 2145
    }

R
Raphael Isemann 已提交
2146 2147 2148
    // we iterated over the whole string without finding a unescaped quote
    // so the given string is malformed
    error("expected '\"'");
N
Niels 已提交
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
}

/*!
This function is called in case a \p "t" is read in the main parse function
@ref parse. In the standard, the \p "true" token is the only candidate, so the
next three characters are expected to be \p "rue". In case of a mismatch, an
error is raised via @ref error.

@pre  A \p "t" was read in the main parse function @ref parse.
@post The character after the \p "true" is the current character. Whitespace is
      skipped.
*/
N
Niels 已提交
2161
void json::parser::parseTrue()
N
Niels 已提交
2162
{
N
Niels 已提交
2163
    if (buffer_.substr(pos_, 3) != "rue")
N
Niels 已提交
2164 2165 2166 2167
    {
        error("expected true");
    }

N
Niels 已提交
2168
    pos_ += 3;
N
Niels 已提交
2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183

    // read next character
    next();
}

/*!
This function is called in case an \p "f" is read in the main parse function
@ref parse. In the standard, the \p "false" token is the only candidate, so the
next four characters are expected to be \p "alse". In case of a mismatch, an
error is raised via @ref error.

@pre  An \p "f" was read in the main parse function.
@post The character after the \p "false" is the current character. Whitespace
      is skipped.
*/
N
Niels 已提交
2184
void json::parser::parseFalse()
N
Niels 已提交
2185
{
N
Niels 已提交
2186
    if (buffer_.substr(pos_, 4) != "alse")
N
Niels 已提交
2187 2188 2189 2190
    {
        error("expected false");
    }

N
Niels 已提交
2191
    pos_ += 4;
N
Niels 已提交
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206

    // read next character
    next();
}

/*!
This function is called in case an \p "n" is read in the main parse function
@ref parse. In the standard, the \p "null" token is the only candidate, so the
next three characters are expected to be \p "ull". In case of a mismatch, an
error is raised via @ref error.

@pre  An \p "n" was read in the main parse function.
@post The character after the \p "null" is the current character. Whitespace is
      skipped.
*/
N
Niels 已提交
2207
void json::parser::parseNull()
N
Niels 已提交
2208
{
N
Niels 已提交
2209
    if (buffer_.substr(pos_, 3) != "ull")
N
Niels 已提交
2210 2211 2212 2213
    {
        error("expected null");
    }

N
Niels 已提交
2214
    pos_ += 3;
N
Niels 已提交
2215 2216 2217 2218 2219 2220 2221

    // read next character
    next();
}

/*!
This function wraps functionality to check whether the current character @ref
N
Niels 已提交
2222 2223
current_ matches a given character \p c. In case of a match, the next character
of the buffer @ref buffer_ is read. In case of a mismatch, an error is raised
N
Niels 已提交
2224 2225 2226 2227 2228 2229
via @ref error.

@param c  character that is expected

@post The next chatacter is read. Whitespace is skipped.
*/
N
Niels 已提交
2230
void json::parser::expect(const char c)
N
Niels 已提交
2231
{
N
Niels 已提交
2232
    if (current_ != c)
N
Niels 已提交
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
    {
        std::string msg = "expected '";
        msg.append(1, c);
        msg += "'";
        error(msg);
    }
    else
    {
        next();
    }
}

N
Niels 已提交
2245 2246
}

N
Niels 已提交
2247 2248 2249 2250 2251 2252 2253 2254
/*!
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 已提交
2255
nlohmann::json operator "" _json(const char* s, std::size_t)
N
Niels 已提交
2256
{
N
Niels 已提交
2257
    return nlohmann::json::parse(s);
N
Niels 已提交
2258
}