1 /*
2 __ _____ _____ _____
3 __| | __| | | | JSON for Modern C++
4 | | |__ | | | | | | version 3.1.1
5 |_____|_____|_____|_|___| https://github.com/nlohmann/json
6
7 Licensed under the MIT License <http://opensource.org/licenses/MIT>.
8 Copyright (c) 2013-2018 Niels Lohmann <http://nlohmann.me>.
9
10 Permission is hereby granted, free of charge, to any person obtaining a copy
11 of this software and associated documentation files (the "Software"), to deal
12 in the Software without restriction, including without limitation the rights
13 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 copies of the Software, and to permit persons to whom the Software is
15 furnished to do so, subject to the following conditions:
16
17 The above copyright notice and this permission notice shall be included in all
18 copies or substantial portions of the Software.
19
20 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26 SOFTWARE.
27 */
28
29 #ifndef NLOHMANN_JSON_HPP
30 #define NLOHMANN_JSON_HPP
31
32 #define NLOHMANN_JSON_VERSION_MAJOR 3
33 #define NLOHMANN_JSON_VERSION_MINOR 1
34 #define NLOHMANN_JSON_VERSION_PATCH 1
35
36 #include <algorithm> // all_of, find, for_each
37 #include <cassert> // assert
38 #include <ciso646> // and, not, or
39 #include <cstddef> // nullptr_t, ptrdiff_t, size_t
40 #include <functional> // hash, less
41 #include <initializer_list> // initializer_list
42 #include <iosfwd> // istream, ostream
43 #include <iterator> // iterator_traits, random_access_iterator_tag
44 #include <numeric> // accumulate
45 #include <string> // string, stoi, to_string
46 #include <utility> // declval, forward, move, pair, swap
47
48 // #include <nlohmann/json_fwd.hpp>
49 #ifndef NLOHMANN_JSON_FWD_HPP
50 #define NLOHMANN_JSON_FWD_HPP
51
52 #include <cstdint> // int64_t, uint64_t
53 #include <map> // map
54 #include <memory> // allocator
55 #include <string> // string
56 #include <vector> // vector
57
58 /*!
59 @brief namespace for Niels Lohmann
60 @see https://github.com/nlohmann
61 @since version 1.0.0
62 */
63 namespace nlohmann
64 {
65 /*!
66 @brief default JSONSerializer template argument
67
68 This serializer ignores the template arguments and uses ADL
69 ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl))
70 for serialization.
71 */
72 template<typename = void, typename = void>
73 struct adl_serializer;
74
75 template<template<typename U, typename V, typename... Args> class ObjectType =
76 std::map,
77 template<typename U, typename... Args> class ArrayType = std::vector,
78 class StringType = std::string, class BooleanType = bool,
79 class NumberIntegerType = std::int64_t,
80 class NumberUnsignedType = std::uint64_t,
81 class NumberFloatType = double,
82 template<typename U> class AllocatorType = std::allocator,
83 template<typename T, typename SFINAE = void> class JSONSerializer =
84 adl_serializer>
85 class basic_json;
86
87 /*!
88 @brief JSON Pointer
89
90 A JSON pointer defines a string syntax for identifying a specific value
91 within a JSON document. It can be used with functions `at` and
92 `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
93
94 @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
95
96 @since version 2.0.0
97 */
98 template<typename BasicJsonType>
99 class json_pointer;
100
101 /*!
102 @brief default JSON class
103
104 This type is the default specialization of the @ref basic_json class which
105 uses the standard template types.
106
107 @since version 1.0.0
108 */
109 using json = basic_json<>;
110 }
111
112 #endif
113
114 // #include <nlohmann/detail/macro_scope.hpp>
115
116
117 // This file contains all internal macro definitions
118 // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
119
120 // exclude unsupported compilers
121 #if defined(__clang__)
122 #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
123 #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
124 #endif
125 #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
126 #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900
127 #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
128 #endif
129 #endif
130
131 // disable float-equal warnings on GCC/clang
132 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
133 #pragma GCC diagnostic push
134 #pragma GCC diagnostic ignored "-Wfloat-equal"
135 #endif
136
137 // disable documentation warnings on clang
138 #if defined(__clang__)
139 #pragma GCC diagnostic push
140 #pragma GCC diagnostic ignored "-Wdocumentation"
141 #endif
142
143 // allow for portable deprecation warnings
144 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
145 #define JSON_DEPRECATED __attribute__((deprecated))
146 #elif defined(_MSC_VER)
147 #define JSON_DEPRECATED __declspec(deprecated)
148 #else
149 #define JSON_DEPRECATED
150 #endif
151
152 // allow to disable exceptions
153 #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
154 #define JSON_THROW(exception) throw exception
155 #define JSON_TRY try
156 #define JSON_CATCH(exception) catch(exception)
157 #else
158 #define JSON_THROW(exception) std::abort()
159 #define JSON_TRY if(true)
160 #define JSON_CATCH(exception) if(false)
161 #endif
162
163 // override exception macros
164 #if defined(JSON_THROW_USER)
165 #undef JSON_THROW
166 #define JSON_THROW JSON_THROW_USER
167 #endif
168 #if defined(JSON_TRY_USER)
169 #undef JSON_TRY
170 #define JSON_TRY JSON_TRY_USER
171 #endif
172 #if defined(JSON_CATCH_USER)
173 #undef JSON_CATCH
174 #define JSON_CATCH JSON_CATCH_USER
175 #endif
176
177 // manual branch prediction
178 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
179 #define JSON_LIKELY(x) __builtin_expect(!!(x), 1)
180 #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
181 #else
182 #define JSON_LIKELY(x) x
183 #define JSON_UNLIKELY(x) x
184 #endif
185
186 // C++ language standard detection
187 #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
188 #define JSON_HAS_CPP_17
189 #define JSON_HAS_CPP_14
190 #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
191 #define JSON_HAS_CPP_14
192 #endif
193
194 // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
195 // may be removed in the future once the class is split.
196
197 #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
198 template<template<typename, typename, typename...> class ObjectType, \
199 template<typename, typename...> class ArrayType, \
200 class StringType, class BooleanType, class NumberIntegerType, \
201 class NumberUnsignedType, class NumberFloatType, \
202 template<typename> class AllocatorType, \
203 template<typename, typename = void> class JSONSerializer>
204
205 #define NLOHMANN_BASIC_JSON_TPL \
206 basic_json<ObjectType, ArrayType, StringType, BooleanType, \
207 NumberIntegerType, NumberUnsignedType, NumberFloatType, \
208 AllocatorType, JSONSerializer>
209
210 /*!
211 @brief Helper to determine whether there's a key_type for T.
212
213 This helper is used to tell associative containers apart from other containers
214 such as sequence containers. For instance, `std::map` passes the test as it
215 contains a `mapped_type`, whereas `std::vector` fails the test.
216
217 @sa http://stackoverflow.com/a/7728728/266378
218 @since version 1.0.0, overworked in version 2.0.6
219 */
220 #define NLOHMANN_JSON_HAS_HELPER(type) \
221 template<typename T> struct has_##type { \
222 private: \
223 template<typename U, typename = typename U::type> \
224 static int detect(U &&); \
225 static void detect(...); \
226 public: \
227 static constexpr bool value = \
228 std::is_integral<decltype(detect(std::declval<T>()))>::value; \
229 }
230
231 // #include <nlohmann/detail/meta.hpp>
232
233
234 #include <ciso646> // not
235 #include <cstddef> // size_t
236 #include <limits> // numeric_limits
237 #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
238 #include <utility> // declval
239
240 // #include <nlohmann/json_fwd.hpp>
241
242 // #include <nlohmann/detail/macro_scope.hpp>
243
244
245 namespace nlohmann
246 {
247 /*!
248 @brief detail namespace with internal helper functions
249
250 This namespace collects functions that should not be exposed,
251 implementations of some @ref basic_json methods, and meta-programming helpers.
252
253 @since version 2.1.0
254 */
255 namespace detail
256 {
257 /////////////
258 // helpers //
259 /////////////
260
261 template<typename> struct is_basic_json : std::false_type {};
262
263 NLOHMANN_BASIC_JSON_TPL_DECLARATION
264 struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
265
266 // alias templates to reduce boilerplate
267 template<bool B, typename T = void>
268 using enable_if_t = typename std::enable_if<B, T>::type;
269
270 template<typename T>
271 using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
272
273 // implementation of C++14 index_sequence and affiliates
274 // source: https://stackoverflow.com/a/32223343
275 template<std::size_t... Ints>
276 struct index_sequence
277 {
278 using type = index_sequence;
279 using value_type = std::size_t;
sizenlohmann::detail::index_sequence280 static constexpr std::size_t size() noexcept
281 {
282 return sizeof...(Ints);
283 }
284 };
285
286 template<class Sequence1, class Sequence2>
287 struct merge_and_renumber;
288
289 template<std::size_t... I1, std::size_t... I2>
290 struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
291 : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
292
293 template<std::size_t N>
294 struct make_index_sequence
295 : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
296 typename make_index_sequence < N - N / 2 >::type > {};
297
298 template<> struct make_index_sequence<0> : index_sequence<> {};
299 template<> struct make_index_sequence<1> : index_sequence<0> {};
300
301 template<typename... Ts>
302 using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
303
304 /*
305 Implementation of two C++17 constructs: conjunction, negation. This is needed
306 to avoid evaluating all the traits in a condition
307
308 For example: not std::is_same<void, T>::value and has_value_type<T>::value
309 will not compile when T = void (on MSVC at least). Whereas
310 conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
311 stop evaluating if negation<...>::value == false
312
313 Please note that those constructs must be used with caution, since symbols can
314 become very long quickly (which can slow down compilation and cause MSVC
315 internal compiler errors). Only use it when you have to (see example ahead).
316 */
317 template<class...> struct conjunction : std::true_type {};
318 template<class B1> struct conjunction<B1> : B1 {};
319 template<class B1, class... Bn>
320 struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
321
322 template<class B> struct negation : std::integral_constant<bool, not B::value> {};
323
324 // dispatch utility (taken from ranges-v3)
325 template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
326 template<> struct priority_tag<0> {};
327
328 ////////////////////////
329 // has_/is_ functions //
330 ////////////////////////
331
332 // source: https://stackoverflow.com/a/37193089/4116453
333
334 template <typename T, typename = void>
335 struct is_complete_type : std::false_type {};
336
337 template <typename T>
338 struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
339
340 NLOHMANN_JSON_HAS_HELPER(mapped_type);
341 NLOHMANN_JSON_HAS_HELPER(key_type);
342 NLOHMANN_JSON_HAS_HELPER(value_type);
343 NLOHMANN_JSON_HAS_HELPER(iterator);
344
345 template<bool B, class RealType, class CompatibleObjectType>
346 struct is_compatible_object_type_impl : std::false_type {};
347
348 template<class RealType, class CompatibleObjectType>
349 struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
350 {
351 static constexpr auto value =
352 std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and
353 std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value;
354 };
355
356 template<class BasicJsonType, class CompatibleObjectType>
357 struct is_compatible_object_type
358 {
359 static auto constexpr value = is_compatible_object_type_impl <
360 conjunction<negation<std::is_same<void, CompatibleObjectType>>,
361 has_mapped_type<CompatibleObjectType>,
362 has_key_type<CompatibleObjectType>>::value,
363 typename BasicJsonType::object_t, CompatibleObjectType >::value;
364 };
365
366 template<typename BasicJsonType, typename T>
367 struct is_basic_json_nested_type
368 {
369 static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
370 std::is_same<T, typename BasicJsonType::const_iterator>::value or
371 std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
372 std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value;
373 };
374
375 template<class BasicJsonType, class CompatibleArrayType>
376 struct is_compatible_array_type
377 {
378 static auto constexpr value =
379 conjunction<negation<std::is_same<void, CompatibleArrayType>>,
380 negation<is_compatible_object_type<
381 BasicJsonType, CompatibleArrayType>>,
382 negation<std::is_constructible<typename BasicJsonType::string_t,
383 CompatibleArrayType>>,
384 negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
385 has_value_type<CompatibleArrayType>,
386 has_iterator<CompatibleArrayType>>::value;
387 };
388
389 template<bool, typename, typename>
390 struct is_compatible_integer_type_impl : std::false_type {};
391
392 template<typename RealIntegerType, typename CompatibleNumberIntegerType>
393 struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
394 {
395 // is there an assert somewhere on overflows?
396 using RealLimits = std::numeric_limits<RealIntegerType>;
397 using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
398
399 static constexpr auto value =
400 std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and
401 CompatibleLimits::is_integer and
402 RealLimits::is_signed == CompatibleLimits::is_signed;
403 };
404
405 template<typename RealIntegerType, typename CompatibleNumberIntegerType>
406 struct is_compatible_integer_type
407 {
408 static constexpr auto value =
409 is_compatible_integer_type_impl <
410 std::is_integral<CompatibleNumberIntegerType>::value and
411 not std::is_same<bool, CompatibleNumberIntegerType>::value,
412 RealIntegerType, CompatibleNumberIntegerType > ::value;
413 };
414
415 // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
416 template<typename BasicJsonType, typename T>
417 struct has_from_json
418 {
419 private:
420 // also check the return type of from_json
421 template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
422 std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
423 static int detect(U&&);
424 static void detect(...);
425
426 public:
427 static constexpr bool value = std::is_integral<decltype(
428 detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
429 };
430
431 // This trait checks if JSONSerializer<T>::from_json(json const&) exists
432 // this overload is used for non-default-constructible user-defined-types
433 template<typename BasicJsonType, typename T>
434 struct has_non_default_from_json
435 {
436 private:
437 template <
438 typename U,
439 typename = enable_if_t<std::is_same<
440 T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value >>
441 static int detect(U&&);
442 static void detect(...);
443
444 public:
445 static constexpr bool value = std::is_integral<decltype(detect(
446 std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
447 };
448
449 // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
450 template<typename BasicJsonType, typename T>
451 struct has_to_json
452 {
453 private:
454 template<typename U, typename = decltype(uncvref_t<U>::to_json(
455 std::declval<BasicJsonType&>(), std::declval<T>()))>
456 static int detect(U&&);
457 static void detect(...);
458
459 public:
460 static constexpr bool value = std::is_integral<decltype(detect(
461 std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
462 };
463
464 template <typename BasicJsonType, typename CompatibleCompleteType>
465 struct is_compatible_complete_type
466 {
467 static constexpr bool value =
468 not std::is_base_of<std::istream, CompatibleCompleteType>::value and
469 not std::is_same<BasicJsonType, CompatibleCompleteType>::value and
470 not is_basic_json_nested_type<BasicJsonType, CompatibleCompleteType>::value and
471 has_to_json<BasicJsonType, CompatibleCompleteType>::value;
472 };
473
474 template <typename BasicJsonType, typename CompatibleType>
475 struct is_compatible_type
476 : conjunction<is_complete_type<CompatibleType>,
477 is_compatible_complete_type<BasicJsonType, CompatibleType>>
478 {
479 };
480
481 // taken from ranges-v3
482 template<typename T>
483 struct static_const
484 {
485 static constexpr T value{};
486 };
487
488 template<typename T>
489 constexpr T static_const<T>::value;
490 }
491 }
492
493 // #include <nlohmann/detail/exceptions.hpp>
494
495
496 #include <exception> // exception
497 #include <stdexcept> // runtime_error
498 #include <string> // to_string
499
500 namespace nlohmann
501 {
502 namespace detail
503 {
504 ////////////////
505 // exceptions //
506 ////////////////
507
508 /*!
509 @brief general exception of the @ref basic_json class
510
511 This class is an extension of `std::exception` objects with a member @a id for
512 exception ids. It is used as the base class for all exceptions thrown by the
513 @ref basic_json class. This class can hence be used as "wildcard" to catch
514 exceptions.
515
516 Subclasses:
517 - @ref parse_error for exceptions indicating a parse error
518 - @ref invalid_iterator for exceptions indicating errors with iterators
519 - @ref type_error for exceptions indicating executing a member function with
520 a wrong type
521 - @ref out_of_range for exceptions indicating access out of the defined range
522 - @ref other_error for exceptions indicating other library errors
523
524 @internal
525 @note To have nothrow-copy-constructible exceptions, we internally use
526 `std::runtime_error` which can cope with arbitrary-length error messages.
527 Intermediate strings are built with static functions and then passed to
528 the actual constructor.
529 @endinternal
530
531 @liveexample{The following code shows how arbitrary library exceptions can be
532 caught.,exception}
533
534 @since version 3.0.0
535 */
536 class exception : public std::exception
537 {
538 public:
539 /// returns the explanatory string
what() const540 const char* what() const noexcept override
541 {
542 return m.what();
543 }
544
545 /// the id of the exception
546 const int id;
547
548 protected:
exception(int id_,const char * what_arg)549 exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
550
name(const std::string & ename,int id_)551 static std::string name(const std::string& ename, int id_)
552 {
553 return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
554 }
555
556 private:
557 /// an exception object as storage for error messages
558 std::runtime_error m;
559 };
560
561 /*!
562 @brief exception indicating a parse error
563
564 This exception is thrown by the library when a parse error occurs. Parse errors
565 can occur during the deserialization of JSON text, CBOR, MessagePack, as well
566 as when using JSON Patch.
567
568 Member @a byte holds the byte index of the last read character in the input
569 file.
570
571 Exceptions have ids 1xx.
572
573 name / id | example message | description
574 ------------------------------ | --------------- | -------------------------
575 json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position.
576 json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
577 json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
578 json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects.
579 json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors.
580 json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`.
581 json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character.
582 json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences.
583 json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
584 json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
585 json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.
586 json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read.
587
588 @note For an input with n bytes, 1 is the index of the first character and n+1
589 is the index of the terminating null byte or the end of file. This also
590 holds true when reading a byte vector (CBOR or MessagePack).
591
592 @liveexample{The following code shows how a `parse_error` exception can be
593 caught.,parse_error}
594
595 @sa @ref exception for the base class of the library exceptions
596 @sa @ref invalid_iterator for exceptions indicating errors with iterators
597 @sa @ref type_error for exceptions indicating executing a member function with
598 a wrong type
599 @sa @ref out_of_range for exceptions indicating access out of the defined range
600 @sa @ref other_error for exceptions indicating other library errors
601
602 @since version 3.0.0
603 */
604 class parse_error : public exception
605 {
606 public:
607 /*!
608 @brief create a parse error exception
609 @param[in] id_ the id of the exception
610 @param[in] byte_ the byte index where the error occurred (or 0 if the
611 position cannot be determined)
612 @param[in] what_arg the explanatory string
613 @return parse_error object
614 */
create(int id_,std::size_t byte_,const std::string & what_arg)615 static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
616 {
617 std::string w = exception::name("parse_error", id_) + "parse error" +
618 (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") +
619 ": " + what_arg;
620 return parse_error(id_, byte_, w.c_str());
621 }
622
623 /*!
624 @brief byte index of the parse error
625
626 The byte index of the last read character in the input file.
627
628 @note For an input with n bytes, 1 is the index of the first character and
629 n+1 is the index of the terminating null byte or the end of file.
630 This also holds true when reading a byte vector (CBOR or MessagePack).
631 */
632 const std::size_t byte;
633
634 private:
parse_error(int id_,std::size_t byte_,const char * what_arg)635 parse_error(int id_, std::size_t byte_, const char* what_arg)
636 : exception(id_, what_arg), byte(byte_) {}
637 };
638
639 /*!
640 @brief exception indicating errors with iterators
641
642 This exception is thrown if iterators passed to a library function do not match
643 the expected semantics.
644
645 Exceptions have ids 2xx.
646
647 name / id | example message | description
648 ----------------------------------- | --------------- | -------------------------
649 json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
650 json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
651 json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
652 json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid.
653 json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.
654 json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.
655 json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
656 json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
657 json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
658 json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
659 json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to.
660 json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
661 json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
662 json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin().
663
664 @liveexample{The following code shows how an `invalid_iterator` exception can be
665 caught.,invalid_iterator}
666
667 @sa @ref exception for the base class of the library exceptions
668 @sa @ref parse_error for exceptions indicating a parse error
669 @sa @ref type_error for exceptions indicating executing a member function with
670 a wrong type
671 @sa @ref out_of_range for exceptions indicating access out of the defined range
672 @sa @ref other_error for exceptions indicating other library errors
673
674 @since version 3.0.0
675 */
676 class invalid_iterator : public exception
677 {
678 public:
create(int id_,const std::string & what_arg)679 static invalid_iterator create(int id_, const std::string& what_arg)
680 {
681 std::string w = exception::name("invalid_iterator", id_) + what_arg;
682 return invalid_iterator(id_, w.c_str());
683 }
684
685 private:
invalid_iterator(int id_,const char * what_arg)686 invalid_iterator(int id_, const char* what_arg)
687 : exception(id_, what_arg) {}
688 };
689
690 /*!
691 @brief exception indicating executing a member function with a wrong type
692
693 This exception is thrown in case of a type error; that is, a library function is
694 executed on a JSON value whose type does not match the expected semantics.
695
696 Exceptions have ids 3xx.
697
698 name / id | example message | description
699 ----------------------------- | --------------- | -------------------------
700 json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
701 json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
702 json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&.
703 json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
704 json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
705 json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
706 json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
707 json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types.
708 json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
709 json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
710 json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types.
711 json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
712 json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined.
713 json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
714 json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive.
715 json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. |
716
717 @liveexample{The following code shows how a `type_error` exception can be
718 caught.,type_error}
719
720 @sa @ref exception for the base class of the library exceptions
721 @sa @ref parse_error for exceptions indicating a parse error
722 @sa @ref invalid_iterator for exceptions indicating errors with iterators
723 @sa @ref out_of_range for exceptions indicating access out of the defined range
724 @sa @ref other_error for exceptions indicating other library errors
725
726 @since version 3.0.0
727 */
728 class type_error : public exception
729 {
730 public:
create(int id_,const std::string & what_arg)731 static type_error create(int id_, const std::string& what_arg)
732 {
733 std::string w = exception::name("type_error", id_) + what_arg;
734 return type_error(id_, w.c_str());
735 }
736
737 private:
type_error(int id_,const char * what_arg)738 type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
739 };
740
741 /*!
742 @brief exception indicating access out of the defined range
743
744 This exception is thrown in case a library function is called on an input
745 parameter that exceeds the expected range, for instance in case of array
746 indices or nonexisting object keys.
747
748 Exceptions have ids 4xx.
749
750 name / id | example message | description
751 ------------------------------- | --------------- | -------------------------
752 json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1.
753 json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
754 json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
755 json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
756 json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
757 json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF.
758 json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON only supports integers numbers up to 9223372036854775807. |
759 json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
760
761 @liveexample{The following code shows how an `out_of_range` exception can be
762 caught.,out_of_range}
763
764 @sa @ref exception for the base class of the library exceptions
765 @sa @ref parse_error for exceptions indicating a parse error
766 @sa @ref invalid_iterator for exceptions indicating errors with iterators
767 @sa @ref type_error for exceptions indicating executing a member function with
768 a wrong type
769 @sa @ref other_error for exceptions indicating other library errors
770
771 @since version 3.0.0
772 */
773 class out_of_range : public exception
774 {
775 public:
create(int id_,const std::string & what_arg)776 static out_of_range create(int id_, const std::string& what_arg)
777 {
778 std::string w = exception::name("out_of_range", id_) + what_arg;
779 return out_of_range(id_, w.c_str());
780 }
781
782 private:
out_of_range(int id_,const char * what_arg)783 out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
784 };
785
786 /*!
787 @brief exception indicating other library errors
788
789 This exception is thrown in case of errors that cannot be classified with the
790 other exception types.
791
792 Exceptions have ids 5xx.
793
794 name / id | example message | description
795 ------------------------------ | --------------- | -------------------------
796 json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
797
798 @sa @ref exception for the base class of the library exceptions
799 @sa @ref parse_error for exceptions indicating a parse error
800 @sa @ref invalid_iterator for exceptions indicating errors with iterators
801 @sa @ref type_error for exceptions indicating executing a member function with
802 a wrong type
803 @sa @ref out_of_range for exceptions indicating access out of the defined range
804
805 @liveexample{The following code shows how an `other_error` exception can be
806 caught.,other_error}
807
808 @since version 3.0.0
809 */
810 class other_error : public exception
811 {
812 public:
create(int id_,const std::string & what_arg)813 static other_error create(int id_, const std::string& what_arg)
814 {
815 std::string w = exception::name("other_error", id_) + what_arg;
816 return other_error(id_, w.c_str());
817 }
818
819 private:
other_error(int id_,const char * what_arg)820 other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
821 };
822 }
823 }
824
825 // #include <nlohmann/detail/value_t.hpp>
826
827
828 #include <array> // array
829 #include <ciso646> // and
830 #include <cstddef> // size_t
831 #include <cstdint> // uint8_t
832
833 namespace nlohmann
834 {
835 namespace detail
836 {
837 ///////////////////////////
838 // JSON type enumeration //
839 ///////////////////////////
840
841 /*!
842 @brief the JSON type enumeration
843
844 This enumeration collects the different JSON types. It is internally used to
845 distinguish the stored values, and the functions @ref basic_json::is_null(),
846 @ref basic_json::is_object(), @ref basic_json::is_array(),
847 @ref basic_json::is_string(), @ref basic_json::is_boolean(),
848 @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
849 @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
850 @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
851 @ref basic_json::is_structured() rely on it.
852
853 @note There are three enumeration entries (number_integer, number_unsigned, and
854 number_float), because the library distinguishes these three types for numbers:
855 @ref basic_json::number_unsigned_t is used for unsigned integers,
856 @ref basic_json::number_integer_t is used for signed integers, and
857 @ref basic_json::number_float_t is used for floating-point numbers or to
858 approximate integers which do not fit in the limits of their respective type.
859
860 @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
861 value with the default value for a given type
862
863 @since version 1.0.0
864 */
865 enum class value_t : std::uint8_t
866 {
867 null, ///< null value
868 object, ///< object (unordered set of name/value pairs)
869 array, ///< array (ordered collection of values)
870 string, ///< string value
871 boolean, ///< boolean value
872 number_integer, ///< number value (signed integer)
873 number_unsigned, ///< number value (unsigned integer)
874 number_float, ///< number value (floating-point)
875 discarded ///< discarded by the the parser callback function
876 };
877
878 /*!
879 @brief comparison operator for JSON types
880
881 Returns an ordering that is similar to Python:
882 - order: null < boolean < number < object < array < string
883 - furthermore, each type is not smaller than itself
884 - discarded values are not comparable
885
886 @since version 1.0.0
887 */
operator <(const value_t lhs,const value_t rhs)888 inline bool operator<(const value_t lhs, const value_t rhs) noexcept
889 {
890 static constexpr std::array<std::uint8_t, 8> order = {{
891 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
892 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
893 }
894 };
895
896 const auto l_index = static_cast<std::size_t>(lhs);
897 const auto r_index = static_cast<std::size_t>(rhs);
898 return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
899 }
900 }
901 }
902
903 // #include <nlohmann/detail/conversions/from_json.hpp>
904
905
906 #include <algorithm> // transform
907 #include <array> // array
908 #include <ciso646> // and, not
909 #include <forward_list> // forward_list
910 #include <iterator> // inserter, front_inserter, end
911 #include <string> // string
912 #include <tuple> // tuple, make_tuple
913 #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
914 #include <utility> // pair, declval
915 #include <valarray> // valarray
916
917 // #include <nlohmann/detail/exceptions.hpp>
918
919 // #include <nlohmann/detail/macro_scope.hpp>
920
921 // #include <nlohmann/detail/meta.hpp>
922
923 // #include <nlohmann/detail/value_t.hpp>
924
925
926 namespace nlohmann
927 {
928 namespace detail
929 {
930 // overloads for basic_json template parameters
931 template<typename BasicJsonType, typename ArithmeticType,
932 enable_if_t<std::is_arithmetic<ArithmeticType>::value and
933 not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
934 int> = 0>
get_arithmetic_value(const BasicJsonType & j,ArithmeticType & val)935 void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
936 {
937 switch (static_cast<value_t>(j))
938 {
939 case value_t::number_unsigned:
940 {
941 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
942 break;
943 }
944 case value_t::number_integer:
945 {
946 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
947 break;
948 }
949 case value_t::number_float:
950 {
951 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
952 break;
953 }
954
955 default:
956 JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
957 }
958 }
959
960 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename BasicJsonType::boolean_t & b)961 void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
962 {
963 if (JSON_UNLIKELY(not j.is_boolean()))
964 {
965 JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
966 }
967 b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
968 }
969
970 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename BasicJsonType::string_t & s)971 void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
972 {
973 if (JSON_UNLIKELY(not j.is_string()))
974 {
975 JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
976 }
977 s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
978 }
979
980 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename BasicJsonType::number_float_t & val)981 void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
982 {
983 get_arithmetic_value(j, val);
984 }
985
986 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename BasicJsonType::number_unsigned_t & val)987 void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
988 {
989 get_arithmetic_value(j, val);
990 }
991
992 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename BasicJsonType::number_integer_t & val)993 void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
994 {
995 get_arithmetic_value(j, val);
996 }
997
998 template<typename BasicJsonType, typename EnumType,
999 enable_if_t<std::is_enum<EnumType>::value, int> = 0>
from_json(const BasicJsonType & j,EnumType & e)1000 void from_json(const BasicJsonType& j, EnumType& e)
1001 {
1002 typename std::underlying_type<EnumType>::type val;
1003 get_arithmetic_value(j, val);
1004 e = static_cast<EnumType>(val);
1005 }
1006
1007 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename BasicJsonType::array_t & arr)1008 void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
1009 {
1010 if (JSON_UNLIKELY(not j.is_array()))
1011 {
1012 JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1013 }
1014 arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
1015 }
1016
1017 // forward_list doesn't have an insert method
1018 template<typename BasicJsonType, typename T, typename Allocator,
1019 enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
from_json(const BasicJsonType & j,std::forward_list<T,Allocator> & l)1020 void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
1021 {
1022 if (JSON_UNLIKELY(not j.is_array()))
1023 {
1024 JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1025 }
1026 std::transform(j.rbegin(), j.rend(),
1027 std::front_inserter(l), [](const BasicJsonType & i)
1028 {
1029 return i.template get<T>();
1030 });
1031 }
1032
1033 // valarray doesn't have an insert method
1034 template<typename BasicJsonType, typename T,
1035 enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
from_json(const BasicJsonType & j,std::valarray<T> & l)1036 void from_json(const BasicJsonType& j, std::valarray<T>& l)
1037 {
1038 if (JSON_UNLIKELY(not j.is_array()))
1039 {
1040 JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1041 }
1042 l.resize(j.size());
1043 std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
1044 }
1045
1046 template<typename BasicJsonType, typename CompatibleArrayType>
from_json_array_impl(const BasicJsonType & j,CompatibleArrayType & arr,priority_tag<0>)1047 void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/)
1048 {
1049 using std::end;
1050
1051 std::transform(j.begin(), j.end(),
1052 std::inserter(arr, end(arr)), [](const BasicJsonType & i)
1053 {
1054 // get<BasicJsonType>() returns *this, this won't call a from_json
1055 // method when value_type is BasicJsonType
1056 return i.template get<typename CompatibleArrayType::value_type>();
1057 });
1058 }
1059
1060 template<typename BasicJsonType, typename CompatibleArrayType>
from_json_array_impl(const BasicJsonType & j,CompatibleArrayType & arr,priority_tag<1>)1061 auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/)
1062 -> decltype(
1063 arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
1064 void())
1065 {
1066 using std::end;
1067
1068 arr.reserve(j.size());
1069 std::transform(j.begin(), j.end(),
1070 std::inserter(arr, end(arr)), [](const BasicJsonType & i)
1071 {
1072 // get<BasicJsonType>() returns *this, this won't call a from_json
1073 // method when value_type is BasicJsonType
1074 return i.template get<typename CompatibleArrayType::value_type>();
1075 });
1076 }
1077
1078 template<typename BasicJsonType, typename T, std::size_t N>
from_json_array_impl(const BasicJsonType & j,std::array<T,N> & arr,priority_tag<2>)1079 void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/)
1080 {
1081 for (std::size_t i = 0; i < N; ++i)
1082 {
1083 arr[i] = j.at(i).template get<T>();
1084 }
1085 }
1086
1087 template <
1088 typename BasicJsonType, typename CompatibleArrayType,
1089 enable_if_t <
1090 is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
1091 not std::is_same<typename BasicJsonType::array_t,
1092 CompatibleArrayType>::value and
1093 std::is_constructible <
1094 BasicJsonType, typename CompatibleArrayType::value_type >::value,
1095 int > = 0 >
from_json(const BasicJsonType & j,CompatibleArrayType & arr)1096 void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
1097 {
1098 if (JSON_UNLIKELY(not j.is_array()))
1099 {
1100 JSON_THROW(type_error::create(302, "type must be array, but is " +
1101 std::string(j.type_name())));
1102 }
1103
1104 from_json_array_impl(j, arr, priority_tag<2> {});
1105 }
1106
1107 template<typename BasicJsonType, typename CompatibleObjectType,
1108 enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
from_json(const BasicJsonType & j,CompatibleObjectType & obj)1109 void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
1110 {
1111 if (JSON_UNLIKELY(not j.is_object()))
1112 {
1113 JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
1114 }
1115
1116 auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
1117 using value_type = typename CompatibleObjectType::value_type;
1118 std::transform(
1119 inner_object->begin(), inner_object->end(),
1120 std::inserter(obj, obj.begin()),
1121 [](typename BasicJsonType::object_t::value_type const & p)
1122 {
1123 return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>());
1124 });
1125 }
1126
1127 // overload for arithmetic types, not chosen for basic_json template arguments
1128 // (BooleanType, etc..); note: Is it really necessary to provide explicit
1129 // overloads for boolean_t etc. in case of a custom BooleanType which is not
1130 // an arithmetic type?
1131 template<typename BasicJsonType, typename ArithmeticType,
1132 enable_if_t <
1133 std::is_arithmetic<ArithmeticType>::value and
1134 not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
1135 not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
1136 not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
1137 not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
1138 int> = 0>
from_json(const BasicJsonType & j,ArithmeticType & val)1139 void from_json(const BasicJsonType& j, ArithmeticType& val)
1140 {
1141 switch (static_cast<value_t>(j))
1142 {
1143 case value_t::number_unsigned:
1144 {
1145 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
1146 break;
1147 }
1148 case value_t::number_integer:
1149 {
1150 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
1151 break;
1152 }
1153 case value_t::number_float:
1154 {
1155 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
1156 break;
1157 }
1158 case value_t::boolean:
1159 {
1160 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
1161 break;
1162 }
1163
1164 default:
1165 JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
1166 }
1167 }
1168
1169 template<typename BasicJsonType, typename A1, typename A2>
from_json(const BasicJsonType & j,std::pair<A1,A2> & p)1170 void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
1171 {
1172 p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
1173 }
1174
1175 template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
from_json_tuple_impl(const BasicJsonType & j,Tuple & t,index_sequence<Idx...>)1176 void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>)
1177 {
1178 t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
1179 }
1180
1181 template<typename BasicJsonType, typename... Args>
from_json(const BasicJsonType & j,std::tuple<Args...> & t)1182 void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
1183 {
1184 from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
1185 }
1186
1187 struct from_json_fn
1188 {
1189 private:
1190 template<typename BasicJsonType, typename T>
callnlohmann::detail::from_json_fn1191 auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const
1192 noexcept(noexcept(from_json(j, val)))
1193 -> decltype(from_json(j, val), void())
1194 {
1195 return from_json(j, val);
1196 }
1197
1198 template<typename BasicJsonType, typename T>
callnlohmann::detail::from_json_fn1199 void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept
1200 {
1201 static_assert(sizeof(BasicJsonType) == 0,
1202 "could not find from_json() method in T's namespace");
1203 #ifdef _MSC_VER
1204 // MSVC does not show a stacktrace for the above assert
1205 using decayed = uncvref_t<T>;
1206 static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
1207 "forcing MSVC stacktrace to show which T we're talking about.");
1208 #endif
1209 }
1210
1211 public:
1212 template<typename BasicJsonType, typename T>
operator ()nlohmann::detail::from_json_fn1213 void operator()(const BasicJsonType& j, T& val) const
1214 noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
1215 {
1216 return call(j, val, priority_tag<1> {});
1217 }
1218 };
1219 }
1220
1221 /// namespace to hold default `from_json` function
1222 /// to see why this is required:
1223 /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
1224 namespace
1225 {
1226 constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
1227 }
1228 }
1229
1230 // #include <nlohmann/detail/conversions/to_json.hpp>
1231
1232
1233 #include <ciso646> // or, and, not
1234 #include <iterator> // begin, end
1235 #include <tuple> // tuple, get
1236 #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
1237 #include <utility> // move, forward, declval, pair
1238 #include <valarray> // valarray
1239 #include <vector> // vector
1240
1241 // #include <nlohmann/detail/meta.hpp>
1242
1243 // #include <nlohmann/detail/value_t.hpp>
1244
1245
1246 namespace nlohmann
1247 {
1248 namespace detail
1249 {
1250 //////////////////
1251 // constructors //
1252 //////////////////
1253
1254 template<value_t> struct external_constructor;
1255
1256 template<>
1257 struct external_constructor<value_t::boolean>
1258 {
1259 template<typename BasicJsonType>
constructnlohmann::detail::external_constructor1260 static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
1261 {
1262 j.m_type = value_t::boolean;
1263 j.m_value = b;
1264 j.assert_invariant();
1265 }
1266 };
1267
1268 template<>
1269 struct external_constructor<value_t::string>
1270 {
1271 template<typename BasicJsonType>
constructnlohmann::detail::external_constructor1272 static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
1273 {
1274 j.m_type = value_t::string;
1275 j.m_value = s;
1276 j.assert_invariant();
1277 }
1278
1279 template<typename BasicJsonType>
constructnlohmann::detail::external_constructor1280 static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
1281 {
1282 j.m_type = value_t::string;
1283 j.m_value = std::move(s);
1284 j.assert_invariant();
1285 }
1286 };
1287
1288 template<>
1289 struct external_constructor<value_t::number_float>
1290 {
1291 template<typename BasicJsonType>
constructnlohmann::detail::external_constructor1292 static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
1293 {
1294 j.m_type = value_t::number_float;
1295 j.m_value = val;
1296 j.assert_invariant();
1297 }
1298 };
1299
1300 template<>
1301 struct external_constructor<value_t::number_unsigned>
1302 {
1303 template<typename BasicJsonType>
constructnlohmann::detail::external_constructor1304 static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
1305 {
1306 j.m_type = value_t::number_unsigned;
1307 j.m_value = val;
1308 j.assert_invariant();
1309 }
1310 };
1311
1312 template<>
1313 struct external_constructor<value_t::number_integer>
1314 {
1315 template<typename BasicJsonType>
constructnlohmann::detail::external_constructor1316 static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
1317 {
1318 j.m_type = value_t::number_integer;
1319 j.m_value = val;
1320 j.assert_invariant();
1321 }
1322 };
1323
1324 template<>
1325 struct external_constructor<value_t::array>
1326 {
1327 template<typename BasicJsonType>
constructnlohmann::detail::external_constructor1328 static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
1329 {
1330 j.m_type = value_t::array;
1331 j.m_value = arr;
1332 j.assert_invariant();
1333 }
1334
1335 template<typename BasicJsonType>
constructnlohmann::detail::external_constructor1336 static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
1337 {
1338 j.m_type = value_t::array;
1339 j.m_value = std::move(arr);
1340 j.assert_invariant();
1341 }
1342
1343 template<typename BasicJsonType, typename CompatibleArrayType,
1344 enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
1345 int> = 0>
constructnlohmann::detail::external_constructor1346 static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
1347 {
1348 using std::begin;
1349 using std::end;
1350 j.m_type = value_t::array;
1351 j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
1352 j.assert_invariant();
1353 }
1354
1355 template<typename BasicJsonType>
constructnlohmann::detail::external_constructor1356 static void construct(BasicJsonType& j, const std::vector<bool>& arr)
1357 {
1358 j.m_type = value_t::array;
1359 j.m_value = value_t::array;
1360 j.m_value.array->reserve(arr.size());
1361 for (const bool x : arr)
1362 {
1363 j.m_value.array->push_back(x);
1364 }
1365 j.assert_invariant();
1366 }
1367
1368 template<typename BasicJsonType, typename T,
1369 enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
constructnlohmann::detail::external_constructor1370 static void construct(BasicJsonType& j, const std::valarray<T>& arr)
1371 {
1372 j.m_type = value_t::array;
1373 j.m_value = value_t::array;
1374 j.m_value.array->resize(arr.size());
1375 std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
1376 j.assert_invariant();
1377 }
1378 };
1379
1380 template<>
1381 struct external_constructor<value_t::object>
1382 {
1383 template<typename BasicJsonType>
constructnlohmann::detail::external_constructor1384 static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
1385 {
1386 j.m_type = value_t::object;
1387 j.m_value = obj;
1388 j.assert_invariant();
1389 }
1390
1391 template<typename BasicJsonType>
constructnlohmann::detail::external_constructor1392 static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
1393 {
1394 j.m_type = value_t::object;
1395 j.m_value = std::move(obj);
1396 j.assert_invariant();
1397 }
1398
1399 template<typename BasicJsonType, typename CompatibleObjectType,
1400 enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
constructnlohmann::detail::external_constructor1401 static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
1402 {
1403 using std::begin;
1404 using std::end;
1405
1406 j.m_type = value_t::object;
1407 j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
1408 j.assert_invariant();
1409 }
1410 };
1411
1412 /////////////
1413 // to_json //
1414 /////////////
1415
1416 template<typename BasicJsonType, typename T,
1417 enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
to_json(BasicJsonType & j,T b)1418 void to_json(BasicJsonType& j, T b) noexcept
1419 {
1420 external_constructor<value_t::boolean>::construct(j, b);
1421 }
1422
1423 template<typename BasicJsonType, typename CompatibleString,
1424 enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
to_json(BasicJsonType & j,const CompatibleString & s)1425 void to_json(BasicJsonType& j, const CompatibleString& s)
1426 {
1427 external_constructor<value_t::string>::construct(j, s);
1428 }
1429
1430 template<typename BasicJsonType>
to_json(BasicJsonType & j,typename BasicJsonType::string_t && s)1431 void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
1432 {
1433 external_constructor<value_t::string>::construct(j, std::move(s));
1434 }
1435
1436 template<typename BasicJsonType, typename FloatType,
1437 enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
to_json(BasicJsonType & j,FloatType val)1438 void to_json(BasicJsonType& j, FloatType val) noexcept
1439 {
1440 external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
1441 }
1442
1443 template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
1444 enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
to_json(BasicJsonType & j,CompatibleNumberUnsignedType val)1445 void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
1446 {
1447 external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
1448 }
1449
1450 template<typename BasicJsonType, typename CompatibleNumberIntegerType,
1451 enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
to_json(BasicJsonType & j,CompatibleNumberIntegerType val)1452 void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
1453 {
1454 external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
1455 }
1456
1457 template<typename BasicJsonType, typename EnumType,
1458 enable_if_t<std::is_enum<EnumType>::value, int> = 0>
to_json(BasicJsonType & j,EnumType e)1459 void to_json(BasicJsonType& j, EnumType e) noexcept
1460 {
1461 using underlying_type = typename std::underlying_type<EnumType>::type;
1462 external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
1463 }
1464
1465 template<typename BasicJsonType>
to_json(BasicJsonType & j,const std::vector<bool> & e)1466 void to_json(BasicJsonType& j, const std::vector<bool>& e)
1467 {
1468 external_constructor<value_t::array>::construct(j, e);
1469 }
1470
1471 template<typename BasicJsonType, typename CompatibleArrayType,
1472 enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
1473 std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
1474 int> = 0>
to_json(BasicJsonType & j,const CompatibleArrayType & arr)1475 void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
1476 {
1477 external_constructor<value_t::array>::construct(j, arr);
1478 }
1479
1480 template<typename BasicJsonType, typename T,
1481 enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
to_json(BasicJsonType & j,std::valarray<T> arr)1482 void to_json(BasicJsonType& j, std::valarray<T> arr)
1483 {
1484 external_constructor<value_t::array>::construct(j, std::move(arr));
1485 }
1486
1487 template<typename BasicJsonType>
to_json(BasicJsonType & j,typename BasicJsonType::array_t && arr)1488 void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
1489 {
1490 external_constructor<value_t::array>::construct(j, std::move(arr));
1491 }
1492
1493 template<typename BasicJsonType, typename CompatibleObjectType,
1494 enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
to_json(BasicJsonType & j,const CompatibleObjectType & obj)1495 void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
1496 {
1497 external_constructor<value_t::object>::construct(j, obj);
1498 }
1499
1500 template<typename BasicJsonType>
to_json(BasicJsonType & j,typename BasicJsonType::object_t && obj)1501 void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
1502 {
1503 external_constructor<value_t::object>::construct(j, std::move(obj));
1504 }
1505
1506 template<typename BasicJsonType, typename T, std::size_t N,
1507 enable_if_t<not std::is_constructible<typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0>
to_json(BasicJsonType & j,T (& arr)[N])1508 void to_json(BasicJsonType& j, T (&arr)[N])
1509 {
1510 external_constructor<value_t::array>::construct(j, arr);
1511 }
1512
1513 template<typename BasicJsonType, typename... Args>
to_json(BasicJsonType & j,const std::pair<Args...> & p)1514 void to_json(BasicJsonType& j, const std::pair<Args...>& p)
1515 {
1516 j = {p.first, p.second};
1517 }
1518
1519 template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
to_json_tuple_impl(BasicJsonType & j,const Tuple & t,index_sequence<Idx...>)1520 void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>)
1521 {
1522 j = {std::get<Idx>(t)...};
1523 }
1524
1525 template<typename BasicJsonType, typename... Args>
to_json(BasicJsonType & j,const std::tuple<Args...> & t)1526 void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
1527 {
1528 to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
1529 }
1530
1531 struct to_json_fn
1532 {
1533 private:
1534 template<typename BasicJsonType, typename T>
callnlohmann::detail::to_json_fn1535 auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
1536 -> decltype(to_json(j, std::forward<T>(val)), void())
1537 {
1538 return to_json(j, std::forward<T>(val));
1539 }
1540
1541 template<typename BasicJsonType, typename T>
callnlohmann::detail::to_json_fn1542 void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept
1543 {
1544 static_assert(sizeof(BasicJsonType) == 0,
1545 "could not find to_json() method in T's namespace");
1546
1547 #ifdef _MSC_VER
1548 // MSVC does not show a stacktrace for the above assert
1549 using decayed = uncvref_t<T>;
1550 static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
1551 "forcing MSVC stacktrace to show which T we're talking about.");
1552 #endif
1553 }
1554
1555 public:
1556 template<typename BasicJsonType, typename T>
operator ()nlohmann::detail::to_json_fn1557 void operator()(BasicJsonType& j, T&& val) const
1558 noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
1559 {
1560 return call(j, std::forward<T>(val), priority_tag<1> {});
1561 }
1562 };
1563 }
1564
1565 /// namespace to hold default `to_json` function
1566 namespace
1567 {
1568 constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
1569 }
1570 }
1571
1572 // #include <nlohmann/detail/input/input_adapters.hpp>
1573
1574
1575 #include <algorithm> // min
1576 #include <array> // array
1577 #include <cassert> // assert
1578 #include <cstddef> // size_t
1579 #include <cstring> // strlen
1580 #include <ios> // streamsize, streamoff, streampos
1581 #include <istream> // istream
1582 #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
1583 #include <memory> // shared_ptr, make_shared, addressof
1584 #include <numeric> // accumulate
1585 #include <string> // string, char_traits
1586 #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
1587 #include <utility> // pair, declval
1588
1589 // #include <nlohmann/detail/macro_scope.hpp>
1590
1591
1592 namespace nlohmann
1593 {
1594 namespace detail
1595 {
1596 ////////////////////
1597 // input adapters //
1598 ////////////////////
1599
1600 /*!
1601 @brief abstract input adapter interface
1602
1603 Produces a stream of std::char_traits<char>::int_type characters from a
1604 std::istream, a buffer, or some other input type. Accepts the return of exactly
1605 one non-EOF character for future input. The int_type characters returned
1606 consist of all valid char values as positive values (typically unsigned char),
1607 plus an EOF value outside that range, specified by the value of the function
1608 std::char_traits<char>::eof(). This value is typically -1, but could be any
1609 arbitrary value which is not a valid char value.
1610 */
1611 struct input_adapter_protocol
1612 {
1613 /// get a character [0,255] or std::char_traits<char>::eof().
1614 virtual std::char_traits<char>::int_type get_character() = 0;
1615 /// restore the last non-eof() character to input
1616 virtual void unget_character() = 0;
1617 virtual ~input_adapter_protocol() = default;
1618 };
1619
1620 /// a type to simplify interfaces
1621 using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
1622
1623 /*!
1624 Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
1625 beginning of input. Does not support changing the underlying std::streambuf
1626 in mid-input. Maintains underlying std::istream and std::streambuf to support
1627 subsequent use of standard std::istream operations to process any input
1628 characters following those used in parsing the JSON input. Clears the
1629 std::istream flags; any input errors (e.g., EOF) will be detected by the first
1630 subsequent call for input from the std::istream.
1631 */
1632 class input_stream_adapter : public input_adapter_protocol
1633 {
1634 public:
~input_stream_adapter()1635 ~input_stream_adapter() override
1636 {
1637 // clear stream flags; we use underlying streambuf I/O, do not
1638 // maintain ifstream flags
1639 is.clear();
1640 }
1641
input_stream_adapter(std::istream & i)1642 explicit input_stream_adapter(std::istream& i)
1643 : is(i), sb(*i.rdbuf())
1644 {
1645 // skip byte order mark
1646 std::char_traits<char>::int_type c;
1647 if ((c = get_character()) == 0xEF)
1648 {
1649 if ((c = get_character()) == 0xBB)
1650 {
1651 if ((c = get_character()) == 0xBF)
1652 {
1653 return; // Ignore BOM
1654 }
1655 else if (c != std::char_traits<char>::eof())
1656 {
1657 is.unget();
1658 }
1659 is.putback('\xBB');
1660 }
1661 else if (c != std::char_traits<char>::eof())
1662 {
1663 is.unget();
1664 }
1665 is.putback('\xEF');
1666 }
1667 else if (c != std::char_traits<char>::eof())
1668 {
1669 is.unget(); // no byte order mark; process as usual
1670 }
1671 }
1672
1673 // delete because of pointer members
1674 input_stream_adapter(const input_stream_adapter&) = delete;
1675 input_stream_adapter& operator=(input_stream_adapter&) = delete;
1676
1677 // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
1678 // ensure that std::char_traits<char>::eof() and the character 0xFF do not
1679 // end up as the same value, eg. 0xFFFFFFFF.
get_character()1680 std::char_traits<char>::int_type get_character() override
1681 {
1682 return sb.sbumpc();
1683 }
1684
unget_character()1685 void unget_character() override
1686 {
1687 sb.sungetc(); // is.unget() avoided for performance
1688 }
1689
1690 private:
1691 /// the associated input stream
1692 std::istream& is;
1693 std::streambuf& sb;
1694 };
1695
1696 /// input adapter for buffer input
1697 class input_buffer_adapter : public input_adapter_protocol
1698 {
1699 public:
input_buffer_adapter(const char * b,const std::size_t l)1700 input_buffer_adapter(const char* b, const std::size_t l)
1701 : cursor(b), limit(b + l), start(b)
1702 {
1703 // skip byte order mark
1704 if (l >= 3 and b[0] == '\xEF' and b[1] == '\xBB' and b[2] == '\xBF')
1705 {
1706 cursor += 3;
1707 }
1708 }
1709
1710 // delete because of pointer members
1711 input_buffer_adapter(const input_buffer_adapter&) = delete;
1712 input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
1713
get_character()1714 std::char_traits<char>::int_type get_character() noexcept override
1715 {
1716 if (JSON_LIKELY(cursor < limit))
1717 {
1718 return std::char_traits<char>::to_int_type(*(cursor++));
1719 }
1720
1721 return std::char_traits<char>::eof();
1722 }
1723
unget_character()1724 void unget_character() noexcept override
1725 {
1726 if (JSON_LIKELY(cursor > start))
1727 {
1728 --cursor;
1729 }
1730 }
1731
1732 private:
1733 /// pointer to the current character
1734 const char* cursor;
1735 /// pointer past the last character
1736 const char* limit;
1737 /// pointer to the first character
1738 const char* start;
1739 };
1740
1741 class input_adapter
1742 {
1743 public:
1744 // native support
1745
1746 /// input adapter for input stream
input_adapter(std::istream & i)1747 input_adapter(std::istream& i)
1748 : ia(std::make_shared<input_stream_adapter>(i)) {}
1749
1750 /// input adapter for input stream
input_adapter(std::istream && i)1751 input_adapter(std::istream&& i)
1752 : ia(std::make_shared<input_stream_adapter>(i)) {}
1753
1754 /// input adapter for buffer
1755 template<typename CharT,
1756 typename std::enable_if<
1757 std::is_pointer<CharT>::value and
1758 std::is_integral<typename std::remove_pointer<CharT>::type>::value and
1759 sizeof(typename std::remove_pointer<CharT>::type) == 1,
1760 int>::type = 0>
input_adapter(CharT b,std::size_t l)1761 input_adapter(CharT b, std::size_t l)
1762 : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
1763
1764 // derived support
1765
1766 /// input adapter for string literal
1767 template<typename CharT,
1768 typename std::enable_if<
1769 std::is_pointer<CharT>::value and
1770 std::is_integral<typename std::remove_pointer<CharT>::type>::value and
1771 sizeof(typename std::remove_pointer<CharT>::type) == 1,
1772 int>::type = 0>
input_adapter(CharT b)1773 input_adapter(CharT b)
1774 : input_adapter(reinterpret_cast<const char*>(b),
1775 std::strlen(reinterpret_cast<const char*>(b))) {}
1776
1777 /// input adapter for iterator range with contiguous storage
1778 template<class IteratorType,
1779 typename std::enable_if<
1780 std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
1781 int>::type = 0>
input_adapter(IteratorType first,IteratorType last)1782 input_adapter(IteratorType first, IteratorType last)
1783 {
1784 // assertion to check that the iterator range is indeed contiguous,
1785 // see http://stackoverflow.com/a/35008842/266378 for more discussion
1786 assert(std::accumulate(
1787 first, last, std::pair<bool, int>(true, 0),
1788 [&first](std::pair<bool, int> res, decltype(*first) val)
1789 {
1790 res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
1791 return res;
1792 }).first);
1793
1794 // assertion to check that each element is 1 byte long
1795 static_assert(
1796 sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
1797 "each element in the iterator range must have the size of 1 byte");
1798
1799 const auto len = static_cast<size_t>(std::distance(first, last));
1800 if (JSON_LIKELY(len > 0))
1801 {
1802 // there is at least one element: use the address of first
1803 ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
1804 }
1805 else
1806 {
1807 // the address of first cannot be used: use nullptr
1808 ia = std::make_shared<input_buffer_adapter>(nullptr, len);
1809 }
1810 }
1811
1812 /// input adapter for array
1813 template<class T, std::size_t N>
input_adapter(T (& array)[N])1814 input_adapter(T (&array)[N])
1815 : input_adapter(std::begin(array), std::end(array)) {}
1816
1817 /// input adapter for contiguous container
1818 template<class ContiguousContainer, typename
1819 std::enable_if<not std::is_pointer<ContiguousContainer>::value and
1820 std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
1821 int>::type = 0>
input_adapter(const ContiguousContainer & c)1822 input_adapter(const ContiguousContainer& c)
1823 : input_adapter(std::begin(c), std::end(c)) {}
1824
operator input_adapter_t()1825 operator input_adapter_t()
1826 {
1827 return ia;
1828 }
1829
1830 private:
1831 /// the actual adapter
1832 input_adapter_t ia = nullptr;
1833 };
1834 }
1835 }
1836
1837 // #include <nlohmann/detail/input/lexer.hpp>
1838
1839
1840 #include <clocale> // localeconv
1841 #include <cstddef> // size_t
1842 #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
1843 #include <initializer_list> // initializer_list
1844 #include <ios> // hex, uppercase
1845 #include <iomanip> // setw, setfill
1846 #include <sstream> // stringstream
1847 #include <string> // char_traits, string
1848 #include <vector> // vector
1849
1850 // #include <nlohmann/detail/macro_scope.hpp>
1851
1852 // #include <nlohmann/detail/input/input_adapters.hpp>
1853
1854
1855 namespace nlohmann
1856 {
1857 namespace detail
1858 {
1859 ///////////
1860 // lexer //
1861 ///////////
1862
1863 /*!
1864 @brief lexical analysis
1865
1866 This class organizes the lexical analysis during JSON deserialization.
1867 */
1868 template<typename BasicJsonType>
1869 class lexer
1870 {
1871 using number_integer_t = typename BasicJsonType::number_integer_t;
1872 using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
1873 using number_float_t = typename BasicJsonType::number_float_t;
1874
1875 public:
1876 /// token types for the parser
1877 enum class token_type
1878 {
1879 uninitialized, ///< indicating the scanner is uninitialized
1880 literal_true, ///< the `true` literal
1881 literal_false, ///< the `false` literal
1882 literal_null, ///< the `null` literal
1883 value_string, ///< a string -- use get_string() for actual value
1884 value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
1885 value_integer, ///< a signed integer -- use get_number_integer() for actual value
1886 value_float, ///< an floating point number -- use get_number_float() for actual value
1887 begin_array, ///< the character for array begin `[`
1888 begin_object, ///< the character for object begin `{`
1889 end_array, ///< the character for array end `]`
1890 end_object, ///< the character for object end `}`
1891 name_separator, ///< the name separator `:`
1892 value_separator, ///< the value separator `,`
1893 parse_error, ///< indicating a parse error
1894 end_of_input, ///< indicating the end of the input buffer
1895 literal_or_value ///< a literal or the begin of a value (only for diagnostics)
1896 };
1897
1898 /// return name of values of type token_type (only used for errors)
token_type_name(const token_type t)1899 static const char* token_type_name(const token_type t) noexcept
1900 {
1901 switch (t)
1902 {
1903 case token_type::uninitialized:
1904 return "<uninitialized>";
1905 case token_type::literal_true:
1906 return "true literal";
1907 case token_type::literal_false:
1908 return "false literal";
1909 case token_type::literal_null:
1910 return "null literal";
1911 case token_type::value_string:
1912 return "string literal";
1913 case lexer::token_type::value_unsigned:
1914 case lexer::token_type::value_integer:
1915 case lexer::token_type::value_float:
1916 return "number literal";
1917 case token_type::begin_array:
1918 return "'['";
1919 case token_type::begin_object:
1920 return "'{'";
1921 case token_type::end_array:
1922 return "']'";
1923 case token_type::end_object:
1924 return "'}'";
1925 case token_type::name_separator:
1926 return "':'";
1927 case token_type::value_separator:
1928 return "','";
1929 case token_type::parse_error:
1930 return "<parse error>";
1931 case token_type::end_of_input:
1932 return "end of input";
1933 case token_type::literal_or_value:
1934 return "'[', '{', or a literal";
1935 default: // catch non-enum values
1936 return "unknown token"; // LCOV_EXCL_LINE
1937 }
1938 }
1939
lexer(detail::input_adapter_t adapter)1940 explicit lexer(detail::input_adapter_t adapter)
1941 : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
1942
1943 // delete because of pointer members
1944 lexer(const lexer&) = delete;
1945 lexer& operator=(lexer&) = delete;
1946
1947 private:
1948 /////////////////////
1949 // locales
1950 /////////////////////
1951
1952 /// return the locale-dependent decimal point
get_decimal_point()1953 static char get_decimal_point() noexcept
1954 {
1955 const auto loc = localeconv();
1956 assert(loc != nullptr);
1957 return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
1958 }
1959
1960 /////////////////////
1961 // scan functions
1962 /////////////////////
1963
1964 /*!
1965 @brief get codepoint from 4 hex characters following `\u`
1966
1967 For input "\u c1 c2 c3 c4" the codepoint is:
1968 (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
1969 = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
1970
1971 Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
1972 must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
1973 conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
1974 between the ASCII value of the character and the desired integer value.
1975
1976 @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
1977 non-hex character)
1978 */
get_codepoint()1979 int get_codepoint()
1980 {
1981 // this function only makes sense after reading `\u`
1982 assert(current == 'u');
1983 int codepoint = 0;
1984
1985 const auto factors = { 12, 8, 4, 0 };
1986 for (const auto factor : factors)
1987 {
1988 get();
1989
1990 if (current >= '0' and current <= '9')
1991 {
1992 codepoint += ((current - 0x30) << factor);
1993 }
1994 else if (current >= 'A' and current <= 'F')
1995 {
1996 codepoint += ((current - 0x37) << factor);
1997 }
1998 else if (current >= 'a' and current <= 'f')
1999 {
2000 codepoint += ((current - 0x57) << factor);
2001 }
2002 else
2003 {
2004 return -1;
2005 }
2006 }
2007
2008 assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
2009 return codepoint;
2010 }
2011
2012 /*!
2013 @brief check if the next byte(s) are inside a given range
2014
2015 Adds the current byte and, for each passed range, reads a new byte and
2016 checks if it is inside the range. If a violation was detected, set up an
2017 error message and return false. Otherwise, return true.
2018
2019 @param[in] ranges list of integers; interpreted as list of pairs of
2020 inclusive lower and upper bound, respectively
2021
2022 @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
2023 1, 2, or 3 pairs. This precondition is enforced by an assertion.
2024
2025 @return true if and only if no range violation was detected
2026 */
next_byte_in_range(std::initializer_list<int> ranges)2027 bool next_byte_in_range(std::initializer_list<int> ranges)
2028 {
2029 assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
2030 add(current);
2031
2032 for (auto range = ranges.begin(); range != ranges.end(); ++range)
2033 {
2034 get();
2035 if (JSON_LIKELY(*range <= current and current <= *(++range)))
2036 {
2037 add(current);
2038 }
2039 else
2040 {
2041 error_message = "invalid string: ill-formed UTF-8 byte";
2042 return false;
2043 }
2044 }
2045
2046 return true;
2047 }
2048
2049 /*!
2050 @brief scan a string literal
2051
2052 This function scans a string according to Sect. 7 of RFC 7159. While
2053 scanning, bytes are escaped and copied into buffer token_buffer. Then the
2054 function returns successfully, token_buffer is *not* null-terminated (as it
2055 may contain \0 bytes), and token_buffer.size() is the number of bytes in the
2056 string.
2057
2058 @return token_type::value_string if string could be successfully scanned,
2059 token_type::parse_error otherwise
2060
2061 @note In case of errors, variable error_message contains a textual
2062 description.
2063 */
scan_string()2064 token_type scan_string()
2065 {
2066 // reset token_buffer (ignore opening quote)
2067 reset();
2068
2069 // we entered the function by reading an open quote
2070 assert(current == '\"');
2071
2072 while (true)
2073 {
2074 // get next character
2075 switch (get())
2076 {
2077 // end of file while parsing string
2078 case std::char_traits<char>::eof():
2079 {
2080 error_message = "invalid string: missing closing quote";
2081 return token_type::parse_error;
2082 }
2083
2084 // closing quote
2085 case '\"':
2086 {
2087 return token_type::value_string;
2088 }
2089
2090 // escapes
2091 case '\\':
2092 {
2093 switch (get())
2094 {
2095 // quotation mark
2096 case '\"':
2097 add('\"');
2098 break;
2099 // reverse solidus
2100 case '\\':
2101 add('\\');
2102 break;
2103 // solidus
2104 case '/':
2105 add('/');
2106 break;
2107 // backspace
2108 case 'b':
2109 add('\b');
2110 break;
2111 // form feed
2112 case 'f':
2113 add('\f');
2114 break;
2115 // line feed
2116 case 'n':
2117 add('\n');
2118 break;
2119 // carriage return
2120 case 'r':
2121 add('\r');
2122 break;
2123 // tab
2124 case 't':
2125 add('\t');
2126 break;
2127
2128 // unicode escapes
2129 case 'u':
2130 {
2131 const int codepoint1 = get_codepoint();
2132 int codepoint = codepoint1; // start with codepoint1
2133
2134 if (JSON_UNLIKELY(codepoint1 == -1))
2135 {
2136 error_message = "invalid string: '\\u' must be followed by 4 hex digits";
2137 return token_type::parse_error;
2138 }
2139
2140 // check if code point is a high surrogate
2141 if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
2142 {
2143 // expect next \uxxxx entry
2144 if (JSON_LIKELY(get() == '\\' and get() == 'u'))
2145 {
2146 const int codepoint2 = get_codepoint();
2147
2148 if (JSON_UNLIKELY(codepoint2 == -1))
2149 {
2150 error_message = "invalid string: '\\u' must be followed by 4 hex digits";
2151 return token_type::parse_error;
2152 }
2153
2154 // check if codepoint2 is a low surrogate
2155 if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
2156 {
2157 // overwrite codepoint
2158 codepoint =
2159 // high surrogate occupies the most significant 22 bits
2160 (codepoint1 << 10)
2161 // low surrogate occupies the least significant 15 bits
2162 + codepoint2
2163 // there is still the 0xD800, 0xDC00 and 0x10000 noise
2164 // in the result so we have to subtract with:
2165 // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
2166 - 0x35FDC00;
2167 }
2168 else
2169 {
2170 error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
2171 return token_type::parse_error;
2172 }
2173 }
2174 else
2175 {
2176 error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
2177 return token_type::parse_error;
2178 }
2179 }
2180 else
2181 {
2182 if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
2183 {
2184 error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
2185 return token_type::parse_error;
2186 }
2187 }
2188
2189 // result of the above calculation yields a proper codepoint
2190 assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
2191
2192 // translate codepoint into bytes
2193 if (codepoint < 0x80)
2194 {
2195 // 1-byte characters: 0xxxxxxx (ASCII)
2196 add(codepoint);
2197 }
2198 else if (codepoint <= 0x7FF)
2199 {
2200 // 2-byte characters: 110xxxxx 10xxxxxx
2201 add(0xC0 | (codepoint >> 6));
2202 add(0x80 | (codepoint & 0x3F));
2203 }
2204 else if (codepoint <= 0xFFFF)
2205 {
2206 // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
2207 add(0xE0 | (codepoint >> 12));
2208 add(0x80 | ((codepoint >> 6) & 0x3F));
2209 add(0x80 | (codepoint & 0x3F));
2210 }
2211 else
2212 {
2213 // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2214 add(0xF0 | (codepoint >> 18));
2215 add(0x80 | ((codepoint >> 12) & 0x3F));
2216 add(0x80 | ((codepoint >> 6) & 0x3F));
2217 add(0x80 | (codepoint & 0x3F));
2218 }
2219
2220 break;
2221 }
2222
2223 // other characters after escape
2224 default:
2225 error_message = "invalid string: forbidden character after backslash";
2226 return token_type::parse_error;
2227 }
2228
2229 break;
2230 }
2231
2232 // invalid control characters
2233 case 0x00:
2234 case 0x01:
2235 case 0x02:
2236 case 0x03:
2237 case 0x04:
2238 case 0x05:
2239 case 0x06:
2240 case 0x07:
2241 case 0x08:
2242 case 0x09:
2243 case 0x0A:
2244 case 0x0B:
2245 case 0x0C:
2246 case 0x0D:
2247 case 0x0E:
2248 case 0x0F:
2249 case 0x10:
2250 case 0x11:
2251 case 0x12:
2252 case 0x13:
2253 case 0x14:
2254 case 0x15:
2255 case 0x16:
2256 case 0x17:
2257 case 0x18:
2258 case 0x19:
2259 case 0x1A:
2260 case 0x1B:
2261 case 0x1C:
2262 case 0x1D:
2263 case 0x1E:
2264 case 0x1F:
2265 {
2266 error_message = "invalid string: control character must be escaped";
2267 return token_type::parse_error;
2268 }
2269
2270 // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
2271 case 0x20:
2272 case 0x21:
2273 case 0x23:
2274 case 0x24:
2275 case 0x25:
2276 case 0x26:
2277 case 0x27:
2278 case 0x28:
2279 case 0x29:
2280 case 0x2A:
2281 case 0x2B:
2282 case 0x2C:
2283 case 0x2D:
2284 case 0x2E:
2285 case 0x2F:
2286 case 0x30:
2287 case 0x31:
2288 case 0x32:
2289 case 0x33:
2290 case 0x34:
2291 case 0x35:
2292 case 0x36:
2293 case 0x37:
2294 case 0x38:
2295 case 0x39:
2296 case 0x3A:
2297 case 0x3B:
2298 case 0x3C:
2299 case 0x3D:
2300 case 0x3E:
2301 case 0x3F:
2302 case 0x40:
2303 case 0x41:
2304 case 0x42:
2305 case 0x43:
2306 case 0x44:
2307 case 0x45:
2308 case 0x46:
2309 case 0x47:
2310 case 0x48:
2311 case 0x49:
2312 case 0x4A:
2313 case 0x4B:
2314 case 0x4C:
2315 case 0x4D:
2316 case 0x4E:
2317 case 0x4F:
2318 case 0x50:
2319 case 0x51:
2320 case 0x52:
2321 case 0x53:
2322 case 0x54:
2323 case 0x55:
2324 case 0x56:
2325 case 0x57:
2326 case 0x58:
2327 case 0x59:
2328 case 0x5A:
2329 case 0x5B:
2330 case 0x5D:
2331 case 0x5E:
2332 case 0x5F:
2333 case 0x60:
2334 case 0x61:
2335 case 0x62:
2336 case 0x63:
2337 case 0x64:
2338 case 0x65:
2339 case 0x66:
2340 case 0x67:
2341 case 0x68:
2342 case 0x69:
2343 case 0x6A:
2344 case 0x6B:
2345 case 0x6C:
2346 case 0x6D:
2347 case 0x6E:
2348 case 0x6F:
2349 case 0x70:
2350 case 0x71:
2351 case 0x72:
2352 case 0x73:
2353 case 0x74:
2354 case 0x75:
2355 case 0x76:
2356 case 0x77:
2357 case 0x78:
2358 case 0x79:
2359 case 0x7A:
2360 case 0x7B:
2361 case 0x7C:
2362 case 0x7D:
2363 case 0x7E:
2364 case 0x7F:
2365 {
2366 add(current);
2367 break;
2368 }
2369
2370 // U+0080..U+07FF: bytes C2..DF 80..BF
2371 case 0xC2:
2372 case 0xC3:
2373 case 0xC4:
2374 case 0xC5:
2375 case 0xC6:
2376 case 0xC7:
2377 case 0xC8:
2378 case 0xC9:
2379 case 0xCA:
2380 case 0xCB:
2381 case 0xCC:
2382 case 0xCD:
2383 case 0xCE:
2384 case 0xCF:
2385 case 0xD0:
2386 case 0xD1:
2387 case 0xD2:
2388 case 0xD3:
2389 case 0xD4:
2390 case 0xD5:
2391 case 0xD6:
2392 case 0xD7:
2393 case 0xD8:
2394 case 0xD9:
2395 case 0xDA:
2396 case 0xDB:
2397 case 0xDC:
2398 case 0xDD:
2399 case 0xDE:
2400 case 0xDF:
2401 {
2402 if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
2403 {
2404 return token_type::parse_error;
2405 }
2406 break;
2407 }
2408
2409 // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
2410 case 0xE0:
2411 {
2412 if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
2413 {
2414 return token_type::parse_error;
2415 }
2416 break;
2417 }
2418
2419 // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
2420 // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
2421 case 0xE1:
2422 case 0xE2:
2423 case 0xE3:
2424 case 0xE4:
2425 case 0xE5:
2426 case 0xE6:
2427 case 0xE7:
2428 case 0xE8:
2429 case 0xE9:
2430 case 0xEA:
2431 case 0xEB:
2432 case 0xEC:
2433 case 0xEE:
2434 case 0xEF:
2435 {
2436 if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
2437 {
2438 return token_type::parse_error;
2439 }
2440 break;
2441 }
2442
2443 // U+D000..U+D7FF: bytes ED 80..9F 80..BF
2444 case 0xED:
2445 {
2446 if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
2447 {
2448 return token_type::parse_error;
2449 }
2450 break;
2451 }
2452
2453 // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
2454 case 0xF0:
2455 {
2456 if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
2457 {
2458 return token_type::parse_error;
2459 }
2460 break;
2461 }
2462
2463 // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
2464 case 0xF1:
2465 case 0xF2:
2466 case 0xF3:
2467 {
2468 if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
2469 {
2470 return token_type::parse_error;
2471 }
2472 break;
2473 }
2474
2475 // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
2476 case 0xF4:
2477 {
2478 if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
2479 {
2480 return token_type::parse_error;
2481 }
2482 break;
2483 }
2484
2485 // remaining bytes (80..C1 and F5..FF) are ill-formed
2486 default:
2487 {
2488 error_message = "invalid string: ill-formed UTF-8 byte";
2489 return token_type::parse_error;
2490 }
2491 }
2492 }
2493 }
2494
strtof(float & f,const char * str,char ** endptr)2495 static void strtof(float& f, const char* str, char** endptr) noexcept
2496 {
2497 f = std::strtof(str, endptr);
2498 }
2499
strtof(double & f,const char * str,char ** endptr)2500 static void strtof(double& f, const char* str, char** endptr) noexcept
2501 {
2502 f = std::strtod(str, endptr);
2503 }
2504
strtof(long double & f,const char * str,char ** endptr)2505 static void strtof(long double& f, const char* str, char** endptr) noexcept
2506 {
2507 f = std::strtold(str, endptr);
2508 }
2509
2510 /*!
2511 @brief scan a number literal
2512
2513 This function scans a string according to Sect. 6 of RFC 7159.
2514
2515 The function is realized with a deterministic finite state machine derived
2516 from the grammar described in RFC 7159. Starting in state "init", the
2517 input is read and used to determined the next state. Only state "done"
2518 accepts the number. State "error" is a trap state to model errors. In the
2519 table below, "anything" means any character but the ones listed before.
2520
2521 state | 0 | 1-9 | e E | + | - | . | anything
2522 ---------|----------|----------|----------|---------|---------|----------|-----------
2523 init | zero | any1 | [error] | [error] | minus | [error] | [error]
2524 minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
2525 zero | done | done | exponent | done | done | decimal1 | done
2526 any1 | any1 | any1 | exponent | done | done | decimal1 | done
2527 decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
2528 decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
2529 exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
2530 sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
2531 any2 | any2 | any2 | done | done | done | done | done
2532
2533 The state machine is realized with one label per state (prefixed with
2534 "scan_number_") and `goto` statements between them. The state machine
2535 contains cycles, but any cycle can be left when EOF is read. Therefore,
2536 the function is guaranteed to terminate.
2537
2538 During scanning, the read bytes are stored in token_buffer. This string is
2539 then converted to a signed integer, an unsigned integer, or a
2540 floating-point number.
2541
2542 @return token_type::value_unsigned, token_type::value_integer, or
2543 token_type::value_float if number could be successfully scanned,
2544 token_type::parse_error otherwise
2545
2546 @note The scanner is independent of the current locale. Internally, the
2547 locale's decimal point is used instead of `.` to work with the
2548 locale-dependent converters.
2549 */
scan_number()2550 token_type scan_number()
2551 {
2552 // reset token_buffer to store the number's bytes
2553 reset();
2554
2555 // the type of the parsed number; initially set to unsigned; will be
2556 // changed if minus sign, decimal point or exponent is read
2557 token_type number_type = token_type::value_unsigned;
2558
2559 // state (init): we just found out we need to scan a number
2560 switch (current)
2561 {
2562 case '-':
2563 {
2564 add(current);
2565 goto scan_number_minus;
2566 }
2567
2568 case '0':
2569 {
2570 add(current);
2571 goto scan_number_zero;
2572 }
2573
2574 case '1':
2575 case '2':
2576 case '3':
2577 case '4':
2578 case '5':
2579 case '6':
2580 case '7':
2581 case '8':
2582 case '9':
2583 {
2584 add(current);
2585 goto scan_number_any1;
2586 }
2587
2588 default:
2589 {
2590 // all other characters are rejected outside scan_number()
2591 assert(false); // LCOV_EXCL_LINE
2592 }
2593 }
2594
2595 scan_number_minus:
2596 // state: we just parsed a leading minus sign
2597 number_type = token_type::value_integer;
2598 switch (get())
2599 {
2600 case '0':
2601 {
2602 add(current);
2603 goto scan_number_zero;
2604 }
2605
2606 case '1':
2607 case '2':
2608 case '3':
2609 case '4':
2610 case '5':
2611 case '6':
2612 case '7':
2613 case '8':
2614 case '9':
2615 {
2616 add(current);
2617 goto scan_number_any1;
2618 }
2619
2620 default:
2621 {
2622 error_message = "invalid number; expected digit after '-'";
2623 return token_type::parse_error;
2624 }
2625 }
2626
2627 scan_number_zero:
2628 // state: we just parse a zero (maybe with a leading minus sign)
2629 switch (get())
2630 {
2631 case '.':
2632 {
2633 add(decimal_point_char);
2634 goto scan_number_decimal1;
2635 }
2636
2637 case 'e':
2638 case 'E':
2639 {
2640 add(current);
2641 goto scan_number_exponent;
2642 }
2643
2644 default:
2645 goto scan_number_done;
2646 }
2647
2648 scan_number_any1:
2649 // state: we just parsed a number 0-9 (maybe with a leading minus sign)
2650 switch (get())
2651 {
2652 case '0':
2653 case '1':
2654 case '2':
2655 case '3':
2656 case '4':
2657 case '5':
2658 case '6':
2659 case '7':
2660 case '8':
2661 case '9':
2662 {
2663 add(current);
2664 goto scan_number_any1;
2665 }
2666
2667 case '.':
2668 {
2669 add(decimal_point_char);
2670 goto scan_number_decimal1;
2671 }
2672
2673 case 'e':
2674 case 'E':
2675 {
2676 add(current);
2677 goto scan_number_exponent;
2678 }
2679
2680 default:
2681 goto scan_number_done;
2682 }
2683
2684 scan_number_decimal1:
2685 // state: we just parsed a decimal point
2686 number_type = token_type::value_float;
2687 switch (get())
2688 {
2689 case '0':
2690 case '1':
2691 case '2':
2692 case '3':
2693 case '4':
2694 case '5':
2695 case '6':
2696 case '7':
2697 case '8':
2698 case '9':
2699 {
2700 add(current);
2701 goto scan_number_decimal2;
2702 }
2703
2704 default:
2705 {
2706 error_message = "invalid number; expected digit after '.'";
2707 return token_type::parse_error;
2708 }
2709 }
2710
2711 scan_number_decimal2:
2712 // we just parsed at least one number after a decimal point
2713 switch (get())
2714 {
2715 case '0':
2716 case '1':
2717 case '2':
2718 case '3':
2719 case '4':
2720 case '5':
2721 case '6':
2722 case '7':
2723 case '8':
2724 case '9':
2725 {
2726 add(current);
2727 goto scan_number_decimal2;
2728 }
2729
2730 case 'e':
2731 case 'E':
2732 {
2733 add(current);
2734 goto scan_number_exponent;
2735 }
2736
2737 default:
2738 goto scan_number_done;
2739 }
2740
2741 scan_number_exponent:
2742 // we just parsed an exponent
2743 number_type = token_type::value_float;
2744 switch (get())
2745 {
2746 case '+':
2747 case '-':
2748 {
2749 add(current);
2750 goto scan_number_sign;
2751 }
2752
2753 case '0':
2754 case '1':
2755 case '2':
2756 case '3':
2757 case '4':
2758 case '5':
2759 case '6':
2760 case '7':
2761 case '8':
2762 case '9':
2763 {
2764 add(current);
2765 goto scan_number_any2;
2766 }
2767
2768 default:
2769 {
2770 error_message =
2771 "invalid number; expected '+', '-', or digit after exponent";
2772 return token_type::parse_error;
2773 }
2774 }
2775
2776 scan_number_sign:
2777 // we just parsed an exponent sign
2778 switch (get())
2779 {
2780 case '0':
2781 case '1':
2782 case '2':
2783 case '3':
2784 case '4':
2785 case '5':
2786 case '6':
2787 case '7':
2788 case '8':
2789 case '9':
2790 {
2791 add(current);
2792 goto scan_number_any2;
2793 }
2794
2795 default:
2796 {
2797 error_message = "invalid number; expected digit after exponent sign";
2798 return token_type::parse_error;
2799 }
2800 }
2801
2802 scan_number_any2:
2803 // we just parsed a number after the exponent or exponent sign
2804 switch (get())
2805 {
2806 case '0':
2807 case '1':
2808 case '2':
2809 case '3':
2810 case '4':
2811 case '5':
2812 case '6':
2813 case '7':
2814 case '8':
2815 case '9':
2816 {
2817 add(current);
2818 goto scan_number_any2;
2819 }
2820
2821 default:
2822 goto scan_number_done;
2823 }
2824
2825 scan_number_done:
2826 // unget the character after the number (we only read it to know that
2827 // we are done scanning a number)
2828 unget();
2829
2830 char* endptr = nullptr;
2831 errno = 0;
2832
2833 // try to parse integers first and fall back to floats
2834 if (number_type == token_type::value_unsigned)
2835 {
2836 const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
2837
2838 // we checked the number format before
2839 assert(endptr == token_buffer.data() + token_buffer.size());
2840
2841 if (errno == 0)
2842 {
2843 value_unsigned = static_cast<number_unsigned_t>(x);
2844 if (value_unsigned == x)
2845 {
2846 return token_type::value_unsigned;
2847 }
2848 }
2849 }
2850 else if (number_type == token_type::value_integer)
2851 {
2852 const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
2853
2854 // we checked the number format before
2855 assert(endptr == token_buffer.data() + token_buffer.size());
2856
2857 if (errno == 0)
2858 {
2859 value_integer = static_cast<number_integer_t>(x);
2860 if (value_integer == x)
2861 {
2862 return token_type::value_integer;
2863 }
2864 }
2865 }
2866
2867 // this code is reached if we parse a floating-point number or if an
2868 // integer conversion above failed
2869 strtof(value_float, token_buffer.data(), &endptr);
2870
2871 // we checked the number format before
2872 assert(endptr == token_buffer.data() + token_buffer.size());
2873
2874 return token_type::value_float;
2875 }
2876
2877 /*!
2878 @param[in] literal_text the literal text to expect
2879 @param[in] length the length of the passed literal text
2880 @param[in] return_type the token type to return on success
2881 */
scan_literal(const char * literal_text,const std::size_t length,token_type return_type)2882 token_type scan_literal(const char* literal_text, const std::size_t length,
2883 token_type return_type)
2884 {
2885 assert(current == literal_text[0]);
2886 for (std::size_t i = 1; i < length; ++i)
2887 {
2888 if (JSON_UNLIKELY(get() != literal_text[i]))
2889 {
2890 error_message = "invalid literal";
2891 return token_type::parse_error;
2892 }
2893 }
2894 return return_type;
2895 }
2896
2897 /////////////////////
2898 // input management
2899 /////////////////////
2900
2901 /// reset token_buffer; current character is beginning of token
reset()2902 void reset() noexcept
2903 {
2904 token_buffer.clear();
2905 token_string.clear();
2906 token_string.push_back(std::char_traits<char>::to_char_type(current));
2907 }
2908
2909 /*
2910 @brief get next character from the input
2911
2912 This function provides the interface to the used input adapter. It does
2913 not throw in case the input reached EOF, but returns a
2914 `std::char_traits<char>::eof()` in that case. Stores the scanned characters
2915 for use in error messages.
2916
2917 @return character read from the input
2918 */
get()2919 std::char_traits<char>::int_type get()
2920 {
2921 ++chars_read;
2922 current = ia->get_character();
2923 if (JSON_LIKELY(current != std::char_traits<char>::eof()))
2924 {
2925 token_string.push_back(std::char_traits<char>::to_char_type(current));
2926 }
2927 return current;
2928 }
2929
2930 /// unget current character (return it again on next get)
unget()2931 void unget()
2932 {
2933 --chars_read;
2934 if (JSON_LIKELY(current != std::char_traits<char>::eof()))
2935 {
2936 ia->unget_character();
2937 assert(token_string.size() != 0);
2938 token_string.pop_back();
2939 }
2940 }
2941
2942 /// add a character to token_buffer
add(int c)2943 void add(int c)
2944 {
2945 token_buffer.push_back(std::char_traits<char>::to_char_type(c));
2946 }
2947
2948 public:
2949 /////////////////////
2950 // value getters
2951 /////////////////////
2952
2953 /// return integer value
get_number_integer() const2954 constexpr number_integer_t get_number_integer() const noexcept
2955 {
2956 return value_integer;
2957 }
2958
2959 /// return unsigned integer value
get_number_unsigned() const2960 constexpr number_unsigned_t get_number_unsigned() const noexcept
2961 {
2962 return value_unsigned;
2963 }
2964
2965 /// return floating-point value
get_number_float() const2966 constexpr number_float_t get_number_float() const noexcept
2967 {
2968 return value_float;
2969 }
2970
2971 /// return current string value (implicitly resets the token; useful only once)
move_string()2972 std::string move_string()
2973 {
2974 return std::move(token_buffer);
2975 }
2976
2977 /////////////////////
2978 // diagnostics
2979 /////////////////////
2980
2981 /// return position of last read token
get_position() const2982 constexpr std::size_t get_position() const noexcept
2983 {
2984 return chars_read;
2985 }
2986
2987 /// return the last read token (for errors only). Will never contain EOF
2988 /// (an arbitrary value that is not a valid char value, often -1), because
2989 /// 255 may legitimately occur. May contain NUL, which should be escaped.
get_token_string() const2990 std::string get_token_string() const
2991 {
2992 // escape control characters
2993 std::string result;
2994 for (const auto c : token_string)
2995 {
2996 if ('\x00' <= c and c <= '\x1F')
2997 {
2998 // escape control characters
2999 std::stringstream ss;
3000 ss << "<U+" << std::setw(4) << std::uppercase << std::setfill('0')
3001 << std::hex << static_cast<int>(c) << ">";
3002 result += ss.str();
3003 }
3004 else
3005 {
3006 // add character as is
3007 result.push_back(c);
3008 }
3009 }
3010
3011 return result;
3012 }
3013
3014 /// return syntax error message
get_error_message() const3015 constexpr const char* get_error_message() const noexcept
3016 {
3017 return error_message;
3018 }
3019
3020 /////////////////////
3021 // actual scanner
3022 /////////////////////
3023
scan()3024 token_type scan()
3025 {
3026 // read next character and ignore whitespace
3027 do
3028 {
3029 get();
3030 }
3031 while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
3032
3033 switch (current)
3034 {
3035 // structural characters
3036 case '[':
3037 return token_type::begin_array;
3038 case ']':
3039 return token_type::end_array;
3040 case '{':
3041 return token_type::begin_object;
3042 case '}':
3043 return token_type::end_object;
3044 case ':':
3045 return token_type::name_separator;
3046 case ',':
3047 return token_type::value_separator;
3048
3049 // literals
3050 case 't':
3051 return scan_literal("true", 4, token_type::literal_true);
3052 case 'f':
3053 return scan_literal("false", 5, token_type::literal_false);
3054 case 'n':
3055 return scan_literal("null", 4, token_type::literal_null);
3056
3057 // string
3058 case '\"':
3059 return scan_string();
3060
3061 // number
3062 case '-':
3063 case '0':
3064 case '1':
3065 case '2':
3066 case '3':
3067 case '4':
3068 case '5':
3069 case '6':
3070 case '7':
3071 case '8':
3072 case '9':
3073 return scan_number();
3074
3075 // end of input (the null byte is needed when parsing from
3076 // string literals)
3077 case '\0':
3078 case std::char_traits<char>::eof():
3079 return token_type::end_of_input;
3080
3081 // error
3082 default:
3083 error_message = "invalid literal";
3084 return token_type::parse_error;
3085 }
3086 }
3087
3088 private:
3089 /// input adapter
3090 detail::input_adapter_t ia = nullptr;
3091
3092 /// the current character
3093 std::char_traits<char>::int_type current = std::char_traits<char>::eof();
3094
3095 /// the number of characters read
3096 std::size_t chars_read = 0;
3097
3098 /// raw input token string (for error messages)
3099 std::vector<char> token_string {};
3100
3101 /// buffer for variable-length tokens (numbers, strings)
3102 std::string token_buffer {};
3103
3104 /// a description of occurred lexer errors
3105 const char* error_message = "";
3106
3107 // number values
3108 number_integer_t value_integer = 0;
3109 number_unsigned_t value_unsigned = 0;
3110 number_float_t value_float = 0;
3111
3112 /// the decimal point
3113 const char decimal_point_char = '.';
3114 };
3115 }
3116 }
3117
3118 // #include <nlohmann/detail/input/parser.hpp>
3119
3120
3121 #include <cassert> // assert
3122 #include <cmath> // isfinite
3123 #include <cstdint> // uint8_t
3124 #include <functional> // function
3125 #include <string> // string
3126 #include <utility> // move
3127
3128 // #include <nlohmann/detail/exceptions.hpp>
3129
3130 // #include <nlohmann/detail/macro_scope.hpp>
3131
3132 // #include <nlohmann/detail/input/input_adapters.hpp>
3133
3134 // #include <nlohmann/detail/input/lexer.hpp>
3135
3136 // #include <nlohmann/detail/value_t.hpp>
3137
3138
3139 namespace nlohmann
3140 {
3141 namespace detail
3142 {
3143 ////////////
3144 // parser //
3145 ////////////
3146
3147 /*!
3148 @brief syntax analysis
3149
3150 This class implements a recursive decent parser.
3151 */
3152 template<typename BasicJsonType>
3153 class parser
3154 {
3155 using number_integer_t = typename BasicJsonType::number_integer_t;
3156 using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
3157 using number_float_t = typename BasicJsonType::number_float_t;
3158 using lexer_t = lexer<BasicJsonType>;
3159 using token_type = typename lexer_t::token_type;
3160
3161 public:
3162 enum class parse_event_t : uint8_t
3163 {
3164 /// the parser read `{` and started to process a JSON object
3165 object_start,
3166 /// the parser read `}` and finished processing a JSON object
3167 object_end,
3168 /// the parser read `[` and started to process a JSON array
3169 array_start,
3170 /// the parser read `]` and finished processing a JSON array
3171 array_end,
3172 /// the parser read a key of a value in an object
3173 key,
3174 /// the parser finished reading a JSON value
3175 value
3176 };
3177
3178 using parser_callback_t =
3179 std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
3180
3181 /// a parser reading from an input adapter
parser(detail::input_adapter_t adapter,const parser_callback_t cb=nullptr,const bool allow_exceptions_=true)3182 explicit parser(detail::input_adapter_t adapter,
3183 const parser_callback_t cb = nullptr,
3184 const bool allow_exceptions_ = true)
3185 : callback(cb), m_lexer(adapter), allow_exceptions(allow_exceptions_)
3186 {}
3187
3188 /*!
3189 @brief public parser interface
3190
3191 @param[in] strict whether to expect the last token to be EOF
3192 @param[in,out] result parsed JSON value
3193
3194 @throw parse_error.101 in case of an unexpected token
3195 @throw parse_error.102 if to_unicode fails or surrogate error
3196 @throw parse_error.103 if to_unicode fails
3197 */
parse(const bool strict,BasicJsonType & result)3198 void parse(const bool strict, BasicJsonType& result)
3199 {
3200 // read first token
3201 get_token();
3202
3203 parse_internal(true, result);
3204 result.assert_invariant();
3205
3206 // in strict mode, input must be completely read
3207 if (strict)
3208 {
3209 get_token();
3210 expect(token_type::end_of_input);
3211 }
3212
3213 // in case of an error, return discarded value
3214 if (errored)
3215 {
3216 result = value_t::discarded;
3217 return;
3218 }
3219
3220 // set top-level value to null if it was discarded by the callback
3221 // function
3222 if (result.is_discarded())
3223 {
3224 result = nullptr;
3225 }
3226 }
3227
3228 /*!
3229 @brief public accept interface
3230
3231 @param[in] strict whether to expect the last token to be EOF
3232 @return whether the input is a proper JSON text
3233 */
accept(const bool strict=true)3234 bool accept(const bool strict = true)
3235 {
3236 // read first token
3237 get_token();
3238
3239 if (not accept_internal())
3240 {
3241 return false;
3242 }
3243
3244 // strict => last token must be EOF
3245 return not strict or (get_token() == token_type::end_of_input);
3246 }
3247
3248 private:
3249 /*!
3250 @brief the actual parser
3251 @throw parse_error.101 in case of an unexpected token
3252 @throw parse_error.102 if to_unicode fails or surrogate error
3253 @throw parse_error.103 if to_unicode fails
3254 */
parse_internal(bool keep,BasicJsonType & result)3255 void parse_internal(bool keep, BasicJsonType& result)
3256 {
3257 // never parse after a parse error was detected
3258 assert(not errored);
3259
3260 // start with a discarded value
3261 if (not result.is_discarded())
3262 {
3263 result.m_value.destroy(result.m_type);
3264 result.m_type = value_t::discarded;
3265 }
3266
3267 switch (last_token)
3268 {
3269 case token_type::begin_object:
3270 {
3271 if (keep)
3272 {
3273 if (callback)
3274 {
3275 keep = callback(depth++, parse_event_t::object_start, result);
3276 }
3277
3278 if (not callback or keep)
3279 {
3280 // explicitly set result to object to cope with {}
3281 result.m_type = value_t::object;
3282 result.m_value = value_t::object;
3283 }
3284 }
3285
3286 // read next token
3287 get_token();
3288
3289 // closing } -> we are done
3290 if (last_token == token_type::end_object)
3291 {
3292 if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
3293 {
3294 result.m_value.destroy(result.m_type);
3295 result.m_type = value_t::discarded;
3296 }
3297 break;
3298 }
3299
3300 // parse values
3301 std::string key;
3302 BasicJsonType value;
3303 while (true)
3304 {
3305 // store key
3306 if (not expect(token_type::value_string))
3307 {
3308 return;
3309 }
3310 key = m_lexer.move_string();
3311
3312 bool keep_tag = false;
3313 if (keep)
3314 {
3315 if (callback)
3316 {
3317 BasicJsonType k(key);
3318 keep_tag = callback(depth, parse_event_t::key, k);
3319 }
3320 else
3321 {
3322 keep_tag = true;
3323 }
3324 }
3325
3326 // parse separator (:)
3327 get_token();
3328 if (not expect(token_type::name_separator))
3329 {
3330 return;
3331 }
3332
3333 // parse and add value
3334 get_token();
3335 value.m_value.destroy(value.m_type);
3336 value.m_type = value_t::discarded;
3337 parse_internal(keep, value);
3338
3339 if (JSON_UNLIKELY(errored))
3340 {
3341 return;
3342 }
3343
3344 if (keep and keep_tag and not value.is_discarded())
3345 {
3346 result.m_value.object->emplace(std::move(key), std::move(value));
3347 }
3348
3349 // comma -> next value
3350 get_token();
3351 if (last_token == token_type::value_separator)
3352 {
3353 get_token();
3354 continue;
3355 }
3356
3357 // closing }
3358 if (not expect(token_type::end_object))
3359 {
3360 return;
3361 }
3362 break;
3363 }
3364
3365 if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
3366 {
3367 result.m_value.destroy(result.m_type);
3368 result.m_type = value_t::discarded;
3369 }
3370 break;
3371 }
3372
3373 case token_type::begin_array:
3374 {
3375 if (keep)
3376 {
3377 if (callback)
3378 {
3379 keep = callback(depth++, parse_event_t::array_start, result);
3380 }
3381
3382 if (not callback or keep)
3383 {
3384 // explicitly set result to array to cope with []
3385 result.m_type = value_t::array;
3386 result.m_value = value_t::array;
3387 }
3388 }
3389
3390 // read next token
3391 get_token();
3392
3393 // closing ] -> we are done
3394 if (last_token == token_type::end_array)
3395 {
3396 if (callback and not callback(--depth, parse_event_t::array_end, result))
3397 {
3398 result.m_value.destroy(result.m_type);
3399 result.m_type = value_t::discarded;
3400 }
3401 break;
3402 }
3403
3404 // parse values
3405 BasicJsonType value;
3406 while (true)
3407 {
3408 // parse value
3409 value.m_value.destroy(value.m_type);
3410 value.m_type = value_t::discarded;
3411 parse_internal(keep, value);
3412
3413 if (JSON_UNLIKELY(errored))
3414 {
3415 return;
3416 }
3417
3418 if (keep and not value.is_discarded())
3419 {
3420 result.m_value.array->push_back(std::move(value));
3421 }
3422
3423 // comma -> next value
3424 get_token();
3425 if (last_token == token_type::value_separator)
3426 {
3427 get_token();
3428 continue;
3429 }
3430
3431 // closing ]
3432 if (not expect(token_type::end_array))
3433 {
3434 return;
3435 }
3436 break;
3437 }
3438
3439 if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
3440 {
3441 result.m_value.destroy(result.m_type);
3442 result.m_type = value_t::discarded;
3443 }
3444 break;
3445 }
3446
3447 case token_type::literal_null:
3448 {
3449 result.m_type = value_t::null;
3450 break;
3451 }
3452
3453 case token_type::value_string:
3454 {
3455 result.m_type = value_t::string;
3456 result.m_value = m_lexer.move_string();
3457 break;
3458 }
3459
3460 case token_type::literal_true:
3461 {
3462 result.m_type = value_t::boolean;
3463 result.m_value = true;
3464 break;
3465 }
3466
3467 case token_type::literal_false:
3468 {
3469 result.m_type = value_t::boolean;
3470 result.m_value = false;
3471 break;
3472 }
3473
3474 case token_type::value_unsigned:
3475 {
3476 result.m_type = value_t::number_unsigned;
3477 result.m_value = m_lexer.get_number_unsigned();
3478 break;
3479 }
3480
3481 case token_type::value_integer:
3482 {
3483 result.m_type = value_t::number_integer;
3484 result.m_value = m_lexer.get_number_integer();
3485 break;
3486 }
3487
3488 case token_type::value_float:
3489 {
3490 result.m_type = value_t::number_float;
3491 result.m_value = m_lexer.get_number_float();
3492
3493 // throw in case of infinity or NAN
3494 if (JSON_UNLIKELY(not std::isfinite(result.m_value.number_float)))
3495 {
3496 if (allow_exceptions)
3497 {
3498 JSON_THROW(out_of_range::create(406, "number overflow parsing '" +
3499 m_lexer.get_token_string() + "'"));
3500 }
3501 expect(token_type::uninitialized);
3502 }
3503 break;
3504 }
3505
3506 case token_type::parse_error:
3507 {
3508 // using "uninitialized" to avoid "expected" message
3509 if (not expect(token_type::uninitialized))
3510 {
3511 return;
3512 }
3513 break; // LCOV_EXCL_LINE
3514 }
3515
3516 default:
3517 {
3518 // the last token was unexpected; we expected a value
3519 if (not expect(token_type::literal_or_value))
3520 {
3521 return;
3522 }
3523 break; // LCOV_EXCL_LINE
3524 }
3525 }
3526
3527 if (keep and callback and not callback(depth, parse_event_t::value, result))
3528 {
3529 result.m_type = value_t::discarded;
3530 }
3531 }
3532
3533 /*!
3534 @brief the actual acceptor
3535
3536 @invariant 1. The last token is not yet processed. Therefore, the caller
3537 of this function must make sure a token has been read.
3538 2. When this function returns, the last token is processed.
3539 That is, the last read character was already considered.
3540
3541 This invariant makes sure that no token needs to be "unput".
3542 */
accept_internal()3543 bool accept_internal()
3544 {
3545 switch (last_token)
3546 {
3547 case token_type::begin_object:
3548 {
3549 // read next token
3550 get_token();
3551
3552 // closing } -> we are done
3553 if (last_token == token_type::end_object)
3554 {
3555 return true;
3556 }
3557
3558 // parse values
3559 while (true)
3560 {
3561 // parse key
3562 if (last_token != token_type::value_string)
3563 {
3564 return false;
3565 }
3566
3567 // parse separator (:)
3568 get_token();
3569 if (last_token != token_type::name_separator)
3570 {
3571 return false;
3572 }
3573
3574 // parse value
3575 get_token();
3576 if (not accept_internal())
3577 {
3578 return false;
3579 }
3580
3581 // comma -> next value
3582 get_token();
3583 if (last_token == token_type::value_separator)
3584 {
3585 get_token();
3586 continue;
3587 }
3588
3589 // closing }
3590 return (last_token == token_type::end_object);
3591 }
3592 }
3593
3594 case token_type::begin_array:
3595 {
3596 // read next token
3597 get_token();
3598
3599 // closing ] -> we are done
3600 if (last_token == token_type::end_array)
3601 {
3602 return true;
3603 }
3604
3605 // parse values
3606 while (true)
3607 {
3608 // parse value
3609 if (not accept_internal())
3610 {
3611 return false;
3612 }
3613
3614 // comma -> next value
3615 get_token();
3616 if (last_token == token_type::value_separator)
3617 {
3618 get_token();
3619 continue;
3620 }
3621
3622 // closing ]
3623 return (last_token == token_type::end_array);
3624 }
3625 }
3626
3627 case token_type::value_float:
3628 {
3629 // reject infinity or NAN
3630 return std::isfinite(m_lexer.get_number_float());
3631 }
3632
3633 case token_type::literal_false:
3634 case token_type::literal_null:
3635 case token_type::literal_true:
3636 case token_type::value_integer:
3637 case token_type::value_string:
3638 case token_type::value_unsigned:
3639 return true;
3640
3641 default: // the last token was unexpected
3642 return false;
3643 }
3644 }
3645
3646 /// get next token from lexer
get_token()3647 token_type get_token()
3648 {
3649 return (last_token = m_lexer.scan());
3650 }
3651
3652 /*!
3653 @throw parse_error.101 if expected token did not occur
3654 */
expect(token_type t)3655 bool expect(token_type t)
3656 {
3657 if (JSON_UNLIKELY(t != last_token))
3658 {
3659 errored = true;
3660 expected = t;
3661 if (allow_exceptions)
3662 {
3663 throw_exception();
3664 }
3665 else
3666 {
3667 return false;
3668 }
3669 }
3670
3671 return true;
3672 }
3673
throw_exception() const3674 [[noreturn]] void throw_exception() const
3675 {
3676 std::string error_msg = "syntax error - ";
3677 if (last_token == token_type::parse_error)
3678 {
3679 error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
3680 m_lexer.get_token_string() + "'";
3681 }
3682 else
3683 {
3684 error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
3685 }
3686
3687 if (expected != token_type::uninitialized)
3688 {
3689 error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
3690 }
3691
3692 JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg));
3693 }
3694
3695 private:
3696 /// current level of recursion
3697 int depth = 0;
3698 /// callback function
3699 const parser_callback_t callback = nullptr;
3700 /// the type of the last read token
3701 token_type last_token = token_type::uninitialized;
3702 /// the lexer
3703 lexer_t m_lexer;
3704 /// whether a syntax error occurred
3705 bool errored = false;
3706 /// possible reason for the syntax error
3707 token_type expected = token_type::uninitialized;
3708 /// whether to throw exceptions in case of errors
3709 const bool allow_exceptions = true;
3710 };
3711 }
3712 }
3713
3714 // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
3715
3716
3717 #include <cstddef> // ptrdiff_t
3718 #include <limits> // numeric_limits
3719
3720 namespace nlohmann
3721 {
3722 namespace detail
3723 {
3724 /*
3725 @brief an iterator for primitive JSON types
3726
3727 This class models an iterator for primitive JSON types (boolean, number,
3728 string). It's only purpose is to allow the iterator/const_iterator classes
3729 to "iterate" over primitive values. Internally, the iterator is modeled by
3730 a `difference_type` variable. Value begin_value (`0`) models the begin,
3731 end_value (`1`) models past the end.
3732 */
3733 class primitive_iterator_t
3734 {
3735 private:
3736 using difference_type = std::ptrdiff_t;
3737 static constexpr difference_type begin_value = 0;
3738 static constexpr difference_type end_value = begin_value + 1;
3739
3740 /// iterator as signed integer type
3741 difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
3742
3743 public:
get_value() const3744 constexpr difference_type get_value() const noexcept
3745 {
3746 return m_it;
3747 }
3748
3749 /// set iterator to a defined beginning
set_begin()3750 void set_begin() noexcept
3751 {
3752 m_it = begin_value;
3753 }
3754
3755 /// set iterator to a defined past the end
set_end()3756 void set_end() noexcept
3757 {
3758 m_it = end_value;
3759 }
3760
3761 /// return whether the iterator can be dereferenced
is_begin() const3762 constexpr bool is_begin() const noexcept
3763 {
3764 return m_it == begin_value;
3765 }
3766
3767 /// return whether the iterator is at end
is_end() const3768 constexpr bool is_end() const noexcept
3769 {
3770 return m_it == end_value;
3771 }
3772
operator ==(primitive_iterator_t lhs,primitive_iterator_t rhs)3773 friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3774 {
3775 return lhs.m_it == rhs.m_it;
3776 }
3777
operator <(primitive_iterator_t lhs,primitive_iterator_t rhs)3778 friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3779 {
3780 return lhs.m_it < rhs.m_it;
3781 }
3782
operator +(difference_type n)3783 primitive_iterator_t operator+(difference_type n) noexcept
3784 {
3785 auto result = *this;
3786 result += n;
3787 return result;
3788 }
3789
operator -(primitive_iterator_t lhs,primitive_iterator_t rhs)3790 friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3791 {
3792 return lhs.m_it - rhs.m_it;
3793 }
3794
operator ++()3795 primitive_iterator_t& operator++() noexcept
3796 {
3797 ++m_it;
3798 return *this;
3799 }
3800
operator ++(int)3801 primitive_iterator_t const operator++(int) noexcept
3802 {
3803 auto result = *this;
3804 m_it++;
3805 return result;
3806 }
3807
operator --()3808 primitive_iterator_t& operator--() noexcept
3809 {
3810 --m_it;
3811 return *this;
3812 }
3813
operator --(int)3814 primitive_iterator_t const operator--(int) noexcept
3815 {
3816 auto result = *this;
3817 m_it--;
3818 return result;
3819 }
3820
operator +=(difference_type n)3821 primitive_iterator_t& operator+=(difference_type n) noexcept
3822 {
3823 m_it += n;
3824 return *this;
3825 }
3826
operator -=(difference_type n)3827 primitive_iterator_t& operator-=(difference_type n) noexcept
3828 {
3829 m_it -= n;
3830 return *this;
3831 }
3832 };
3833 }
3834 }
3835
3836 // #include <nlohmann/detail/iterators/internal_iterator.hpp>
3837
3838
3839 // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
3840
3841
3842 namespace nlohmann
3843 {
3844 namespace detail
3845 {
3846 /*!
3847 @brief an iterator value
3848
3849 @note This structure could easily be a union, but MSVC currently does not allow
3850 unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
3851 */
3852 template<typename BasicJsonType> struct internal_iterator
3853 {
3854 /// iterator for JSON objects
3855 typename BasicJsonType::object_t::iterator object_iterator {};
3856 /// iterator for JSON arrays
3857 typename BasicJsonType::array_t::iterator array_iterator {};
3858 /// generic iterator for all other types
3859 primitive_iterator_t primitive_iterator {};
3860 };
3861 }
3862 }
3863
3864 // #include <nlohmann/detail/iterators/iter_impl.hpp>
3865
3866
3867 #include <ciso646> // not
3868 #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
3869 #include <type_traits> // conditional, is_const, remove_const
3870
3871 // #include <nlohmann/detail/exceptions.hpp>
3872
3873 // #include <nlohmann/detail/iterators/internal_iterator.hpp>
3874
3875 // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
3876
3877 // #include <nlohmann/detail/macro_scope.hpp>
3878
3879 // #include <nlohmann/detail/meta.hpp>
3880
3881 // #include <nlohmann/detail/value_t.hpp>
3882
3883
3884 namespace nlohmann
3885 {
3886 namespace detail
3887 {
3888 // forward declare, to be able to friend it later on
3889 template<typename IteratorType> class iteration_proxy;
3890
3891 /*!
3892 @brief a template for a bidirectional iterator for the @ref basic_json class
3893
3894 This class implements a both iterators (iterator and const_iterator) for the
3895 @ref basic_json class.
3896
3897 @note An iterator is called *initialized* when a pointer to a JSON value has
3898 been set (e.g., by a constructor or a copy assignment). If the iterator is
3899 default-constructed, it is *uninitialized* and most methods are undefined.
3900 **The library uses assertions to detect calls on uninitialized iterators.**
3901
3902 @requirement The class satisfies the following concept requirements:
3903 -
3904 [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):
3905 The iterator that can be moved can be moved in both directions (i.e.
3906 incremented and decremented).
3907
3908 @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
3909 iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
3910 */
3911 template<typename BasicJsonType>
3912 class iter_impl
3913 {
3914 /// allow basic_json to access private members
3915 friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
3916 friend BasicJsonType;
3917 friend iteration_proxy<iter_impl>;
3918
3919 using object_t = typename BasicJsonType::object_t;
3920 using array_t = typename BasicJsonType::array_t;
3921 // make sure BasicJsonType is basic_json or const basic_json
3922 static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
3923 "iter_impl only accepts (const) basic_json");
3924
3925 public:
3926
3927 /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
3928 /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
3929 /// A user-defined iterator should provide publicly accessible typedefs named
3930 /// iterator_category, value_type, difference_type, pointer, and reference.
3931 /// Note that value_type is required to be non-const, even for constant iterators.
3932 using iterator_category = std::bidirectional_iterator_tag;
3933
3934 /// the type of the values when the iterator is dereferenced
3935 using value_type = typename BasicJsonType::value_type;
3936 /// a type to represent differences between iterators
3937 using difference_type = typename BasicJsonType::difference_type;
3938 /// defines a pointer to the type iterated over (value_type)
3939 using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
3940 typename BasicJsonType::const_pointer,
3941 typename BasicJsonType::pointer>::type;
3942 /// defines a reference to the type iterated over (value_type)
3943 using reference =
3944 typename std::conditional<std::is_const<BasicJsonType>::value,
3945 typename BasicJsonType::const_reference,
3946 typename BasicJsonType::reference>::type;
3947
3948 /// default constructor
3949 iter_impl() = default;
3950
3951 /*!
3952 @brief constructor for a given JSON instance
3953 @param[in] object pointer to a JSON object for this iterator
3954 @pre object != nullptr
3955 @post The iterator is initialized; i.e. `m_object != nullptr`.
3956 */
iter_impl(pointer object)3957 explicit iter_impl(pointer object) noexcept : m_object(object)
3958 {
3959 assert(m_object != nullptr);
3960
3961 switch (m_object->m_type)
3962 {
3963 case value_t::object:
3964 {
3965 m_it.object_iterator = typename object_t::iterator();
3966 break;
3967 }
3968
3969 case value_t::array:
3970 {
3971 m_it.array_iterator = typename array_t::iterator();
3972 break;
3973 }
3974
3975 default:
3976 {
3977 m_it.primitive_iterator = primitive_iterator_t();
3978 break;
3979 }
3980 }
3981 }
3982
3983 /*!
3984 @note The conventional copy constructor and copy assignment are implicitly
3985 defined. Combined with the following converting constructor and
3986 assignment, they support: (1) copy from iterator to iterator, (2)
3987 copy from const iterator to const iterator, and (3) conversion from
3988 iterator to const iterator. However conversion from const iterator
3989 to iterator is not defined.
3990 */
3991
3992 /*!
3993 @brief converting constructor
3994 @param[in] other non-const iterator to copy from
3995 @note It is not checked whether @a other is initialized.
3996 */
iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type> & other)3997 iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
3998 : m_object(other.m_object), m_it(other.m_it) {}
3999
4000 /*!
4001 @brief converting assignment
4002 @param[in,out] other non-const iterator to copy from
4003 @return const/non-const iterator
4004 @note It is not checked whether @a other is initialized.
4005 */
operator =(const iter_impl<typename std::remove_const<BasicJsonType>::type> & other)4006 iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
4007 {
4008 m_object = other.m_object;
4009 m_it = other.m_it;
4010 return *this;
4011 }
4012
4013 private:
4014 /*!
4015 @brief set the iterator to the first value
4016 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4017 */
set_begin()4018 void set_begin() noexcept
4019 {
4020 assert(m_object != nullptr);
4021
4022 switch (m_object->m_type)
4023 {
4024 case value_t::object:
4025 {
4026 m_it.object_iterator = m_object->m_value.object->begin();
4027 break;
4028 }
4029
4030 case value_t::array:
4031 {
4032 m_it.array_iterator = m_object->m_value.array->begin();
4033 break;
4034 }
4035
4036 case value_t::null:
4037 {
4038 // set to end so begin()==end() is true: null is empty
4039 m_it.primitive_iterator.set_end();
4040 break;
4041 }
4042
4043 default:
4044 {
4045 m_it.primitive_iterator.set_begin();
4046 break;
4047 }
4048 }
4049 }
4050
4051 /*!
4052 @brief set the iterator past the last value
4053 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4054 */
set_end()4055 void set_end() noexcept
4056 {
4057 assert(m_object != nullptr);
4058
4059 switch (m_object->m_type)
4060 {
4061 case value_t::object:
4062 {
4063 m_it.object_iterator = m_object->m_value.object->end();
4064 break;
4065 }
4066
4067 case value_t::array:
4068 {
4069 m_it.array_iterator = m_object->m_value.array->end();
4070 break;
4071 }
4072
4073 default:
4074 {
4075 m_it.primitive_iterator.set_end();
4076 break;
4077 }
4078 }
4079 }
4080
4081 public:
4082 /*!
4083 @brief return a reference to the value pointed to by the iterator
4084 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4085 */
operator *() const4086 reference operator*() const
4087 {
4088 assert(m_object != nullptr);
4089
4090 switch (m_object->m_type)
4091 {
4092 case value_t::object:
4093 {
4094 assert(m_it.object_iterator != m_object->m_value.object->end());
4095 return m_it.object_iterator->second;
4096 }
4097
4098 case value_t::array:
4099 {
4100 assert(m_it.array_iterator != m_object->m_value.array->end());
4101 return *m_it.array_iterator;
4102 }
4103
4104 case value_t::null:
4105 JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4106
4107 default:
4108 {
4109 if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
4110 {
4111 return *m_object;
4112 }
4113
4114 JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4115 }
4116 }
4117 }
4118
4119 /*!
4120 @brief dereference the iterator
4121 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4122 */
operator ->() const4123 pointer operator->() const
4124 {
4125 assert(m_object != nullptr);
4126
4127 switch (m_object->m_type)
4128 {
4129 case value_t::object:
4130 {
4131 assert(m_it.object_iterator != m_object->m_value.object->end());
4132 return &(m_it.object_iterator->second);
4133 }
4134
4135 case value_t::array:
4136 {
4137 assert(m_it.array_iterator != m_object->m_value.array->end());
4138 return &*m_it.array_iterator;
4139 }
4140
4141 default:
4142 {
4143 if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
4144 {
4145 return m_object;
4146 }
4147
4148 JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4149 }
4150 }
4151 }
4152
4153 /*!
4154 @brief post-increment (it++)
4155 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4156 */
operator ++(int)4157 iter_impl const operator++(int)
4158 {
4159 auto result = *this;
4160 ++(*this);
4161 return result;
4162 }
4163
4164 /*!
4165 @brief pre-increment (++it)
4166 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4167 */
operator ++()4168 iter_impl& operator++()
4169 {
4170 assert(m_object != nullptr);
4171
4172 switch (m_object->m_type)
4173 {
4174 case value_t::object:
4175 {
4176 std::advance(m_it.object_iterator, 1);
4177 break;
4178 }
4179
4180 case value_t::array:
4181 {
4182 std::advance(m_it.array_iterator, 1);
4183 break;
4184 }
4185
4186 default:
4187 {
4188 ++m_it.primitive_iterator;
4189 break;
4190 }
4191 }
4192
4193 return *this;
4194 }
4195
4196 /*!
4197 @brief post-decrement (it--)
4198 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4199 */
operator --(int)4200 iter_impl const operator--(int)
4201 {
4202 auto result = *this;
4203 --(*this);
4204 return result;
4205 }
4206
4207 /*!
4208 @brief pre-decrement (--it)
4209 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4210 */
operator --()4211 iter_impl& operator--()
4212 {
4213 assert(m_object != nullptr);
4214
4215 switch (m_object->m_type)
4216 {
4217 case value_t::object:
4218 {
4219 std::advance(m_it.object_iterator, -1);
4220 break;
4221 }
4222
4223 case value_t::array:
4224 {
4225 std::advance(m_it.array_iterator, -1);
4226 break;
4227 }
4228
4229 default:
4230 {
4231 --m_it.primitive_iterator;
4232 break;
4233 }
4234 }
4235
4236 return *this;
4237 }
4238
4239 /*!
4240 @brief comparison: equal
4241 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4242 */
operator ==(const iter_impl & other) const4243 bool operator==(const iter_impl& other) const
4244 {
4245 // if objects are not the same, the comparison is undefined
4246 if (JSON_UNLIKELY(m_object != other.m_object))
4247 {
4248 JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
4249 }
4250
4251 assert(m_object != nullptr);
4252
4253 switch (m_object->m_type)
4254 {
4255 case value_t::object:
4256 return (m_it.object_iterator == other.m_it.object_iterator);
4257
4258 case value_t::array:
4259 return (m_it.array_iterator == other.m_it.array_iterator);
4260
4261 default:
4262 return (m_it.primitive_iterator == other.m_it.primitive_iterator);
4263 }
4264 }
4265
4266 /*!
4267 @brief comparison: not equal
4268 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4269 */
operator !=(const iter_impl & other) const4270 bool operator!=(const iter_impl& other) const
4271 {
4272 return not operator==(other);
4273 }
4274
4275 /*!
4276 @brief comparison: smaller
4277 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4278 */
operator <(const iter_impl & other) const4279 bool operator<(const iter_impl& other) const
4280 {
4281 // if objects are not the same, the comparison is undefined
4282 if (JSON_UNLIKELY(m_object != other.m_object))
4283 {
4284 JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
4285 }
4286
4287 assert(m_object != nullptr);
4288
4289 switch (m_object->m_type)
4290 {
4291 case value_t::object:
4292 JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
4293
4294 case value_t::array:
4295 return (m_it.array_iterator < other.m_it.array_iterator);
4296
4297 default:
4298 return (m_it.primitive_iterator < other.m_it.primitive_iterator);
4299 }
4300 }
4301
4302 /*!
4303 @brief comparison: less than or equal
4304 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4305 */
operator <=(const iter_impl & other) const4306 bool operator<=(const iter_impl& other) const
4307 {
4308 return not other.operator < (*this);
4309 }
4310
4311 /*!
4312 @brief comparison: greater than
4313 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4314 */
operator >(const iter_impl & other) const4315 bool operator>(const iter_impl& other) const
4316 {
4317 return not operator<=(other);
4318 }
4319
4320 /*!
4321 @brief comparison: greater than or equal
4322 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4323 */
operator >=(const iter_impl & other) const4324 bool operator>=(const iter_impl& other) const
4325 {
4326 return not operator<(other);
4327 }
4328
4329 /*!
4330 @brief add to iterator
4331 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4332 */
operator +=(difference_type i)4333 iter_impl& operator+=(difference_type i)
4334 {
4335 assert(m_object != nullptr);
4336
4337 switch (m_object->m_type)
4338 {
4339 case value_t::object:
4340 JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
4341
4342 case value_t::array:
4343 {
4344 std::advance(m_it.array_iterator, i);
4345 break;
4346 }
4347
4348 default:
4349 {
4350 m_it.primitive_iterator += i;
4351 break;
4352 }
4353 }
4354
4355 return *this;
4356 }
4357
4358 /*!
4359 @brief subtract from iterator
4360 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4361 */
operator -=(difference_type i)4362 iter_impl& operator-=(difference_type i)
4363 {
4364 return operator+=(-i);
4365 }
4366
4367 /*!
4368 @brief add to iterator
4369 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4370 */
operator +(difference_type i) const4371 iter_impl operator+(difference_type i) const
4372 {
4373 auto result = *this;
4374 result += i;
4375 return result;
4376 }
4377
4378 /*!
4379 @brief addition of distance and iterator
4380 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4381 */
operator +(difference_type i,const iter_impl & it)4382 friend iter_impl operator+(difference_type i, const iter_impl& it)
4383 {
4384 auto result = it;
4385 result += i;
4386 return result;
4387 }
4388
4389 /*!
4390 @brief subtract from iterator
4391 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4392 */
operator -(difference_type i) const4393 iter_impl operator-(difference_type i) const
4394 {
4395 auto result = *this;
4396 result -= i;
4397 return result;
4398 }
4399
4400 /*!
4401 @brief return difference
4402 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4403 */
operator -(const iter_impl & other) const4404 difference_type operator-(const iter_impl& other) const
4405 {
4406 assert(m_object != nullptr);
4407
4408 switch (m_object->m_type)
4409 {
4410 case value_t::object:
4411 JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
4412
4413 case value_t::array:
4414 return m_it.array_iterator - other.m_it.array_iterator;
4415
4416 default:
4417 return m_it.primitive_iterator - other.m_it.primitive_iterator;
4418 }
4419 }
4420
4421 /*!
4422 @brief access to successor
4423 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4424 */
operator [](difference_type n) const4425 reference operator[](difference_type n) const
4426 {
4427 assert(m_object != nullptr);
4428
4429 switch (m_object->m_type)
4430 {
4431 case value_t::object:
4432 JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
4433
4434 case value_t::array:
4435 return *std::next(m_it.array_iterator, n);
4436
4437 case value_t::null:
4438 JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4439
4440 default:
4441 {
4442 if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
4443 {
4444 return *m_object;
4445 }
4446
4447 JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4448 }
4449 }
4450 }
4451
4452 /*!
4453 @brief return the key of an object iterator
4454 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4455 */
key() const4456 typename object_t::key_type key() const
4457 {
4458 assert(m_object != nullptr);
4459
4460 if (JSON_LIKELY(m_object->is_object()))
4461 {
4462 return m_it.object_iterator->first;
4463 }
4464
4465 JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
4466 }
4467
4468 /*!
4469 @brief return the value of an iterator
4470 @pre The iterator is initialized; i.e. `m_object != nullptr`.
4471 */
value() const4472 reference value() const
4473 {
4474 return operator*();
4475 }
4476
4477 private:
4478 /// associated JSON instance
4479 pointer m_object = nullptr;
4480 /// the actual iterator of the associated instance
4481 internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it;
4482 };
4483 }
4484 }
4485
4486 // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
4487
4488
4489 #include <cstddef> // size_t
4490 #include <string> // string, to_string
4491
4492 // #include <nlohmann/detail/value_t.hpp>
4493
4494
4495 namespace nlohmann
4496 {
4497 namespace detail
4498 {
4499 /// proxy class for the items() function
4500 template<typename IteratorType> class iteration_proxy
4501 {
4502 private:
4503 /// helper class for iteration
4504 class iteration_proxy_internal
4505 {
4506 private:
4507 /// the iterator
4508 IteratorType anchor;
4509 /// an index for arrays (used to create key names)
4510 std::size_t array_index = 0;
4511
4512 public:
iteration_proxy_internal(IteratorType it)4513 explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {}
4514
4515 /// dereference operator (needed for range-based for)
operator *()4516 iteration_proxy_internal& operator*()
4517 {
4518 return *this;
4519 }
4520
4521 /// increment operator (needed for range-based for)
operator ++()4522 iteration_proxy_internal& operator++()
4523 {
4524 ++anchor;
4525 ++array_index;
4526
4527 return *this;
4528 }
4529
4530 /// inequality operator (needed for range-based for)
operator !=(const iteration_proxy_internal & o) const4531 bool operator!=(const iteration_proxy_internal& o) const noexcept
4532 {
4533 return anchor != o.anchor;
4534 }
4535
4536 /// return key of the iterator
key() const4537 std::string key() const
4538 {
4539 assert(anchor.m_object != nullptr);
4540
4541 switch (anchor.m_object->type())
4542 {
4543 // use integer array index as key
4544 case value_t::array:
4545 return std::to_string(array_index);
4546
4547 // use key from the object
4548 case value_t::object:
4549 return anchor.key();
4550
4551 // use an empty key for all primitive types
4552 default:
4553 return "";
4554 }
4555 }
4556
4557 /// return value of the iterator
value() const4558 typename IteratorType::reference value() const
4559 {
4560 return anchor.value();
4561 }
4562 };
4563
4564 /// the container to iterate
4565 typename IteratorType::reference container;
4566
4567 public:
4568 /// construct iteration proxy from a container
iteration_proxy(typename IteratorType::reference cont)4569 explicit iteration_proxy(typename IteratorType::reference cont) noexcept
4570 : container(cont) {}
4571
4572 /// return iterator begin (needed for range-based for)
begin()4573 iteration_proxy_internal begin() noexcept
4574 {
4575 return iteration_proxy_internal(container.begin());
4576 }
4577
4578 /// return iterator end (needed for range-based for)
end()4579 iteration_proxy_internal end() noexcept
4580 {
4581 return iteration_proxy_internal(container.end());
4582 }
4583 };
4584 }
4585 }
4586
4587 // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
4588
4589
4590 #include <cstddef> // ptrdiff_t
4591 #include <iterator> // reverse_iterator
4592 #include <utility> // declval
4593
4594 namespace nlohmann
4595 {
4596 namespace detail
4597 {
4598 //////////////////////
4599 // reverse_iterator //
4600 //////////////////////
4601
4602 /*!
4603 @brief a template for a reverse iterator class
4604
4605 @tparam Base the base iterator type to reverse. Valid types are @ref
4606 iterator (to create @ref reverse_iterator) and @ref const_iterator (to
4607 create @ref const_reverse_iterator).
4608
4609 @requirement The class satisfies the following concept requirements:
4610 -
4611 [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):
4612 The iterator that can be moved can be moved in both directions (i.e.
4613 incremented and decremented).
4614 - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
4615 It is possible to write to the pointed-to element (only if @a Base is
4616 @ref iterator).
4617
4618 @since version 1.0.0
4619 */
4620 template<typename Base>
4621 class json_reverse_iterator : public std::reverse_iterator<Base>
4622 {
4623 public:
4624 using difference_type = std::ptrdiff_t;
4625 /// shortcut to the reverse iterator adapter
4626 using base_iterator = std::reverse_iterator<Base>;
4627 /// the reference type for the pointed-to element
4628 using reference = typename Base::reference;
4629
4630 /// create reverse iterator from iterator
json_reverse_iterator(const typename base_iterator::iterator_type & it)4631 json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
4632 : base_iterator(it) {}
4633
4634 /// create reverse iterator from base class
json_reverse_iterator(const base_iterator & it)4635 json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
4636
4637 /// post-increment (it++)
operator ++(int)4638 json_reverse_iterator const operator++(int)
4639 {
4640 return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
4641 }
4642
4643 /// pre-increment (++it)
operator ++()4644 json_reverse_iterator& operator++()
4645 {
4646 return static_cast<json_reverse_iterator&>(base_iterator::operator++());
4647 }
4648
4649 /// post-decrement (it--)
operator --(int)4650 json_reverse_iterator const operator--(int)
4651 {
4652 return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
4653 }
4654
4655 /// pre-decrement (--it)
operator --()4656 json_reverse_iterator& operator--()
4657 {
4658 return static_cast<json_reverse_iterator&>(base_iterator::operator--());
4659 }
4660
4661 /// add to iterator
operator +=(difference_type i)4662 json_reverse_iterator& operator+=(difference_type i)
4663 {
4664 return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
4665 }
4666
4667 /// add to iterator
operator +(difference_type i) const4668 json_reverse_iterator operator+(difference_type i) const
4669 {
4670 return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
4671 }
4672
4673 /// subtract from iterator
operator -(difference_type i) const4674 json_reverse_iterator operator-(difference_type i) const
4675 {
4676 return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
4677 }
4678
4679 /// return difference
operator -(const json_reverse_iterator & other) const4680 difference_type operator-(const json_reverse_iterator& other) const
4681 {
4682 return base_iterator(*this) - base_iterator(other);
4683 }
4684
4685 /// access to successor
operator [](difference_type n) const4686 reference operator[](difference_type n) const
4687 {
4688 return *(this->operator+(n));
4689 }
4690
4691 /// return the key of an object iterator
key() const4692 auto key() const -> decltype(std::declval<Base>().key())
4693 {
4694 auto it = --this->base();
4695 return it.key();
4696 }
4697
4698 /// return the value of an iterator
value() const4699 reference value() const
4700 {
4701 auto it = --this->base();
4702 return it.operator * ();
4703 }
4704 };
4705 }
4706 }
4707
4708 // #include <nlohmann/detail/output/output_adapters.hpp>
4709
4710
4711 #include <algorithm> // copy
4712 #include <cstddef> // size_t
4713 #include <ios> // streamsize
4714 #include <iterator> // back_inserter
4715 #include <memory> // shared_ptr, make_shared
4716 #include <ostream> // basic_ostream
4717 #include <string> // basic_string
4718 #include <vector> // vector
4719
4720 namespace nlohmann
4721 {
4722 namespace detail
4723 {
4724 /// abstract output adapter interface
4725 template<typename CharType> struct output_adapter_protocol
4726 {
4727 virtual void write_character(CharType c) = 0;
4728 virtual void write_characters(const CharType* s, std::size_t length) = 0;
4729 virtual ~output_adapter_protocol() = default;
4730 };
4731
4732 /// a type to simplify interfaces
4733 template<typename CharType>
4734 using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
4735
4736 /// output adapter for byte vectors
4737 template<typename CharType>
4738 class output_vector_adapter : public output_adapter_protocol<CharType>
4739 {
4740 public:
output_vector_adapter(std::vector<CharType> & vec)4741 explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {}
4742
write_character(CharType c)4743 void write_character(CharType c) override
4744 {
4745 v.push_back(c);
4746 }
4747
write_characters(const CharType * s,std::size_t length)4748 void write_characters(const CharType* s, std::size_t length) override
4749 {
4750 std::copy(s, s + length, std::back_inserter(v));
4751 }
4752
4753 private:
4754 std::vector<CharType>& v;
4755 };
4756
4757 /// output adapter for output streams
4758 template<typename CharType>
4759 class output_stream_adapter : public output_adapter_protocol<CharType>
4760 {
4761 public:
output_stream_adapter(std::basic_ostream<CharType> & s)4762 explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {}
4763
write_character(CharType c)4764 void write_character(CharType c) override
4765 {
4766 stream.put(c);
4767 }
4768
write_characters(const CharType * s,std::size_t length)4769 void write_characters(const CharType* s, std::size_t length) override
4770 {
4771 stream.write(s, static_cast<std::streamsize>(length));
4772 }
4773
4774 private:
4775 std::basic_ostream<CharType>& stream;
4776 };
4777
4778 /// output adapter for basic_string
4779 template<typename CharType>
4780 class output_string_adapter : public output_adapter_protocol<CharType>
4781 {
4782 public:
output_string_adapter(std::basic_string<CharType> & s)4783 explicit output_string_adapter(std::basic_string<CharType>& s) : str(s) {}
4784
write_character(CharType c)4785 void write_character(CharType c) override
4786 {
4787 str.push_back(c);
4788 }
4789
write_characters(const CharType * s,std::size_t length)4790 void write_characters(const CharType* s, std::size_t length) override
4791 {
4792 str.append(s, length);
4793 }
4794
4795 private:
4796 std::basic_string<CharType>& str;
4797 };
4798
4799 template<typename CharType>
4800 class output_adapter
4801 {
4802 public:
output_adapter(std::vector<CharType> & vec)4803 output_adapter(std::vector<CharType>& vec)
4804 : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
4805
output_adapter(std::basic_ostream<CharType> & s)4806 output_adapter(std::basic_ostream<CharType>& s)
4807 : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
4808
output_adapter(std::basic_string<CharType> & s)4809 output_adapter(std::basic_string<CharType>& s)
4810 : oa(std::make_shared<output_string_adapter<CharType>>(s)) {}
4811
operator output_adapter_t<CharType>()4812 operator output_adapter_t<CharType>()
4813 {
4814 return oa;
4815 }
4816
4817 private:
4818 output_adapter_t<CharType> oa = nullptr;
4819 };
4820 }
4821 }
4822
4823 // #include <nlohmann/detail/input/binary_reader.hpp>
4824
4825
4826 #include <algorithm> // generate_n
4827 #include <array> // array
4828 #include <cassert> // assert
4829 #include <cmath> // ldexp
4830 #include <cstddef> // size_t
4831 #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
4832 #include <cstring> // memcpy
4833 #include <iomanip> // setw, setfill
4834 #include <ios> // hex
4835 #include <iterator> // back_inserter
4836 #include <limits> // numeric_limits
4837 #include <sstream> // stringstream
4838 #include <string> // char_traits, string
4839 #include <utility> // make_pair, move
4840
4841 // #include <nlohmann/detail/input/input_adapters.hpp>
4842
4843 // #include <nlohmann/detail/exceptions.hpp>
4844
4845 // #include <nlohmann/detail/macro_scope.hpp>
4846
4847 // #include <nlohmann/detail/value_t.hpp>
4848
4849
4850 namespace nlohmann
4851 {
4852 namespace detail
4853 {
4854 ///////////////////
4855 // binary reader //
4856 ///////////////////
4857
4858 /*!
4859 @brief deserialization of CBOR and MessagePack values
4860 */
4861 template<typename BasicJsonType>
4862 class binary_reader
4863 {
4864 using number_integer_t = typename BasicJsonType::number_integer_t;
4865 using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
4866 using string_t = typename BasicJsonType::string_t;
4867
4868 public:
4869 /*!
4870 @brief create a binary reader
4871
4872 @param[in] adapter input adapter to read from
4873 */
binary_reader(input_adapter_t adapter)4874 explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
4875 {
4876 assert(ia);
4877 }
4878
4879 /*!
4880 @brief create a JSON value from CBOR input
4881
4882 @param[in] strict whether to expect the input to be consumed completed
4883 @return JSON value created from CBOR input
4884
4885 @throw parse_error.110 if input ended unexpectedly or the end of file was
4886 not reached when @a strict was set to true
4887 @throw parse_error.112 if unsupported byte was read
4888 */
parse_cbor(const bool strict)4889 BasicJsonType parse_cbor(const bool strict)
4890 {
4891 const auto res = parse_cbor_internal();
4892 if (strict)
4893 {
4894 get();
4895 expect_eof();
4896 }
4897 return res;
4898 }
4899
4900 /*!
4901 @brief create a JSON value from MessagePack input
4902
4903 @param[in] strict whether to expect the input to be consumed completed
4904 @return JSON value created from MessagePack input
4905
4906 @throw parse_error.110 if input ended unexpectedly or the end of file was
4907 not reached when @a strict was set to true
4908 @throw parse_error.112 if unsupported byte was read
4909 */
parse_msgpack(const bool strict)4910 BasicJsonType parse_msgpack(const bool strict)
4911 {
4912 const auto res = parse_msgpack_internal();
4913 if (strict)
4914 {
4915 get();
4916 expect_eof();
4917 }
4918 return res;
4919 }
4920
4921 /*!
4922 @brief create a JSON value from UBJSON input
4923
4924 @param[in] strict whether to expect the input to be consumed completed
4925 @return JSON value created from UBJSON input
4926
4927 @throw parse_error.110 if input ended unexpectedly or the end of file was
4928 not reached when @a strict was set to true
4929 @throw parse_error.112 if unsupported byte was read
4930 */
parse_ubjson(const bool strict)4931 BasicJsonType parse_ubjson(const bool strict)
4932 {
4933 const auto res = parse_ubjson_internal();
4934 if (strict)
4935 {
4936 get_ignore_noop();
4937 expect_eof();
4938 }
4939 return res;
4940 }
4941
4942 /*!
4943 @brief determine system byte order
4944
4945 @return true if and only if system's byte order is little endian
4946
4947 @note from http://stackoverflow.com/a/1001328/266378
4948 */
little_endianess(int num=1)4949 static constexpr bool little_endianess(int num = 1) noexcept
4950 {
4951 return (*reinterpret_cast<char*>(&num) == 1);
4952 }
4953
4954 private:
4955 /*!
4956 @param[in] get_char whether a new character should be retrieved from the
4957 input (true, default) or whether the last read
4958 character should be considered instead
4959 */
parse_cbor_internal(const bool get_char=true)4960 BasicJsonType parse_cbor_internal(const bool get_char = true)
4961 {
4962 switch (get_char ? get() : current)
4963 {
4964 // EOF
4965 case std::char_traits<char>::eof():
4966 JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
4967
4968 // Integer 0x00..0x17 (0..23)
4969 case 0x00:
4970 case 0x01:
4971 case 0x02:
4972 case 0x03:
4973 case 0x04:
4974 case 0x05:
4975 case 0x06:
4976 case 0x07:
4977 case 0x08:
4978 case 0x09:
4979 case 0x0A:
4980 case 0x0B:
4981 case 0x0C:
4982 case 0x0D:
4983 case 0x0E:
4984 case 0x0F:
4985 case 0x10:
4986 case 0x11:
4987 case 0x12:
4988 case 0x13:
4989 case 0x14:
4990 case 0x15:
4991 case 0x16:
4992 case 0x17:
4993 return static_cast<number_unsigned_t>(current);
4994
4995 case 0x18: // Unsigned integer (one-byte uint8_t follows)
4996 return get_number<uint8_t>();
4997
4998 case 0x19: // Unsigned integer (two-byte uint16_t follows)
4999 return get_number<uint16_t>();
5000
5001 case 0x1A: // Unsigned integer (four-byte uint32_t follows)
5002 return get_number<uint32_t>();
5003
5004 case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
5005 return get_number<uint64_t>();
5006
5007 // Negative integer -1-0x00..-1-0x17 (-1..-24)
5008 case 0x20:
5009 case 0x21:
5010 case 0x22:
5011 case 0x23:
5012 case 0x24:
5013 case 0x25:
5014 case 0x26:
5015 case 0x27:
5016 case 0x28:
5017 case 0x29:
5018 case 0x2A:
5019 case 0x2B:
5020 case 0x2C:
5021 case 0x2D:
5022 case 0x2E:
5023 case 0x2F:
5024 case 0x30:
5025 case 0x31:
5026 case 0x32:
5027 case 0x33:
5028 case 0x34:
5029 case 0x35:
5030 case 0x36:
5031 case 0x37:
5032 return static_cast<int8_t>(0x20 - 1 - current);
5033
5034 case 0x38: // Negative integer (one-byte uint8_t follows)
5035 {
5036 return static_cast<number_integer_t>(-1) - get_number<uint8_t>();
5037 }
5038
5039 case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
5040 {
5041 return static_cast<number_integer_t>(-1) - get_number<uint16_t>();
5042 }
5043
5044 case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
5045 {
5046 return static_cast<number_integer_t>(-1) - get_number<uint32_t>();
5047 }
5048
5049 case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
5050 {
5051 return static_cast<number_integer_t>(-1) -
5052 static_cast<number_integer_t>(get_number<uint64_t>());
5053 }
5054
5055 // UTF-8 string (0x00..0x17 bytes follow)
5056 case 0x60:
5057 case 0x61:
5058 case 0x62:
5059 case 0x63:
5060 case 0x64:
5061 case 0x65:
5062 case 0x66:
5063 case 0x67:
5064 case 0x68:
5065 case 0x69:
5066 case 0x6A:
5067 case 0x6B:
5068 case 0x6C:
5069 case 0x6D:
5070 case 0x6E:
5071 case 0x6F:
5072 case 0x70:
5073 case 0x71:
5074 case 0x72:
5075 case 0x73:
5076 case 0x74:
5077 case 0x75:
5078 case 0x76:
5079 case 0x77:
5080 case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
5081 case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
5082 case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
5083 case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
5084 case 0x7F: // UTF-8 string (indefinite length)
5085 {
5086 return get_cbor_string();
5087 }
5088
5089 // array (0x00..0x17 data items follow)
5090 case 0x80:
5091 case 0x81:
5092 case 0x82:
5093 case 0x83:
5094 case 0x84:
5095 case 0x85:
5096 case 0x86:
5097 case 0x87:
5098 case 0x88:
5099 case 0x89:
5100 case 0x8A:
5101 case 0x8B:
5102 case 0x8C:
5103 case 0x8D:
5104 case 0x8E:
5105 case 0x8F:
5106 case 0x90:
5107 case 0x91:
5108 case 0x92:
5109 case 0x93:
5110 case 0x94:
5111 case 0x95:
5112 case 0x96:
5113 case 0x97:
5114 {
5115 return get_cbor_array(current & 0x1F);
5116 }
5117
5118 case 0x98: // array (one-byte uint8_t for n follows)
5119 {
5120 return get_cbor_array(get_number<uint8_t>());
5121 }
5122
5123 case 0x99: // array (two-byte uint16_t for n follow)
5124 {
5125 return get_cbor_array(get_number<uint16_t>());
5126 }
5127
5128 case 0x9A: // array (four-byte uint32_t for n follow)
5129 {
5130 return get_cbor_array(get_number<uint32_t>());
5131 }
5132
5133 case 0x9B: // array (eight-byte uint64_t for n follow)
5134 {
5135 return get_cbor_array(get_number<uint64_t>());
5136 }
5137
5138 case 0x9F: // array (indefinite length)
5139 {
5140 BasicJsonType result = value_t::array;
5141 while (get() != 0xFF)
5142 {
5143 result.push_back(parse_cbor_internal(false));
5144 }
5145 return result;
5146 }
5147
5148 // map (0x00..0x17 pairs of data items follow)
5149 case 0xA0:
5150 case 0xA1:
5151 case 0xA2:
5152 case 0xA3:
5153 case 0xA4:
5154 case 0xA5:
5155 case 0xA6:
5156 case 0xA7:
5157 case 0xA8:
5158 case 0xA9:
5159 case 0xAA:
5160 case 0xAB:
5161 case 0xAC:
5162 case 0xAD:
5163 case 0xAE:
5164 case 0xAF:
5165 case 0xB0:
5166 case 0xB1:
5167 case 0xB2:
5168 case 0xB3:
5169 case 0xB4:
5170 case 0xB5:
5171 case 0xB6:
5172 case 0xB7:
5173 {
5174 return get_cbor_object(current & 0x1F);
5175 }
5176
5177 case 0xB8: // map (one-byte uint8_t for n follows)
5178 {
5179 return get_cbor_object(get_number<uint8_t>());
5180 }
5181
5182 case 0xB9: // map (two-byte uint16_t for n follow)
5183 {
5184 return get_cbor_object(get_number<uint16_t>());
5185 }
5186
5187 case 0xBA: // map (four-byte uint32_t for n follow)
5188 {
5189 return get_cbor_object(get_number<uint32_t>());
5190 }
5191
5192 case 0xBB: // map (eight-byte uint64_t for n follow)
5193 {
5194 return get_cbor_object(get_number<uint64_t>());
5195 }
5196
5197 case 0xBF: // map (indefinite length)
5198 {
5199 BasicJsonType result = value_t::object;
5200 while (get() != 0xFF)
5201 {
5202 auto key = get_cbor_string();
5203 result[key] = parse_cbor_internal();
5204 }
5205 return result;
5206 }
5207
5208 case 0xF4: // false
5209 {
5210 return false;
5211 }
5212
5213 case 0xF5: // true
5214 {
5215 return true;
5216 }
5217
5218 case 0xF6: // null
5219 {
5220 return value_t::null;
5221 }
5222
5223 case 0xF9: // Half-Precision Float (two-byte IEEE 754)
5224 {
5225 const int byte1 = get();
5226 unexpect_eof();
5227 const int byte2 = get();
5228 unexpect_eof();
5229
5230 // code from RFC 7049, Appendix D, Figure 3:
5231 // As half-precision floating-point numbers were only added
5232 // to IEEE 754 in 2008, today's programming platforms often
5233 // still only have limited support for them. It is very
5234 // easy to include at least decoding support for them even
5235 // without such support. An example of a small decoder for
5236 // half-precision floating-point numbers in the C language
5237 // is shown in Fig. 3.
5238 const int half = (byte1 << 8) + byte2;
5239 const int exp = (half >> 10) & 0x1F;
5240 const int mant = half & 0x3FF;
5241 double val;
5242 if (exp == 0)
5243 {
5244 val = std::ldexp(mant, -24);
5245 }
5246 else if (exp != 31)
5247 {
5248 val = std::ldexp(mant + 1024, exp - 25);
5249 }
5250 else
5251 {
5252 val = (mant == 0) ? std::numeric_limits<double>::infinity()
5253 : std::numeric_limits<double>::quiet_NaN();
5254 }
5255 return (half & 0x8000) != 0 ? -val : val;
5256 }
5257
5258 case 0xFA: // Single-Precision Float (four-byte IEEE 754)
5259 {
5260 return get_number<float>();
5261 }
5262
5263 case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
5264 {
5265 return get_number<double>();
5266 }
5267
5268 default: // anything else (0xFF is handled inside the other types)
5269 {
5270 std::stringstream ss;
5271 ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5272 JSON_THROW(parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + ss.str()));
5273 }
5274 }
5275 }
5276
parse_msgpack_internal()5277 BasicJsonType parse_msgpack_internal()
5278 {
5279 switch (get())
5280 {
5281 // EOF
5282 case std::char_traits<char>::eof():
5283 JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
5284
5285 // positive fixint
5286 case 0x00:
5287 case 0x01:
5288 case 0x02:
5289 case 0x03:
5290 case 0x04:
5291 case 0x05:
5292 case 0x06:
5293 case 0x07:
5294 case 0x08:
5295 case 0x09:
5296 case 0x0A:
5297 case 0x0B:
5298 case 0x0C:
5299 case 0x0D:
5300 case 0x0E:
5301 case 0x0F:
5302 case 0x10:
5303 case 0x11:
5304 case 0x12:
5305 case 0x13:
5306 case 0x14:
5307 case 0x15:
5308 case 0x16:
5309 case 0x17:
5310 case 0x18:
5311 case 0x19:
5312 case 0x1A:
5313 case 0x1B:
5314 case 0x1C:
5315 case 0x1D:
5316 case 0x1E:
5317 case 0x1F:
5318 case 0x20:
5319 case 0x21:
5320 case 0x22:
5321 case 0x23:
5322 case 0x24:
5323 case 0x25:
5324 case 0x26:
5325 case 0x27:
5326 case 0x28:
5327 case 0x29:
5328 case 0x2A:
5329 case 0x2B:
5330 case 0x2C:
5331 case 0x2D:
5332 case 0x2E:
5333 case 0x2F:
5334 case 0x30:
5335 case 0x31:
5336 case 0x32:
5337 case 0x33:
5338 case 0x34:
5339 case 0x35:
5340 case 0x36:
5341 case 0x37:
5342 case 0x38:
5343 case 0x39:
5344 case 0x3A:
5345 case 0x3B:
5346 case 0x3C:
5347 case 0x3D:
5348 case 0x3E:
5349 case 0x3F:
5350 case 0x40:
5351 case 0x41:
5352 case 0x42:
5353 case 0x43:
5354 case 0x44:
5355 case 0x45:
5356 case 0x46:
5357 case 0x47:
5358 case 0x48:
5359 case 0x49:
5360 case 0x4A:
5361 case 0x4B:
5362 case 0x4C:
5363 case 0x4D:
5364 case 0x4E:
5365 case 0x4F:
5366 case 0x50:
5367 case 0x51:
5368 case 0x52:
5369 case 0x53:
5370 case 0x54:
5371 case 0x55:
5372 case 0x56:
5373 case 0x57:
5374 case 0x58:
5375 case 0x59:
5376 case 0x5A:
5377 case 0x5B:
5378 case 0x5C:
5379 case 0x5D:
5380 case 0x5E:
5381 case 0x5F:
5382 case 0x60:
5383 case 0x61:
5384 case 0x62:
5385 case 0x63:
5386 case 0x64:
5387 case 0x65:
5388 case 0x66:
5389 case 0x67:
5390 case 0x68:
5391 case 0x69:
5392 case 0x6A:
5393 case 0x6B:
5394 case 0x6C:
5395 case 0x6D:
5396 case 0x6E:
5397 case 0x6F:
5398 case 0x70:
5399 case 0x71:
5400 case 0x72:
5401 case 0x73:
5402 case 0x74:
5403 case 0x75:
5404 case 0x76:
5405 case 0x77:
5406 case 0x78:
5407 case 0x79:
5408 case 0x7A:
5409 case 0x7B:
5410 case 0x7C:
5411 case 0x7D:
5412 case 0x7E:
5413 case 0x7F:
5414 return static_cast<number_unsigned_t>(current);
5415
5416 // fixmap
5417 case 0x80:
5418 case 0x81:
5419 case 0x82:
5420 case 0x83:
5421 case 0x84:
5422 case 0x85:
5423 case 0x86:
5424 case 0x87:
5425 case 0x88:
5426 case 0x89:
5427 case 0x8A:
5428 case 0x8B:
5429 case 0x8C:
5430 case 0x8D:
5431 case 0x8E:
5432 case 0x8F:
5433 {
5434 return get_msgpack_object(current & 0x0F);
5435 }
5436
5437 // fixarray
5438 case 0x90:
5439 case 0x91:
5440 case 0x92:
5441 case 0x93:
5442 case 0x94:
5443 case 0x95:
5444 case 0x96:
5445 case 0x97:
5446 case 0x98:
5447 case 0x99:
5448 case 0x9A:
5449 case 0x9B:
5450 case 0x9C:
5451 case 0x9D:
5452 case 0x9E:
5453 case 0x9F:
5454 {
5455 return get_msgpack_array(current & 0x0F);
5456 }
5457
5458 // fixstr
5459 case 0xA0:
5460 case 0xA1:
5461 case 0xA2:
5462 case 0xA3:
5463 case 0xA4:
5464 case 0xA5:
5465 case 0xA6:
5466 case 0xA7:
5467 case 0xA8:
5468 case 0xA9:
5469 case 0xAA:
5470 case 0xAB:
5471 case 0xAC:
5472 case 0xAD:
5473 case 0xAE:
5474 case 0xAF:
5475 case 0xB0:
5476 case 0xB1:
5477 case 0xB2:
5478 case 0xB3:
5479 case 0xB4:
5480 case 0xB5:
5481 case 0xB6:
5482 case 0xB7:
5483 case 0xB8:
5484 case 0xB9:
5485 case 0xBA:
5486 case 0xBB:
5487 case 0xBC:
5488 case 0xBD:
5489 case 0xBE:
5490 case 0xBF:
5491 return get_msgpack_string();
5492
5493 case 0xC0: // nil
5494 return value_t::null;
5495
5496 case 0xC2: // false
5497 return false;
5498
5499 case 0xC3: // true
5500 return true;
5501
5502 case 0xCA: // float 32
5503 return get_number<float>();
5504
5505 case 0xCB: // float 64
5506 return get_number<double>();
5507
5508 case 0xCC: // uint 8
5509 return get_number<uint8_t>();
5510
5511 case 0xCD: // uint 16
5512 return get_number<uint16_t>();
5513
5514 case 0xCE: // uint 32
5515 return get_number<uint32_t>();
5516
5517 case 0xCF: // uint 64
5518 return get_number<uint64_t>();
5519
5520 case 0xD0: // int 8
5521 return get_number<int8_t>();
5522
5523 case 0xD1: // int 16
5524 return get_number<int16_t>();
5525
5526 case 0xD2: // int 32
5527 return get_number<int32_t>();
5528
5529 case 0xD3: // int 64
5530 return get_number<int64_t>();
5531
5532 case 0xD9: // str 8
5533 case 0xDA: // str 16
5534 case 0xDB: // str 32
5535 return get_msgpack_string();
5536
5537 case 0xDC: // array 16
5538 {
5539 return get_msgpack_array(get_number<uint16_t>());
5540 }
5541
5542 case 0xDD: // array 32
5543 {
5544 return get_msgpack_array(get_number<uint32_t>());
5545 }
5546
5547 case 0xDE: // map 16
5548 {
5549 return get_msgpack_object(get_number<uint16_t>());
5550 }
5551
5552 case 0xDF: // map 32
5553 {
5554 return get_msgpack_object(get_number<uint32_t>());
5555 }
5556
5557 // positive fixint
5558 case 0xE0:
5559 case 0xE1:
5560 case 0xE2:
5561 case 0xE3:
5562 case 0xE4:
5563 case 0xE5:
5564 case 0xE6:
5565 case 0xE7:
5566 case 0xE8:
5567 case 0xE9:
5568 case 0xEA:
5569 case 0xEB:
5570 case 0xEC:
5571 case 0xED:
5572 case 0xEE:
5573 case 0xEF:
5574 case 0xF0:
5575 case 0xF1:
5576 case 0xF2:
5577 case 0xF3:
5578 case 0xF4:
5579 case 0xF5:
5580 case 0xF6:
5581 case 0xF7:
5582 case 0xF8:
5583 case 0xF9:
5584 case 0xFA:
5585 case 0xFB:
5586 case 0xFC:
5587 case 0xFD:
5588 case 0xFE:
5589 case 0xFF:
5590 return static_cast<int8_t>(current);
5591
5592 default: // anything else
5593 {
5594 std::stringstream ss;
5595 ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5596 JSON_THROW(parse_error::create(112, chars_read,
5597 "error reading MessagePack; last byte: 0x" + ss.str()));
5598 }
5599 }
5600 }
5601
5602 /*!
5603 @param[in] get_char whether a new character should be retrieved from the
5604 input (true, default) or whether the last read
5605 character should be considered instead
5606 */
parse_ubjson_internal(const bool get_char=true)5607 BasicJsonType parse_ubjson_internal(const bool get_char = true)
5608 {
5609 return get_ubjson_value(get_char ? get_ignore_noop() : current);
5610 }
5611
5612 /*!
5613 @brief get next character from the input
5614
5615 This function provides the interface to the used input adapter. It does
5616 not throw in case the input reached EOF, but returns a -'ve valued
5617 `std::char_traits<char>::eof()` in that case.
5618
5619 @return character read from the input
5620 */
get()5621 int get()
5622 {
5623 ++chars_read;
5624 return (current = ia->get_character());
5625 }
5626
5627 /*!
5628 @return character read from the input after ignoring all 'N' entries
5629 */
get_ignore_noop()5630 int get_ignore_noop()
5631 {
5632 do
5633 {
5634 get();
5635 }
5636 while (current == 'N');
5637
5638 return current;
5639 }
5640
5641 /*
5642 @brief read a number from the input
5643
5644 @tparam NumberType the type of the number
5645
5646 @return number of type @a NumberType
5647
5648 @note This function needs to respect the system's endianess, because
5649 bytes in CBOR and MessagePack are stored in network order (big
5650 endian) and therefore need reordering on little endian systems.
5651
5652 @throw parse_error.110 if input has less than `sizeof(NumberType)` bytes
5653 */
get_number()5654 template<typename NumberType> NumberType get_number()
5655 {
5656 // step 1: read input into array with system's byte order
5657 std::array<uint8_t, sizeof(NumberType)> vec;
5658 for (std::size_t i = 0; i < sizeof(NumberType); ++i)
5659 {
5660 get();
5661 unexpect_eof();
5662
5663 // reverse byte order prior to conversion if necessary
5664 if (is_little_endian)
5665 {
5666 vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);
5667 }
5668 else
5669 {
5670 vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE
5671 }
5672 }
5673
5674 // step 2: convert array into number of type T and return
5675 NumberType result;
5676 std::memcpy(&result, vec.data(), sizeof(NumberType));
5677 return result;
5678 }
5679
5680 /*!
5681 @brief create a string by reading characters from the input
5682
5683 @param[in] len number of bytes to read
5684
5685 @note We can not reserve @a len bytes for the result, because @a len
5686 may be too large. Usually, @ref unexpect_eof() detects the end of
5687 the input before we run out of string memory.
5688
5689 @return string created by reading @a len bytes
5690
5691 @throw parse_error.110 if input has less than @a len bytes
5692 */
5693 template<typename NumberType>
get_string(const NumberType len)5694 string_t get_string(const NumberType len)
5695 {
5696 string_t result;
5697 std::generate_n(std::back_inserter(result), len, [this]()
5698 {
5699 get();
5700 unexpect_eof();
5701 return static_cast<char>(current);
5702 });
5703 return result;
5704 }
5705
5706 /*!
5707 @brief reads a CBOR string
5708
5709 This function first reads starting bytes to determine the expected
5710 string length and then copies this number of bytes into a string.
5711 Additionally, CBOR's strings with indefinite lengths are supported.
5712
5713 @return string
5714
5715 @throw parse_error.110 if input ended
5716 @throw parse_error.113 if an unexpected byte is read
5717 */
get_cbor_string()5718 string_t get_cbor_string()
5719 {
5720 unexpect_eof();
5721
5722 switch (current)
5723 {
5724 // UTF-8 string (0x00..0x17 bytes follow)
5725 case 0x60:
5726 case 0x61:
5727 case 0x62:
5728 case 0x63:
5729 case 0x64:
5730 case 0x65:
5731 case 0x66:
5732 case 0x67:
5733 case 0x68:
5734 case 0x69:
5735 case 0x6A:
5736 case 0x6B:
5737 case 0x6C:
5738 case 0x6D:
5739 case 0x6E:
5740 case 0x6F:
5741 case 0x70:
5742 case 0x71:
5743 case 0x72:
5744 case 0x73:
5745 case 0x74:
5746 case 0x75:
5747 case 0x76:
5748 case 0x77:
5749 {
5750 return get_string(current & 0x1F);
5751 }
5752
5753 case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
5754 {
5755 return get_string(get_number<uint8_t>());
5756 }
5757
5758 case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
5759 {
5760 return get_string(get_number<uint16_t>());
5761 }
5762
5763 case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
5764 {
5765 return get_string(get_number<uint32_t>());
5766 }
5767
5768 case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
5769 {
5770 return get_string(get_number<uint64_t>());
5771 }
5772
5773 case 0x7F: // UTF-8 string (indefinite length)
5774 {
5775 string_t result;
5776 while (get() != 0xFF)
5777 {
5778 result.append(get_cbor_string());
5779 }
5780 return result;
5781 }
5782
5783 default:
5784 {
5785 std::stringstream ss;
5786 ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5787 JSON_THROW(parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + ss.str()));
5788 }
5789 }
5790 }
5791
5792 template<typename NumberType>
get_cbor_array(const NumberType len)5793 BasicJsonType get_cbor_array(const NumberType len)
5794 {
5795 BasicJsonType result = value_t::array;
5796 std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
5797 {
5798 return parse_cbor_internal();
5799 });
5800 return result;
5801 }
5802
5803 template<typename NumberType>
get_cbor_object(const NumberType len)5804 BasicJsonType get_cbor_object(const NumberType len)
5805 {
5806 BasicJsonType result = value_t::object;
5807 std::generate_n(std::inserter(*result.m_value.object,
5808 result.m_value.object->end()),
5809 len, [this]()
5810 {
5811 get();
5812 auto key = get_cbor_string();
5813 auto val = parse_cbor_internal();
5814 return std::make_pair(std::move(key), std::move(val));
5815 });
5816 return result;
5817 }
5818
5819 /*!
5820 @brief reads a MessagePack string
5821
5822 This function first reads starting bytes to determine the expected
5823 string length and then copies this number of bytes into a string.
5824
5825 @return string
5826
5827 @throw parse_error.110 if input ended
5828 @throw parse_error.113 if an unexpected byte is read
5829 */
get_msgpack_string()5830 string_t get_msgpack_string()
5831 {
5832 unexpect_eof();
5833
5834 switch (current)
5835 {
5836 // fixstr
5837 case 0xA0:
5838 case 0xA1:
5839 case 0xA2:
5840 case 0xA3:
5841 case 0xA4:
5842 case 0xA5:
5843 case 0xA6:
5844 case 0xA7:
5845 case 0xA8:
5846 case 0xA9:
5847 case 0xAA:
5848 case 0xAB:
5849 case 0xAC:
5850 case 0xAD:
5851 case 0xAE:
5852 case 0xAF:
5853 case 0xB0:
5854 case 0xB1:
5855 case 0xB2:
5856 case 0xB3:
5857 case 0xB4:
5858 case 0xB5:
5859 case 0xB6:
5860 case 0xB7:
5861 case 0xB8:
5862 case 0xB9:
5863 case 0xBA:
5864 case 0xBB:
5865 case 0xBC:
5866 case 0xBD:
5867 case 0xBE:
5868 case 0xBF:
5869 {
5870 return get_string(current & 0x1F);
5871 }
5872
5873 case 0xD9: // str 8
5874 {
5875 return get_string(get_number<uint8_t>());
5876 }
5877
5878 case 0xDA: // str 16
5879 {
5880 return get_string(get_number<uint16_t>());
5881 }
5882
5883 case 0xDB: // str 32
5884 {
5885 return get_string(get_number<uint32_t>());
5886 }
5887
5888 default:
5889 {
5890 std::stringstream ss;
5891 ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5892 JSON_THROW(parse_error::create(113, chars_read,
5893 "expected a MessagePack string; last byte: 0x" + ss.str()));
5894 }
5895 }
5896 }
5897
5898 template<typename NumberType>
get_msgpack_array(const NumberType len)5899 BasicJsonType get_msgpack_array(const NumberType len)
5900 {
5901 BasicJsonType result = value_t::array;
5902 std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
5903 {
5904 return parse_msgpack_internal();
5905 });
5906 return result;
5907 }
5908
5909 template<typename NumberType>
get_msgpack_object(const NumberType len)5910 BasicJsonType get_msgpack_object(const NumberType len)
5911 {
5912 BasicJsonType result = value_t::object;
5913 std::generate_n(std::inserter(*result.m_value.object,
5914 result.m_value.object->end()),
5915 len, [this]()
5916 {
5917 get();
5918 auto key = get_msgpack_string();
5919 auto val = parse_msgpack_internal();
5920 return std::make_pair(std::move(key), std::move(val));
5921 });
5922 return result;
5923 }
5924
5925 /*!
5926 @brief reads a UBJSON string
5927
5928 This function is either called after reading the 'S' byte explicitly
5929 indicating a string, or in case of an object key where the 'S' byte can be
5930 left out.
5931
5932 @param[in] get_char whether a new character should be retrieved from the
5933 input (true, default) or whether the last read
5934 character should be considered instead
5935
5936 @return string
5937
5938 @throw parse_error.110 if input ended
5939 @throw parse_error.113 if an unexpected byte is read
5940 */
get_ubjson_string(const bool get_char=true)5941 string_t get_ubjson_string(const bool get_char = true)
5942 {
5943 if (get_char)
5944 {
5945 get(); // TODO: may we ignore N here?
5946 }
5947
5948 unexpect_eof();
5949
5950 switch (current)
5951 {
5952 case 'U':
5953 return get_string(get_number<uint8_t>());
5954 case 'i':
5955 return get_string(get_number<int8_t>());
5956 case 'I':
5957 return get_string(get_number<int16_t>());
5958 case 'l':
5959 return get_string(get_number<int32_t>());
5960 case 'L':
5961 return get_string(get_number<int64_t>());
5962 default:
5963 std::stringstream ss;
5964 ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5965 JSON_THROW(parse_error::create(113, chars_read,
5966 "expected a UBJSON string; last byte: 0x" + ss.str()));
5967 }
5968 }
5969
5970 /*!
5971 @brief determine the type and size for a container
5972
5973 In the optimized UBJSON format, a type and a size can be provided to allow
5974 for a more compact representation.
5975
5976 @return pair of the size and the type
5977 */
get_ubjson_size_type()5978 std::pair<std::size_t, int> get_ubjson_size_type()
5979 {
5980 std::size_t sz = string_t::npos;
5981 int tc = 0;
5982
5983 get_ignore_noop();
5984
5985 if (current == '$')
5986 {
5987 tc = get(); // must not ignore 'N', because 'N' maybe the type
5988 unexpect_eof();
5989
5990 get_ignore_noop();
5991 if (current != '#')
5992 {
5993 std::stringstream ss;
5994 ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5995 JSON_THROW(parse_error::create(112, chars_read,
5996 "expected '#' after UBJSON type information; last byte: 0x" + ss.str()));
5997 }
5998 sz = parse_ubjson_internal();
5999 }
6000 else if (current == '#')
6001 {
6002 sz = parse_ubjson_internal();
6003 }
6004
6005 return std::make_pair(sz, tc);
6006 }
6007
get_ubjson_value(const int prefix)6008 BasicJsonType get_ubjson_value(const int prefix)
6009 {
6010 switch (prefix)
6011 {
6012 case std::char_traits<char>::eof(): // EOF
6013 JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
6014
6015 case 'T': // true
6016 return true;
6017 case 'F': // false
6018 return false;
6019
6020 case 'Z': // null
6021 return nullptr;
6022
6023 case 'U':
6024 return get_number<uint8_t>();
6025 case 'i':
6026 return get_number<int8_t>();
6027 case 'I':
6028 return get_number<int16_t>();
6029 case 'l':
6030 return get_number<int32_t>();
6031 case 'L':
6032 return get_number<int64_t>();
6033 case 'd':
6034 return get_number<float>();
6035 case 'D':
6036 return get_number<double>();
6037
6038 case 'C': // char
6039 {
6040 get();
6041 unexpect_eof();
6042 if (JSON_UNLIKELY(current > 127))
6043 {
6044 std::stringstream ss;
6045 ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
6046 JSON_THROW(parse_error::create(113, chars_read,
6047 "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + ss.str()));
6048 }
6049 return string_t(1, static_cast<char>(current));
6050 }
6051
6052 case 'S': // string
6053 return get_ubjson_string();
6054
6055 case '[': // array
6056 return get_ubjson_array();
6057
6058 case '{': // object
6059 return get_ubjson_object();
6060
6061 default: // anything else
6062 std::stringstream ss;
6063 ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
6064 JSON_THROW(parse_error::create(112, chars_read,
6065 "error reading UBJSON; last byte: 0x" + ss.str()));
6066 }
6067 }
6068
get_ubjson_array()6069 BasicJsonType get_ubjson_array()
6070 {
6071 BasicJsonType result = value_t::array;
6072 const auto size_and_type = get_ubjson_size_type();
6073
6074 if (size_and_type.first != string_t::npos)
6075 {
6076 if (JSON_UNLIKELY(size_and_type.first > result.max_size()))
6077 {
6078 JSON_THROW(out_of_range::create(408,
6079 "excessive array size: " + std::to_string(size_and_type.first)));
6080 }
6081
6082 if (size_and_type.second != 0)
6083 {
6084 if (size_and_type.second != 'N')
6085 {
6086 std::generate_n(std::back_inserter(*result.m_value.array),
6087 size_and_type.first, [this, size_and_type]()
6088 {
6089 return get_ubjson_value(size_and_type.second);
6090 });
6091 }
6092 }
6093 else
6094 {
6095 std::generate_n(std::back_inserter(*result.m_value.array),
6096 size_and_type.first, [this]()
6097 {
6098 return parse_ubjson_internal();
6099 });
6100 }
6101 }
6102 else
6103 {
6104 while (current != ']')
6105 {
6106 result.push_back(parse_ubjson_internal(false));
6107 get_ignore_noop();
6108 }
6109 }
6110
6111 return result;
6112 }
6113
get_ubjson_object()6114 BasicJsonType get_ubjson_object()
6115 {
6116 BasicJsonType result = value_t::object;
6117 const auto size_and_type = get_ubjson_size_type();
6118
6119 if (size_and_type.first != string_t::npos)
6120 {
6121 if (JSON_UNLIKELY(size_and_type.first > result.max_size()))
6122 {
6123 JSON_THROW(out_of_range::create(408,
6124 "excessive object size: " + std::to_string(size_and_type.first)));
6125 }
6126
6127 if (size_and_type.second != 0)
6128 {
6129 std::generate_n(std::inserter(*result.m_value.object,
6130 result.m_value.object->end()),
6131 size_and_type.first, [this, size_and_type]()
6132 {
6133 auto key = get_ubjson_string();
6134 auto val = get_ubjson_value(size_and_type.second);
6135 return std::make_pair(std::move(key), std::move(val));
6136 });
6137 }
6138 else
6139 {
6140 std::generate_n(std::inserter(*result.m_value.object,
6141 result.m_value.object->end()),
6142 size_and_type.first, [this]()
6143 {
6144 auto key = get_ubjson_string();
6145 auto val = parse_ubjson_internal();
6146 return std::make_pair(std::move(key), std::move(val));
6147 });
6148 }
6149 }
6150 else
6151 {
6152 while (current != '}')
6153 {
6154 auto key = get_ubjson_string(false);
6155 result[std::move(key)] = parse_ubjson_internal();
6156 get_ignore_noop();
6157 }
6158 }
6159
6160 return result;
6161 }
6162
6163 /*!
6164 @brief throw if end of input is not reached
6165 @throw parse_error.110 if input not ended
6166 */
expect_eof() const6167 void expect_eof() const
6168 {
6169 if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
6170 {
6171 JSON_THROW(parse_error::create(110, chars_read, "expected end of input"));
6172 }
6173 }
6174
6175 /*!
6176 @briefthrow if end of input is reached
6177 @throw parse_error.110 if input ended
6178 */
unexpect_eof() const6179 void unexpect_eof() const
6180 {
6181 if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
6182 {
6183 JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
6184 }
6185 }
6186
6187 private:
6188 /// input adapter
6189 input_adapter_t ia = nullptr;
6190
6191 /// the current character
6192 int current = std::char_traits<char>::eof();
6193
6194 /// the number of characters read
6195 std::size_t chars_read = 0;
6196
6197 /// whether we can assume little endianess
6198 const bool is_little_endian = little_endianess();
6199 };
6200 }
6201 }
6202
6203 // #include <nlohmann/detail/output/binary_writer.hpp>
6204
6205
6206 #include <algorithm> // reverse
6207 #include <array> // array
6208 #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
6209 #include <cstring> // memcpy
6210 #include <limits> // numeric_limits
6211
6212 // #include <nlohmann/detail/input/binary_reader.hpp>
6213
6214 // #include <nlohmann/detail/output/output_adapters.hpp>
6215
6216
6217 namespace nlohmann
6218 {
6219 namespace detail
6220 {
6221 ///////////////////
6222 // binary writer //
6223 ///////////////////
6224
6225 /*!
6226 @brief serialization to CBOR and MessagePack values
6227 */
6228 template<typename BasicJsonType, typename CharType>
6229 class binary_writer
6230 {
6231 public:
6232 /*!
6233 @brief create a binary writer
6234
6235 @param[in] adapter output adapter to write to
6236 */
binary_writer(output_adapter_t<CharType> adapter)6237 explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
6238 {
6239 assert(oa);
6240 }
6241
6242 /*!
6243 @brief[in] j JSON value to serialize
6244 */
write_cbor(const BasicJsonType & j)6245 void write_cbor(const BasicJsonType& j)
6246 {
6247 switch (j.type())
6248 {
6249 case value_t::null:
6250 {
6251 oa->write_character(static_cast<CharType>(0xF6));
6252 break;
6253 }
6254
6255 case value_t::boolean:
6256 {
6257 oa->write_character(j.m_value.boolean
6258 ? static_cast<CharType>(0xF5)
6259 : static_cast<CharType>(0xF4));
6260 break;
6261 }
6262
6263 case value_t::number_integer:
6264 {
6265 if (j.m_value.number_integer >= 0)
6266 {
6267 // CBOR does not differentiate between positive signed
6268 // integers and unsigned integers. Therefore, we used the
6269 // code from the value_t::number_unsigned case here.
6270 if (j.m_value.number_integer <= 0x17)
6271 {
6272 write_number(static_cast<uint8_t>(j.m_value.number_integer));
6273 }
6274 else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
6275 {
6276 oa->write_character(static_cast<CharType>(0x18));
6277 write_number(static_cast<uint8_t>(j.m_value.number_integer));
6278 }
6279 else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
6280 {
6281 oa->write_character(static_cast<CharType>(0x19));
6282 write_number(static_cast<uint16_t>(j.m_value.number_integer));
6283 }
6284 else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
6285 {
6286 oa->write_character(static_cast<CharType>(0x1A));
6287 write_number(static_cast<uint32_t>(j.m_value.number_integer));
6288 }
6289 else
6290 {
6291 oa->write_character(static_cast<CharType>(0x1B));
6292 write_number(static_cast<uint64_t>(j.m_value.number_integer));
6293 }
6294 }
6295 else
6296 {
6297 // The conversions below encode the sign in the first
6298 // byte, and the value is converted to a positive number.
6299 const auto positive_number = -1 - j.m_value.number_integer;
6300 if (j.m_value.number_integer >= -24)
6301 {
6302 write_number(static_cast<uint8_t>(0x20 + positive_number));
6303 }
6304 else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
6305 {
6306 oa->write_character(static_cast<CharType>(0x38));
6307 write_number(static_cast<uint8_t>(positive_number));
6308 }
6309 else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
6310 {
6311 oa->write_character(static_cast<CharType>(0x39));
6312 write_number(static_cast<uint16_t>(positive_number));
6313 }
6314 else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
6315 {
6316 oa->write_character(static_cast<CharType>(0x3A));
6317 write_number(static_cast<uint32_t>(positive_number));
6318 }
6319 else
6320 {
6321 oa->write_character(static_cast<CharType>(0x3B));
6322 write_number(static_cast<uint64_t>(positive_number));
6323 }
6324 }
6325 break;
6326 }
6327
6328 case value_t::number_unsigned:
6329 {
6330 if (j.m_value.number_unsigned <= 0x17)
6331 {
6332 write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
6333 }
6334 else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
6335 {
6336 oa->write_character(static_cast<CharType>(0x18));
6337 write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
6338 }
6339 else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
6340 {
6341 oa->write_character(static_cast<CharType>(0x19));
6342 write_number(static_cast<uint16_t>(j.m_value.number_unsigned));
6343 }
6344 else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
6345 {
6346 oa->write_character(static_cast<CharType>(0x1A));
6347 write_number(static_cast<uint32_t>(j.m_value.number_unsigned));
6348 }
6349 else
6350 {
6351 oa->write_character(static_cast<CharType>(0x1B));
6352 write_number(static_cast<uint64_t>(j.m_value.number_unsigned));
6353 }
6354 break;
6355 }
6356
6357 case value_t::number_float: // Double-Precision Float
6358 {
6359 oa->write_character(static_cast<CharType>(0xFB));
6360 write_number(j.m_value.number_float);
6361 break;
6362 }
6363
6364 case value_t::string:
6365 {
6366 // step 1: write control byte and the string length
6367 const auto N = j.m_value.string->size();
6368 if (N <= 0x17)
6369 {
6370 write_number(static_cast<uint8_t>(0x60 + N));
6371 }
6372 else if (N <= (std::numeric_limits<uint8_t>::max)())
6373 {
6374 oa->write_character(static_cast<CharType>(0x78));
6375 write_number(static_cast<uint8_t>(N));
6376 }
6377 else if (N <= (std::numeric_limits<uint16_t>::max)())
6378 {
6379 oa->write_character(static_cast<CharType>(0x79));
6380 write_number(static_cast<uint16_t>(N));
6381 }
6382 else if (N <= (std::numeric_limits<uint32_t>::max)())
6383 {
6384 oa->write_character(static_cast<CharType>(0x7A));
6385 write_number(static_cast<uint32_t>(N));
6386 }
6387 // LCOV_EXCL_START
6388 else if (N <= (std::numeric_limits<uint64_t>::max)())
6389 {
6390 oa->write_character(static_cast<CharType>(0x7B));
6391 write_number(static_cast<uint64_t>(N));
6392 }
6393 // LCOV_EXCL_STOP
6394
6395 // step 2: write the string
6396 oa->write_characters(
6397 reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
6398 j.m_value.string->size());
6399 break;
6400 }
6401
6402 case value_t::array:
6403 {
6404 // step 1: write control byte and the array size
6405 const auto N = j.m_value.array->size();
6406 if (N <= 0x17)
6407 {
6408 write_number(static_cast<uint8_t>(0x80 + N));
6409 }
6410 else if (N <= (std::numeric_limits<uint8_t>::max)())
6411 {
6412 oa->write_character(static_cast<CharType>(0x98));
6413 write_number(static_cast<uint8_t>(N));
6414 }
6415 else if (N <= (std::numeric_limits<uint16_t>::max)())
6416 {
6417 oa->write_character(static_cast<CharType>(0x99));
6418 write_number(static_cast<uint16_t>(N));
6419 }
6420 else if (N <= (std::numeric_limits<uint32_t>::max)())
6421 {
6422 oa->write_character(static_cast<CharType>(0x9A));
6423 write_number(static_cast<uint32_t>(N));
6424 }
6425 // LCOV_EXCL_START
6426 else if (N <= (std::numeric_limits<uint64_t>::max)())
6427 {
6428 oa->write_character(static_cast<CharType>(0x9B));
6429 write_number(static_cast<uint64_t>(N));
6430 }
6431 // LCOV_EXCL_STOP
6432
6433 // step 2: write each element
6434 for (const auto& el : *j.m_value.array)
6435 {
6436 write_cbor(el);
6437 }
6438 break;
6439 }
6440
6441 case value_t::object:
6442 {
6443 // step 1: write control byte and the object size
6444 const auto N = j.m_value.object->size();
6445 if (N <= 0x17)
6446 {
6447 write_number(static_cast<uint8_t>(0xA0 + N));
6448 }
6449 else if (N <= (std::numeric_limits<uint8_t>::max)())
6450 {
6451 oa->write_character(static_cast<CharType>(0xB8));
6452 write_number(static_cast<uint8_t>(N));
6453 }
6454 else if (N <= (std::numeric_limits<uint16_t>::max)())
6455 {
6456 oa->write_character(static_cast<CharType>(0xB9));
6457 write_number(static_cast<uint16_t>(N));
6458 }
6459 else if (N <= (std::numeric_limits<uint32_t>::max)())
6460 {
6461 oa->write_character(static_cast<CharType>(0xBA));
6462 write_number(static_cast<uint32_t>(N));
6463 }
6464 // LCOV_EXCL_START
6465 else if (N <= (std::numeric_limits<uint64_t>::max)())
6466 {
6467 oa->write_character(static_cast<CharType>(0xBB));
6468 write_number(static_cast<uint64_t>(N));
6469 }
6470 // LCOV_EXCL_STOP
6471
6472 // step 2: write each element
6473 for (const auto& el : *j.m_value.object)
6474 {
6475 write_cbor(el.first);
6476 write_cbor(el.second);
6477 }
6478 break;
6479 }
6480
6481 default:
6482 break;
6483 }
6484 }
6485
6486 /*!
6487 @brief[in] j JSON value to serialize
6488 */
write_msgpack(const BasicJsonType & j)6489 void write_msgpack(const BasicJsonType& j)
6490 {
6491 switch (j.type())
6492 {
6493 case value_t::null: // nil
6494 {
6495 oa->write_character(static_cast<CharType>(0xC0));
6496 break;
6497 }
6498
6499 case value_t::boolean: // true and false
6500 {
6501 oa->write_character(j.m_value.boolean
6502 ? static_cast<CharType>(0xC3)
6503 : static_cast<CharType>(0xC2));
6504 break;
6505 }
6506
6507 case value_t::number_integer:
6508 {
6509 if (j.m_value.number_integer >= 0)
6510 {
6511 // MessagePack does not differentiate between positive
6512 // signed integers and unsigned integers. Therefore, we used
6513 // the code from the value_t::number_unsigned case here.
6514 if (j.m_value.number_unsigned < 128)
6515 {
6516 // positive fixnum
6517 write_number(static_cast<uint8_t>(j.m_value.number_integer));
6518 }
6519 else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
6520 {
6521 // uint 8
6522 oa->write_character(static_cast<CharType>(0xCC));
6523 write_number(static_cast<uint8_t>(j.m_value.number_integer));
6524 }
6525 else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
6526 {
6527 // uint 16
6528 oa->write_character(static_cast<CharType>(0xCD));
6529 write_number(static_cast<uint16_t>(j.m_value.number_integer));
6530 }
6531 else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
6532 {
6533 // uint 32
6534 oa->write_character(static_cast<CharType>(0xCE));
6535 write_number(static_cast<uint32_t>(j.m_value.number_integer));
6536 }
6537 else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
6538 {
6539 // uint 64
6540 oa->write_character(static_cast<CharType>(0xCF));
6541 write_number(static_cast<uint64_t>(j.m_value.number_integer));
6542 }
6543 }
6544 else
6545 {
6546 if (j.m_value.number_integer >= -32)
6547 {
6548 // negative fixnum
6549 write_number(static_cast<int8_t>(j.m_value.number_integer));
6550 }
6551 else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and
6552 j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
6553 {
6554 // int 8
6555 oa->write_character(static_cast<CharType>(0xD0));
6556 write_number(static_cast<int8_t>(j.m_value.number_integer));
6557 }
6558 else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and
6559 j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
6560 {
6561 // int 16
6562 oa->write_character(static_cast<CharType>(0xD1));
6563 write_number(static_cast<int16_t>(j.m_value.number_integer));
6564 }
6565 else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and
6566 j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
6567 {
6568 // int 32
6569 oa->write_character(static_cast<CharType>(0xD2));
6570 write_number(static_cast<int32_t>(j.m_value.number_integer));
6571 }
6572 else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and
6573 j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
6574 {
6575 // int 64
6576 oa->write_character(static_cast<CharType>(0xD3));
6577 write_number(static_cast<int64_t>(j.m_value.number_integer));
6578 }
6579 }
6580 break;
6581 }
6582
6583 case value_t::number_unsigned:
6584 {
6585 if (j.m_value.number_unsigned < 128)
6586 {
6587 // positive fixnum
6588 write_number(static_cast<uint8_t>(j.m_value.number_integer));
6589 }
6590 else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
6591 {
6592 // uint 8
6593 oa->write_character(static_cast<CharType>(0xCC));
6594 write_number(static_cast<uint8_t>(j.m_value.number_integer));
6595 }
6596 else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
6597 {
6598 // uint 16
6599 oa->write_character(static_cast<CharType>(0xCD));
6600 write_number(static_cast<uint16_t>(j.m_value.number_integer));
6601 }
6602 else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
6603 {
6604 // uint 32
6605 oa->write_character(static_cast<CharType>(0xCE));
6606 write_number(static_cast<uint32_t>(j.m_value.number_integer));
6607 }
6608 else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
6609 {
6610 // uint 64
6611 oa->write_character(static_cast<CharType>(0xCF));
6612 write_number(static_cast<uint64_t>(j.m_value.number_integer));
6613 }
6614 break;
6615 }
6616
6617 case value_t::number_float: // float 64
6618 {
6619 oa->write_character(static_cast<CharType>(0xCB));
6620 write_number(j.m_value.number_float);
6621 break;
6622 }
6623
6624 case value_t::string:
6625 {
6626 // step 1: write control byte and the string length
6627 const auto N = j.m_value.string->size();
6628 if (N <= 31)
6629 {
6630 // fixstr
6631 write_number(static_cast<uint8_t>(0xA0 | N));
6632 }
6633 else if (N <= (std::numeric_limits<uint8_t>::max)())
6634 {
6635 // str 8
6636 oa->write_character(static_cast<CharType>(0xD9));
6637 write_number(static_cast<uint8_t>(N));
6638 }
6639 else if (N <= (std::numeric_limits<uint16_t>::max)())
6640 {
6641 // str 16
6642 oa->write_character(static_cast<CharType>(0xDA));
6643 write_number(static_cast<uint16_t>(N));
6644 }
6645 else if (N <= (std::numeric_limits<uint32_t>::max)())
6646 {
6647 // str 32
6648 oa->write_character(static_cast<CharType>(0xDB));
6649 write_number(static_cast<uint32_t>(N));
6650 }
6651
6652 // step 2: write the string
6653 oa->write_characters(
6654 reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
6655 j.m_value.string->size());
6656 break;
6657 }
6658
6659 case value_t::array:
6660 {
6661 // step 1: write control byte and the array size
6662 const auto N = j.m_value.array->size();
6663 if (N <= 15)
6664 {
6665 // fixarray
6666 write_number(static_cast<uint8_t>(0x90 | N));
6667 }
6668 else if (N <= (std::numeric_limits<uint16_t>::max)())
6669 {
6670 // array 16
6671 oa->write_character(static_cast<CharType>(0xDC));
6672 write_number(static_cast<uint16_t>(N));
6673 }
6674 else if (N <= (std::numeric_limits<uint32_t>::max)())
6675 {
6676 // array 32
6677 oa->write_character(static_cast<CharType>(0xDD));
6678 write_number(static_cast<uint32_t>(N));
6679 }
6680
6681 // step 2: write each element
6682 for (const auto& el : *j.m_value.array)
6683 {
6684 write_msgpack(el);
6685 }
6686 break;
6687 }
6688
6689 case value_t::object:
6690 {
6691 // step 1: write control byte and the object size
6692 const auto N = j.m_value.object->size();
6693 if (N <= 15)
6694 {
6695 // fixmap
6696 write_number(static_cast<uint8_t>(0x80 | (N & 0xF)));
6697 }
6698 else if (N <= (std::numeric_limits<uint16_t>::max)())
6699 {
6700 // map 16
6701 oa->write_character(static_cast<CharType>(0xDE));
6702 write_number(static_cast<uint16_t>(N));
6703 }
6704 else if (N <= (std::numeric_limits<uint32_t>::max)())
6705 {
6706 // map 32
6707 oa->write_character(static_cast<CharType>(0xDF));
6708 write_number(static_cast<uint32_t>(N));
6709 }
6710
6711 // step 2: write each element
6712 for (const auto& el : *j.m_value.object)
6713 {
6714 write_msgpack(el.first);
6715 write_msgpack(el.second);
6716 }
6717 break;
6718 }
6719
6720 default:
6721 break;
6722 }
6723 }
6724
6725 /*!
6726 @param[in] j JSON value to serialize
6727 @param[in] use_count whether to use '#' prefixes (optimized format)
6728 @param[in] use_type whether to use '$' prefixes (optimized format)
6729 @param[in] add_prefix whether prefixes need to be used for this value
6730 */
write_ubjson(const BasicJsonType & j,const bool use_count,const bool use_type,const bool add_prefix=true)6731 void write_ubjson(const BasicJsonType& j, const bool use_count,
6732 const bool use_type, const bool add_prefix = true)
6733 {
6734 switch (j.type())
6735 {
6736 case value_t::null:
6737 {
6738 if (add_prefix)
6739 {
6740 oa->write_character(static_cast<CharType>('Z'));
6741 }
6742 break;
6743 }
6744
6745 case value_t::boolean:
6746 {
6747 if (add_prefix)
6748 oa->write_character(j.m_value.boolean
6749 ? static_cast<CharType>('T')
6750 : static_cast<CharType>('F'));
6751 break;
6752 }
6753
6754 case value_t::number_integer:
6755 {
6756 write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
6757 break;
6758 }
6759
6760 case value_t::number_unsigned:
6761 {
6762 write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
6763 break;
6764 }
6765
6766 case value_t::number_float:
6767 {
6768 write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
6769 break;
6770 }
6771
6772 case value_t::string:
6773 {
6774 if (add_prefix)
6775 {
6776 oa->write_character(static_cast<CharType>('S'));
6777 }
6778 write_number_with_ubjson_prefix(j.m_value.string->size(), true);
6779 oa->write_characters(
6780 reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
6781 j.m_value.string->size());
6782 break;
6783 }
6784
6785 case value_t::array:
6786 {
6787 if (add_prefix)
6788 {
6789 oa->write_character(static_cast<CharType>('['));
6790 }
6791
6792 bool prefix_required = true;
6793 if (use_type and not j.m_value.array->empty())
6794 {
6795 assert(use_count);
6796 const char first_prefix = ubjson_prefix(j.front());
6797 const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
6798 [this, first_prefix](const BasicJsonType & v)
6799 {
6800 return ubjson_prefix(v) == first_prefix;
6801 });
6802
6803 if (same_prefix)
6804 {
6805 prefix_required = false;
6806 oa->write_character(static_cast<CharType>('$'));
6807 oa->write_character(static_cast<CharType>(first_prefix));
6808 }
6809 }
6810
6811 if (use_count)
6812 {
6813 oa->write_character(static_cast<CharType>('#'));
6814 write_number_with_ubjson_prefix(j.m_value.array->size(), true);
6815 }
6816
6817 for (const auto& el : *j.m_value.array)
6818 {
6819 write_ubjson(el, use_count, use_type, prefix_required);
6820 }
6821
6822 if (not use_count)
6823 {
6824 oa->write_character(static_cast<CharType>(']'));
6825 }
6826
6827 break;
6828 }
6829
6830 case value_t::object:
6831 {
6832 if (add_prefix)
6833 {
6834 oa->write_character(static_cast<CharType>('{'));
6835 }
6836
6837 bool prefix_required = true;
6838 if (use_type and not j.m_value.object->empty())
6839 {
6840 assert(use_count);
6841 const char first_prefix = ubjson_prefix(j.front());
6842 const bool same_prefix = std::all_of(j.begin(), j.end(),
6843 [this, first_prefix](const BasicJsonType & v)
6844 {
6845 return ubjson_prefix(v) == first_prefix;
6846 });
6847
6848 if (same_prefix)
6849 {
6850 prefix_required = false;
6851 oa->write_character(static_cast<CharType>('$'));
6852 oa->write_character(static_cast<CharType>(first_prefix));
6853 }
6854 }
6855
6856 if (use_count)
6857 {
6858 oa->write_character(static_cast<CharType>('#'));
6859 write_number_with_ubjson_prefix(j.m_value.object->size(), true);
6860 }
6861
6862 for (const auto& el : *j.m_value.object)
6863 {
6864 write_number_with_ubjson_prefix(el.first.size(), true);
6865 oa->write_characters(
6866 reinterpret_cast<const CharType*>(el.first.c_str()),
6867 el.first.size());
6868 write_ubjson(el.second, use_count, use_type, prefix_required);
6869 }
6870
6871 if (not use_count)
6872 {
6873 oa->write_character(static_cast<CharType>('}'));
6874 }
6875
6876 break;
6877 }
6878
6879 default:
6880 break;
6881 }
6882 }
6883
6884 private:
6885 /*
6886 @brief write a number to output input
6887
6888 @param[in] n number of type @a NumberType
6889 @tparam NumberType the type of the number
6890
6891 @note This function needs to respect the system's endianess, because bytes
6892 in CBOR, MessagePack, and UBJSON are stored in network order (big
6893 endian) and therefore need reordering on little endian systems.
6894 */
6895 template<typename NumberType>
write_number(const NumberType n)6896 void write_number(const NumberType n)
6897 {
6898 // step 1: write number to array of length NumberType
6899 std::array<CharType, sizeof(NumberType)> vec;
6900 std::memcpy(vec.data(), &n, sizeof(NumberType));
6901
6902 // step 2: write array to output (with possible reordering)
6903 if (is_little_endian)
6904 {
6905 // reverse byte order prior to conversion if necessary
6906 std::reverse(vec.begin(), vec.end());
6907 }
6908
6909 oa->write_characters(vec.data(), sizeof(NumberType));
6910 }
6911
6912 template<typename NumberType>
write_number_with_ubjson_prefix(const NumberType n,const bool add_prefix)6913 void write_number_with_ubjson_prefix(const NumberType n,
6914 const bool add_prefix)
6915 {
6916 if (std::is_floating_point<NumberType>::value)
6917 {
6918 if (add_prefix)
6919 {
6920 oa->write_character(static_cast<CharType>('D')); // float64
6921 }
6922 write_number(n);
6923 }
6924 else if (std::is_unsigned<NumberType>::value)
6925 {
6926 if (n <= (std::numeric_limits<int8_t>::max)())
6927 {
6928 if (add_prefix)
6929 {
6930 oa->write_character(static_cast<CharType>('i')); // int8
6931 }
6932 write_number(static_cast<uint8_t>(n));
6933 }
6934 else if (n <= (std::numeric_limits<uint8_t>::max)())
6935 {
6936 if (add_prefix)
6937 {
6938 oa->write_character(static_cast<CharType>('U')); // uint8
6939 }
6940 write_number(static_cast<uint8_t>(n));
6941 }
6942 else if (n <= (std::numeric_limits<int16_t>::max)())
6943 {
6944 if (add_prefix)
6945 {
6946 oa->write_character(static_cast<CharType>('I')); // int16
6947 }
6948 write_number(static_cast<int16_t>(n));
6949 }
6950 else if (n <= (std::numeric_limits<int32_t>::max)())
6951 {
6952 if (add_prefix)
6953 {
6954 oa->write_character(static_cast<CharType>('l')); // int32
6955 }
6956 write_number(static_cast<int32_t>(n));
6957 }
6958 else if (n <= (std::numeric_limits<int64_t>::max)())
6959 {
6960 if (add_prefix)
6961 {
6962 oa->write_character(static_cast<CharType>('L')); // int64
6963 }
6964 write_number(static_cast<int64_t>(n));
6965 }
6966 else
6967 {
6968 JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n)));
6969 }
6970 }
6971 else
6972 {
6973 if ((std::numeric_limits<int8_t>::min)() <= n and n <= (std::numeric_limits<int8_t>::max)())
6974 {
6975 if (add_prefix)
6976 {
6977 oa->write_character(static_cast<CharType>('i')); // int8
6978 }
6979 write_number(static_cast<int8_t>(n));
6980 }
6981 else if ((std::numeric_limits<uint8_t>::min)() <= n and n <= (std::numeric_limits<uint8_t>::max)())
6982 {
6983 if (add_prefix)
6984 {
6985 oa->write_character(static_cast<CharType>('U')); // uint8
6986 }
6987 write_number(static_cast<uint8_t>(n));
6988 }
6989 else if ((std::numeric_limits<int16_t>::min)() <= n and n <= (std::numeric_limits<int16_t>::max)())
6990 {
6991 if (add_prefix)
6992 {
6993 oa->write_character(static_cast<CharType>('I')); // int16
6994 }
6995 write_number(static_cast<int16_t>(n));
6996 }
6997 else if ((std::numeric_limits<int32_t>::min)() <= n and n <= (std::numeric_limits<int32_t>::max)())
6998 {
6999 if (add_prefix)
7000 {
7001 oa->write_character(static_cast<CharType>('l')); // int32
7002 }
7003 write_number(static_cast<int32_t>(n));
7004 }
7005 else if ((std::numeric_limits<int64_t>::min)() <= n and n <= (std::numeric_limits<int64_t>::max)())
7006 {
7007 if (add_prefix)
7008 {
7009 oa->write_character(static_cast<CharType>('L')); // int64
7010 }
7011 write_number(static_cast<int64_t>(n));
7012 }
7013 // LCOV_EXCL_START
7014 else
7015 {
7016 JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n)));
7017 }
7018 // LCOV_EXCL_STOP
7019 }
7020 }
7021
7022 /*!
7023 @brief determine the type prefix of container values
7024
7025 @note This function does not need to be 100% accurate when it comes to
7026 integer limits. In case a number exceeds the limits of int64_t,
7027 this will be detected by a later call to function
7028 write_number_with_ubjson_prefix. Therefore, we return 'L' for any
7029 value that does not fit the previous limits.
7030 */
ubjson_prefix(const BasicJsonType & j) const7031 char ubjson_prefix(const BasicJsonType& j) const noexcept
7032 {
7033 switch (j.type())
7034 {
7035 case value_t::null:
7036 return 'Z';
7037
7038 case value_t::boolean:
7039 return j.m_value.boolean ? 'T' : 'F';
7040
7041 case value_t::number_integer:
7042 {
7043 if ((std::numeric_limits<int8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
7044 {
7045 return 'i';
7046 }
7047 else if ((std::numeric_limits<uint8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
7048 {
7049 return 'U';
7050 }
7051 else if ((std::numeric_limits<int16_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
7052 {
7053 return 'I';
7054 }
7055 else if ((std::numeric_limits<int32_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
7056 {
7057 return 'l';
7058 }
7059 else // no check and assume int64_t (see note above)
7060 {
7061 return 'L';
7062 }
7063 }
7064
7065 case value_t::number_unsigned:
7066 {
7067 if (j.m_value.number_unsigned <= (std::numeric_limits<int8_t>::max)())
7068 {
7069 return 'i';
7070 }
7071 else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
7072 {
7073 return 'U';
7074 }
7075 else if (j.m_value.number_unsigned <= (std::numeric_limits<int16_t>::max)())
7076 {
7077 return 'I';
7078 }
7079 else if (j.m_value.number_unsigned <= (std::numeric_limits<int32_t>::max)())
7080 {
7081 return 'l';
7082 }
7083 else // no check and assume int64_t (see note above)
7084 {
7085 return 'L';
7086 }
7087 }
7088
7089 case value_t::number_float:
7090 return 'D';
7091
7092 case value_t::string:
7093 return 'S';
7094
7095 case value_t::array:
7096 return '[';
7097
7098 case value_t::object:
7099 return '{';
7100
7101 default: // discarded values
7102 return 'N';
7103 }
7104 }
7105
7106 private:
7107 /// whether we can assume little endianess
7108 const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
7109
7110 /// the output
7111 output_adapter_t<CharType> oa = nullptr;
7112 };
7113 }
7114 }
7115
7116 // #include <nlohmann/detail/output/serializer.hpp>
7117
7118
7119 #include <algorithm> // reverse, remove, fill, find, none_of
7120 #include <array> // array
7121 #include <cassert> // assert
7122 #include <ciso646> // and, or
7123 #include <clocale> // localeconv, lconv
7124 #include <cmath> // labs, isfinite, isnan, signbit
7125 #include <cstddef> // size_t, ptrdiff_t
7126 #include <cstdint> // uint8_t
7127 #include <cstdio> // snprintf
7128 #include <iomanip> // setfill
7129 #include <iterator> // next
7130 #include <limits> // numeric_limits
7131 #include <string> // string
7132 #include <sstream> // stringstream
7133 #include <type_traits> // is_same
7134
7135 // #include <nlohmann/detail/exceptions.hpp>
7136
7137 // #include <nlohmann/detail/conversions/to_chars.hpp>
7138
7139
7140 #include <cassert> // assert
7141 #include <ciso646> // or, and, not
7142 #include <cmath> // signbit, isfinite
7143 #include <cstdint> // intN_t, uintN_t
7144 #include <cstring> // memcpy, memmove
7145
7146 namespace nlohmann
7147 {
7148 namespace detail
7149 {
7150
7151 /*!
7152 @brief implements the Grisu2 algorithm for binary to decimal floating-point
7153 conversion.
7154
7155 This implementation is a slightly modified version of the reference
7156 implementation which may be obtained from
7157 http://florian.loitsch.com/publications (bench.tar.gz).
7158
7159 The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
7160
7161 For a detailed description of the algorithm see:
7162
7163 [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
7164 Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
7165 Language Design and Implementation, PLDI 2010
7166 [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
7167 Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
7168 Design and Implementation, PLDI 1996
7169 */
7170 namespace dtoa_impl
7171 {
7172
7173 template <typename Target, typename Source>
7174 Target reinterpret_bits(const Source source)
7175 {
7176 static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
7177
7178 Target target;
7179 std::memcpy(&target, &source, sizeof(Source));
7180 return target;
7181 }
7182
7183 struct diyfp // f * 2^e
7184 {
7185 static constexpr int kPrecision = 64; // = q
7186
7187 uint64_t f;
7188 int e;
7189
diyfpnlohmann::detail::dtoa_impl::diyfp7190 constexpr diyfp() noexcept : f(0), e(0) {}
diyfpnlohmann::detail::dtoa_impl::diyfp7191 constexpr diyfp(uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
7192
7193 /*!
7194 @brief returns x - y
7195 @pre x.e == y.e and x.f >= y.f
7196 */
subnlohmann::detail::dtoa_impl::diyfp7197 static diyfp sub(const diyfp& x, const diyfp& y) noexcept
7198 {
7199 assert(x.e == y.e);
7200 assert(x.f >= y.f);
7201
7202 return diyfp(x.f - y.f, x.e);
7203 }
7204
7205 /*!
7206 @brief returns x * y
7207 @note The result is rounded. (Only the upper q bits are returned.)
7208 */
mulnlohmann::detail::dtoa_impl::diyfp7209 static diyfp mul(const diyfp& x, const diyfp& y) noexcept
7210 {
7211 static_assert(kPrecision == 64, "internal error");
7212
7213 // Computes:
7214 // f = round((x.f * y.f) / 2^q)
7215 // e = x.e + y.e + q
7216
7217 // Emulate the 64-bit * 64-bit multiplication:
7218 //
7219 // p = u * v
7220 // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
7221 // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
7222 // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
7223 // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
7224 // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
7225 // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
7226 // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
7227 //
7228 // (Since Q might be larger than 2^32 - 1)
7229 //
7230 // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
7231 //
7232 // (Q_hi + H does not overflow a 64-bit int)
7233 //
7234 // = p_lo + 2^64 p_hi
7235
7236 const uint64_t u_lo = x.f & 0xFFFFFFFF;
7237 const uint64_t u_hi = x.f >> 32;
7238 const uint64_t v_lo = y.f & 0xFFFFFFFF;
7239 const uint64_t v_hi = y.f >> 32;
7240
7241 const uint64_t p0 = u_lo * v_lo;
7242 const uint64_t p1 = u_lo * v_hi;
7243 const uint64_t p2 = u_hi * v_lo;
7244 const uint64_t p3 = u_hi * v_hi;
7245
7246 const uint64_t p0_hi = p0 >> 32;
7247 const uint64_t p1_lo = p1 & 0xFFFFFFFF;
7248 const uint64_t p1_hi = p1 >> 32;
7249 const uint64_t p2_lo = p2 & 0xFFFFFFFF;
7250 const uint64_t p2_hi = p2 >> 32;
7251
7252 uint64_t Q = p0_hi + p1_lo + p2_lo;
7253
7254 // The full product might now be computed as
7255 //
7256 // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
7257 // p_lo = p0_lo + (Q << 32)
7258 //
7259 // But in this particular case here, the full p_lo is not required.
7260 // Effectively we only need to add the highest bit in p_lo to p_hi (and
7261 // Q_hi + 1 does not overflow).
7262
7263 Q += uint64_t{1} << (64 - 32 - 1); // round, ties up
7264
7265 const uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32);
7266
7267 return diyfp(h, x.e + y.e + 64);
7268 }
7269
7270 /*!
7271 @brief normalize x such that the significand is >= 2^(q-1)
7272 @pre x.f != 0
7273 */
normalizenlohmann::detail::dtoa_impl::diyfp7274 static diyfp normalize(diyfp x) noexcept
7275 {
7276 assert(x.f != 0);
7277
7278 while ((x.f >> 63) == 0)
7279 {
7280 x.f <<= 1;
7281 x.e--;
7282 }
7283
7284 return x;
7285 }
7286
7287 /*!
7288 @brief normalize x such that the result has the exponent E
7289 @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
7290 */
normalize_tonlohmann::detail::dtoa_impl::diyfp7291 static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
7292 {
7293 const int delta = x.e - target_exponent;
7294
7295 assert(delta >= 0);
7296 assert(((x.f << delta) >> delta) == x.f);
7297
7298 return diyfp(x.f << delta, target_exponent);
7299 }
7300 };
7301
7302 struct boundaries
7303 {
7304 diyfp w;
7305 diyfp minus;
7306 diyfp plus;
7307 };
7308
7309 /*!
7310 Compute the (normalized) diyfp representing the input number 'value' and its
7311 boundaries.
7312
7313 @pre value must be finite and positive
7314 */
7315 template <typename FloatType>
compute_boundaries(FloatType value)7316 boundaries compute_boundaries(FloatType value)
7317 {
7318 assert(std::isfinite(value));
7319 assert(value > 0);
7320
7321 // Convert the IEEE representation into a diyfp.
7322 //
7323 // If v is denormal:
7324 // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
7325 // If v is normalized:
7326 // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
7327
7328 static_assert(std::numeric_limits<FloatType>::is_iec559,
7329 "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
7330
7331 constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
7332 constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
7333 constexpr int kMinExp = 1 - kBias;
7334 constexpr uint64_t kHiddenBit = uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
7335
7336 using bits_type = typename std::conditional< kPrecision == 24, uint32_t, uint64_t >::type;
7337
7338 const uint64_t bits = reinterpret_bits<bits_type>(value);
7339 const uint64_t E = bits >> (kPrecision - 1);
7340 const uint64_t F = bits & (kHiddenBit - 1);
7341
7342 const bool is_denormal = (E == 0);
7343 const diyfp v = is_denormal
7344 ? diyfp(F, kMinExp)
7345 : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
7346
7347 // Compute the boundaries m- and m+ of the floating-point value
7348 // v = f * 2^e.
7349 //
7350 // Determine v- and v+, the floating-point predecessor and successor if v,
7351 // respectively.
7352 //
7353 // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
7354 // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
7355 //
7356 // v+ = v + 2^e
7357 //
7358 // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
7359 // between m- and m+ round to v, regardless of how the input rounding
7360 // algorithm breaks ties.
7361 //
7362 // ---+-------------+-------------+-------------+-------------+--- (A)
7363 // v- m- v m+ v+
7364 //
7365 // -----------------+------+------+-------------+-------------+--- (B)
7366 // v- m- v m+ v+
7367
7368 const bool lower_boundary_is_closer = (F == 0 and E > 1);
7369 const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
7370 const diyfp m_minus = lower_boundary_is_closer
7371 ? diyfp(4 * v.f - 1, v.e - 2) // (B)
7372 : diyfp(2 * v.f - 1, v.e - 1); // (A)
7373
7374 // Determine the normalized w+ = m+.
7375 const diyfp w_plus = diyfp::normalize(m_plus);
7376
7377 // Determine w- = m- such that e_(w-) = e_(w+).
7378 const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
7379
7380 return {diyfp::normalize(v), w_minus, w_plus};
7381 }
7382
7383 // Given normalized diyfp w, Grisu needs to find a (normalized) cached
7384 // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
7385 // within a certain range [alpha, gamma] (Definition 3.2 from [1])
7386 //
7387 // alpha <= e = e_c + e_w + q <= gamma
7388 //
7389 // or
7390 //
7391 // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
7392 // <= f_c * f_w * 2^gamma
7393 //
7394 // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
7395 //
7396 // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
7397 //
7398 // or
7399 //
7400 // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
7401 //
7402 // The choice of (alpha,gamma) determines the size of the table and the form of
7403 // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
7404 // in practice:
7405 //
7406 // The idea is to cut the number c * w = f * 2^e into two parts, which can be
7407 // processed independently: An integral part p1, and a fractional part p2:
7408 //
7409 // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
7410 // = (f div 2^-e) + (f mod 2^-e) * 2^e
7411 // = p1 + p2 * 2^e
7412 //
7413 // The conversion of p1 into decimal form requires a series of divisions and
7414 // modulos by (a power of) 10. These operations are faster for 32-bit than for
7415 // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
7416 // achieved by choosing
7417 //
7418 // -e >= 32 or e <= -32 := gamma
7419 //
7420 // In order to convert the fractional part
7421 //
7422 // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
7423 //
7424 // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
7425 // d[-i] are extracted in order:
7426 //
7427 // (10 * p2) div 2^-e = d[-1]
7428 // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
7429 //
7430 // The multiplication by 10 must not overflow. It is sufficient to choose
7431 //
7432 // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
7433 //
7434 // Since p2 = f mod 2^-e < 2^-e,
7435 //
7436 // -e <= 60 or e >= -60 := alpha
7437
7438 constexpr int kAlpha = -60;
7439 constexpr int kGamma = -32;
7440
7441 struct cached_power // c = f * 2^e ~= 10^k
7442 {
7443 uint64_t f;
7444 int e;
7445 int k;
7446 };
7447
7448 /*!
7449 For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
7450 power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
7451 satisfies (Definition 3.2 from [1])
7452
7453 alpha <= e_c + e + q <= gamma.
7454 */
get_cached_power_for_binary_exponent(int e)7455 inline cached_power get_cached_power_for_binary_exponent(int e)
7456 {
7457 // Now
7458 //
7459 // alpha <= e_c + e + q <= gamma (1)
7460 // ==> f_c * 2^alpha <= c * 2^e * 2^q
7461 //
7462 // and since the c's are normalized, 2^(q-1) <= f_c,
7463 //
7464 // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
7465 // ==> 2^(alpha - e - 1) <= c
7466 //
7467 // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as
7468 //
7469 // k = ceil( log_10( 2^(alpha - e - 1) ) )
7470 // = ceil( (alpha - e - 1) * log_10(2) )
7471 //
7472 // From the paper:
7473 // "In theory the result of the procedure could be wrong since c is rounded,
7474 // and the computation itself is approximated [...]. In practice, however,
7475 // this simple function is sufficient."
7476 //
7477 // For IEEE double precision floating-point numbers converted into
7478 // normalized diyfp's w = f * 2^e, with q = 64,
7479 //
7480 // e >= -1022 (min IEEE exponent)
7481 // -52 (p - 1)
7482 // -52 (p - 1, possibly normalize denormal IEEE numbers)
7483 // -11 (normalize the diyfp)
7484 // = -1137
7485 //
7486 // and
7487 //
7488 // e <= +1023 (max IEEE exponent)
7489 // -52 (p - 1)
7490 // -11 (normalize the diyfp)
7491 // = 960
7492 //
7493 // This binary exponent range [-1137,960] results in a decimal exponent
7494 // range [-307,324]. One does not need to store a cached power for each
7495 // k in this range. For each such k it suffices to find a cached power
7496 // such that the exponent of the product lies in [alpha,gamma].
7497 // This implies that the difference of the decimal exponents of adjacent
7498 // table entries must be less than or equal to
7499 //
7500 // floor( (gamma - alpha) * log_10(2) ) = 8.
7501 //
7502 // (A smaller distance gamma-alpha would require a larger table.)
7503
7504 // NB:
7505 // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
7506
7507 constexpr int kCachedPowersSize = 79;
7508 constexpr int kCachedPowersMinDecExp = -300;
7509 constexpr int kCachedPowersDecStep = 8;
7510
7511 static constexpr cached_power kCachedPowers[] =
7512 {
7513 { 0xAB70FE17C79AC6CA, -1060, -300 },
7514 { 0xFF77B1FCBEBCDC4F, -1034, -292 },
7515 { 0xBE5691EF416BD60C, -1007, -284 },
7516 { 0x8DD01FAD907FFC3C, -980, -276 },
7517 { 0xD3515C2831559A83, -954, -268 },
7518 { 0x9D71AC8FADA6C9B5, -927, -260 },
7519 { 0xEA9C227723EE8BCB, -901, -252 },
7520 { 0xAECC49914078536D, -874, -244 },
7521 { 0x823C12795DB6CE57, -847, -236 },
7522 { 0xC21094364DFB5637, -821, -228 },
7523 { 0x9096EA6F3848984F, -794, -220 },
7524 { 0xD77485CB25823AC7, -768, -212 },
7525 { 0xA086CFCD97BF97F4, -741, -204 },
7526 { 0xEF340A98172AACE5, -715, -196 },
7527 { 0xB23867FB2A35B28E, -688, -188 },
7528 { 0x84C8D4DFD2C63F3B, -661, -180 },
7529 { 0xC5DD44271AD3CDBA, -635, -172 },
7530 { 0x936B9FCEBB25C996, -608, -164 },
7531 { 0xDBAC6C247D62A584, -582, -156 },
7532 { 0xA3AB66580D5FDAF6, -555, -148 },
7533 { 0xF3E2F893DEC3F126, -529, -140 },
7534 { 0xB5B5ADA8AAFF80B8, -502, -132 },
7535 { 0x87625F056C7C4A8B, -475, -124 },
7536 { 0xC9BCFF6034C13053, -449, -116 },
7537 { 0x964E858C91BA2655, -422, -108 },
7538 { 0xDFF9772470297EBD, -396, -100 },
7539 { 0xA6DFBD9FB8E5B88F, -369, -92 },
7540 { 0xF8A95FCF88747D94, -343, -84 },
7541 { 0xB94470938FA89BCF, -316, -76 },
7542 { 0x8A08F0F8BF0F156B, -289, -68 },
7543 { 0xCDB02555653131B6, -263, -60 },
7544 { 0x993FE2C6D07B7FAC, -236, -52 },
7545 { 0xE45C10C42A2B3B06, -210, -44 },
7546 { 0xAA242499697392D3, -183, -36 },
7547 { 0xFD87B5F28300CA0E, -157, -28 },
7548 { 0xBCE5086492111AEB, -130, -20 },
7549 { 0x8CBCCC096F5088CC, -103, -12 },
7550 { 0xD1B71758E219652C, -77, -4 },
7551 { 0x9C40000000000000, -50, 4 },
7552 { 0xE8D4A51000000000, -24, 12 },
7553 { 0xAD78EBC5AC620000, 3, 20 },
7554 { 0x813F3978F8940984, 30, 28 },
7555 { 0xC097CE7BC90715B3, 56, 36 },
7556 { 0x8F7E32CE7BEA5C70, 83, 44 },
7557 { 0xD5D238A4ABE98068, 109, 52 },
7558 { 0x9F4F2726179A2245, 136, 60 },
7559 { 0xED63A231D4C4FB27, 162, 68 },
7560 { 0xB0DE65388CC8ADA8, 189, 76 },
7561 { 0x83C7088E1AAB65DB, 216, 84 },
7562 { 0xC45D1DF942711D9A, 242, 92 },
7563 { 0x924D692CA61BE758, 269, 100 },
7564 { 0xDA01EE641A708DEA, 295, 108 },
7565 { 0xA26DA3999AEF774A, 322, 116 },
7566 { 0xF209787BB47D6B85, 348, 124 },
7567 { 0xB454E4A179DD1877, 375, 132 },
7568 { 0x865B86925B9BC5C2, 402, 140 },
7569 { 0xC83553C5C8965D3D, 428, 148 },
7570 { 0x952AB45CFA97A0B3, 455, 156 },
7571 { 0xDE469FBD99A05FE3, 481, 164 },
7572 { 0xA59BC234DB398C25, 508, 172 },
7573 { 0xF6C69A72A3989F5C, 534, 180 },
7574 { 0xB7DCBF5354E9BECE, 561, 188 },
7575 { 0x88FCF317F22241E2, 588, 196 },
7576 { 0xCC20CE9BD35C78A5, 614, 204 },
7577 { 0x98165AF37B2153DF, 641, 212 },
7578 { 0xE2A0B5DC971F303A, 667, 220 },
7579 { 0xA8D9D1535CE3B396, 694, 228 },
7580 { 0xFB9B7CD9A4A7443C, 720, 236 },
7581 { 0xBB764C4CA7A44410, 747, 244 },
7582 { 0x8BAB8EEFB6409C1A, 774, 252 },
7583 { 0xD01FEF10A657842C, 800, 260 },
7584 { 0x9B10A4E5E9913129, 827, 268 },
7585 { 0xE7109BFBA19C0C9D, 853, 276 },
7586 { 0xAC2820D9623BF429, 880, 284 },
7587 { 0x80444B5E7AA7CF85, 907, 292 },
7588 { 0xBF21E44003ACDD2D, 933, 300 },
7589 { 0x8E679C2F5E44FF8F, 960, 308 },
7590 { 0xD433179D9C8CB841, 986, 316 },
7591 { 0x9E19DB92B4E31BA9, 1013, 324 },
7592 };
7593
7594 // This computation gives exactly the same results for k as
7595 // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
7596 // for |e| <= 1500, but doesn't require floating-point operations.
7597 // NB: log_10(2) ~= 78913 / 2^18
7598 assert(e >= -1500);
7599 assert(e <= 1500);
7600 const int f = kAlpha - e - 1;
7601 const int k = (f * 78913) / (1 << 18) + (f > 0);
7602
7603 const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
7604 assert(index >= 0);
7605 assert(index < kCachedPowersSize);
7606 static_cast<void>(kCachedPowersSize); // Fix warning.
7607
7608 const cached_power cached = kCachedPowers[index];
7609 assert(kAlpha <= cached.e + e + 64);
7610 assert(kGamma >= cached.e + e + 64);
7611
7612 return cached;
7613 }
7614
7615 /*!
7616 For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
7617 For n == 0, returns 1 and sets pow10 := 1.
7618 */
find_largest_pow10(const uint32_t n,uint32_t & pow10)7619 inline int find_largest_pow10(const uint32_t n, uint32_t& pow10)
7620 {
7621 // LCOV_EXCL_START
7622 if (n >= 1000000000)
7623 {
7624 pow10 = 1000000000;
7625 return 10;
7626 }
7627 // LCOV_EXCL_STOP
7628 else if (n >= 100000000)
7629 {
7630 pow10 = 100000000;
7631 return 9;
7632 }
7633 else if (n >= 10000000)
7634 {
7635 pow10 = 10000000;
7636 return 8;
7637 }
7638 else if (n >= 1000000)
7639 {
7640 pow10 = 1000000;
7641 return 7;
7642 }
7643 else if (n >= 100000)
7644 {
7645 pow10 = 100000;
7646 return 6;
7647 }
7648 else if (n >= 10000)
7649 {
7650 pow10 = 10000;
7651 return 5;
7652 }
7653 else if (n >= 1000)
7654 {
7655 pow10 = 1000;
7656 return 4;
7657 }
7658 else if (n >= 100)
7659 {
7660 pow10 = 100;
7661 return 3;
7662 }
7663 else if (n >= 10)
7664 {
7665 pow10 = 10;
7666 return 2;
7667 }
7668 else
7669 {
7670 pow10 = 1;
7671 return 1;
7672 }
7673 }
7674
grisu2_round(char * buf,int len,uint64_t dist,uint64_t delta,uint64_t rest,uint64_t ten_k)7675 inline void grisu2_round(char* buf, int len, uint64_t dist, uint64_t delta,
7676 uint64_t rest, uint64_t ten_k)
7677 {
7678 assert(len >= 1);
7679 assert(dist <= delta);
7680 assert(rest <= delta);
7681 assert(ten_k > 0);
7682
7683 // <--------------------------- delta ---->
7684 // <---- dist --------->
7685 // --------------[------------------+-------------------]--------------
7686 // M- w M+
7687 //
7688 // ten_k
7689 // <------>
7690 // <---- rest ---->
7691 // --------------[------------------+----+--------------]--------------
7692 // w V
7693 // = buf * 10^k
7694 //
7695 // ten_k represents a unit-in-the-last-place in the decimal representation
7696 // stored in buf.
7697 // Decrement buf by ten_k while this takes buf closer to w.
7698
7699 // The tests are written in this order to avoid overflow in unsigned
7700 // integer arithmetic.
7701
7702 while (rest < dist
7703 and delta - rest >= ten_k
7704 and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
7705 {
7706 assert(buf[len - 1] != '0');
7707 buf[len - 1]--;
7708 rest += ten_k;
7709 }
7710 }
7711
7712 /*!
7713 Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
7714 M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
7715 */
grisu2_digit_gen(char * buffer,int & length,int & decimal_exponent,diyfp M_minus,diyfp w,diyfp M_plus)7716 inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
7717 diyfp M_minus, diyfp w, diyfp M_plus)
7718 {
7719 static_assert(kAlpha >= -60, "internal error");
7720 static_assert(kGamma <= -32, "internal error");
7721
7722 // Generates the digits (and the exponent) of a decimal floating-point
7723 // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
7724 // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
7725 //
7726 // <--------------------------- delta ---->
7727 // <---- dist --------->
7728 // --------------[------------------+-------------------]--------------
7729 // M- w M+
7730 //
7731 // Grisu2 generates the digits of M+ from left to right and stops as soon as
7732 // V is in [M-,M+].
7733
7734 assert(M_plus.e >= kAlpha);
7735 assert(M_plus.e <= kGamma);
7736
7737 uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
7738 uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
7739
7740 // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
7741 //
7742 // M+ = f * 2^e
7743 // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
7744 // = ((p1 ) * 2^-e + (p2 )) * 2^e
7745 // = p1 + p2 * 2^e
7746
7747 const diyfp one(uint64_t{1} << -M_plus.e, M_plus.e);
7748
7749 uint32_t p1 = static_cast<uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)
7750 uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
7751
7752 // 1)
7753 //
7754 // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
7755
7756 assert(p1 > 0);
7757
7758 uint32_t pow10;
7759 const int k = find_largest_pow10(p1, pow10);
7760
7761 // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
7762 //
7763 // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
7764 // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
7765 //
7766 // M+ = p1 + p2 * 2^e
7767 // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
7768 // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
7769 // = d[k-1] * 10^(k-1) + ( rest) * 2^e
7770 //
7771 // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
7772 //
7773 // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
7774 //
7775 // but stop as soon as
7776 //
7777 // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
7778
7779 int n = k;
7780 while (n > 0)
7781 {
7782 // Invariants:
7783 // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
7784 // pow10 = 10^(n-1) <= p1 < 10^n
7785 //
7786 const uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
7787 const uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
7788 //
7789 // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
7790 // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
7791 //
7792 assert(d <= 9);
7793 buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
7794 //
7795 // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
7796 //
7797 p1 = r;
7798 n--;
7799 //
7800 // M+ = buffer * 10^n + (p1 + p2 * 2^e)
7801 // pow10 = 10^n
7802 //
7803
7804 // Now check if enough digits have been generated.
7805 // Compute
7806 //
7807 // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
7808 //
7809 // Note:
7810 // Since rest and delta share the same exponent e, it suffices to
7811 // compare the significands.
7812 const uint64_t rest = (uint64_t{p1} << -one.e) + p2;
7813 if (rest <= delta)
7814 {
7815 // V = buffer * 10^n, with M- <= V <= M+.
7816
7817 decimal_exponent += n;
7818
7819 // We may now just stop. But instead look if the buffer could be
7820 // decremented to bring V closer to w.
7821 //
7822 // pow10 = 10^n is now 1 ulp in the decimal representation V.
7823 // The rounding procedure works with diyfp's with an implicit
7824 // exponent of e.
7825 //
7826 // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
7827 //
7828 const uint64_t ten_n = uint64_t{pow10} << -one.e;
7829 grisu2_round(buffer, length, dist, delta, rest, ten_n);
7830
7831 return;
7832 }
7833
7834 pow10 /= 10;
7835 //
7836 // pow10 = 10^(n-1) <= p1 < 10^n
7837 // Invariants restored.
7838 }
7839
7840 // 2)
7841 //
7842 // The digits of the integral part have been generated:
7843 //
7844 // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
7845 // = buffer + p2 * 2^e
7846 //
7847 // Now generate the digits of the fractional part p2 * 2^e.
7848 //
7849 // Note:
7850 // No decimal point is generated: the exponent is adjusted instead.
7851 //
7852 // p2 actually represents the fraction
7853 //
7854 // p2 * 2^e
7855 // = p2 / 2^-e
7856 // = d[-1] / 10^1 + d[-2] / 10^2 + ...
7857 //
7858 // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
7859 //
7860 // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
7861 // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
7862 //
7863 // using
7864 //
7865 // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
7866 // = ( d) * 2^-e + ( r)
7867 //
7868 // or
7869 // 10^m * p2 * 2^e = d + r * 2^e
7870 //
7871 // i.e.
7872 //
7873 // M+ = buffer + p2 * 2^e
7874 // = buffer + 10^-m * (d + r * 2^e)
7875 // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
7876 //
7877 // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
7878
7879 assert(p2 > delta);
7880
7881 int m = 0;
7882 for (;;)
7883 {
7884 // Invariant:
7885 // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
7886 // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
7887 // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
7888 // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
7889 //
7890 assert(p2 <= UINT64_MAX / 10);
7891 p2 *= 10;
7892 const uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
7893 const uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
7894 //
7895 // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
7896 // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
7897 // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
7898 //
7899 assert(d <= 9);
7900 buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
7901 //
7902 // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
7903 //
7904 p2 = r;
7905 m++;
7906 //
7907 // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
7908 // Invariant restored.
7909
7910 // Check if enough digits have been generated.
7911 //
7912 // 10^-m * p2 * 2^e <= delta * 2^e
7913 // p2 * 2^e <= 10^m * delta * 2^e
7914 // p2 <= 10^m * delta
7915 delta *= 10;
7916 dist *= 10;
7917 if (p2 <= delta)
7918 {
7919 break;
7920 }
7921 }
7922
7923 // V = buffer * 10^-m, with M- <= V <= M+.
7924
7925 decimal_exponent -= m;
7926
7927 // 1 ulp in the decimal representation is now 10^-m.
7928 // Since delta and dist are now scaled by 10^m, we need to do the
7929 // same with ulp in order to keep the units in sync.
7930 //
7931 // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
7932 //
7933 const uint64_t ten_m = one.f;
7934 grisu2_round(buffer, length, dist, delta, p2, ten_m);
7935
7936 // By construction this algorithm generates the shortest possible decimal
7937 // number (Loitsch, Theorem 6.2) which rounds back to w.
7938 // For an input number of precision p, at least
7939 //
7940 // N = 1 + ceil(p * log_10(2))
7941 //
7942 // decimal digits are sufficient to identify all binary floating-point
7943 // numbers (Matula, "In-and-Out conversions").
7944 // This implies that the algorithm does not produce more than N decimal
7945 // digits.
7946 //
7947 // N = 17 for p = 53 (IEEE double precision)
7948 // N = 9 for p = 24 (IEEE single precision)
7949 }
7950
7951 /*!
7952 v = buf * 10^decimal_exponent
7953 len is the length of the buffer (number of decimal digits)
7954 The buffer must be large enough, i.e. >= max_digits10.
7955 */
grisu2(char * buf,int & len,int & decimal_exponent,diyfp m_minus,diyfp v,diyfp m_plus)7956 inline void grisu2(char* buf, int& len, int& decimal_exponent,
7957 diyfp m_minus, diyfp v, diyfp m_plus)
7958 {
7959 assert(m_plus.e == m_minus.e);
7960 assert(m_plus.e == v.e);
7961
7962 // --------(-----------------------+-----------------------)-------- (A)
7963 // m- v m+
7964 //
7965 // --------------------(-----------+-----------------------)-------- (B)
7966 // m- v m+
7967 //
7968 // First scale v (and m- and m+) such that the exponent is in the range
7969 // [alpha, gamma].
7970
7971 const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
7972
7973 const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
7974
7975 // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
7976 const diyfp w = diyfp::mul(v, c_minus_k);
7977 const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
7978 const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
7979
7980 // ----(---+---)---------------(---+---)---------------(---+---)----
7981 // w- w w+
7982 // = c*m- = c*v = c*m+
7983 //
7984 // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
7985 // w+ are now off by a small amount.
7986 // In fact:
7987 //
7988 // w - v * 10^k < 1 ulp
7989 //
7990 // To account for this inaccuracy, add resp. subtract 1 ulp.
7991 //
7992 // --------+---[---------------(---+---)---------------]---+--------
7993 // w- M- w M+ w+
7994 //
7995 // Now any number in [M-, M+] (bounds included) will round to w when input,
7996 // regardless of how the input rounding algorithm breaks ties.
7997 //
7998 // And digit_gen generates the shortest possible such number in [M-, M+].
7999 // Note that this does not mean that Grisu2 always generates the shortest
8000 // possible number in the interval (m-, m+).
8001 const diyfp M_minus(w_minus.f + 1, w_minus.e);
8002 const diyfp M_plus (w_plus.f - 1, w_plus.e );
8003
8004 decimal_exponent = -cached.k; // = -(-k) = k
8005
8006 grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
8007 }
8008
8009 /*!
8010 v = buf * 10^decimal_exponent
8011 len is the length of the buffer (number of decimal digits)
8012 The buffer must be large enough, i.e. >= max_digits10.
8013 */
8014 template <typename FloatType>
grisu2(char * buf,int & len,int & decimal_exponent,FloatType value)8015 void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
8016 {
8017 static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
8018 "internal error: not enough precision");
8019
8020 assert(std::isfinite(value));
8021 assert(value > 0);
8022
8023 // If the neighbors (and boundaries) of 'value' are always computed for double-precision
8024 // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
8025 // decimal representations are not exactly "short".
8026 //
8027 // The documentation for 'std::to_chars' (http://en.cppreference.com/w/cpp/utility/to_chars)
8028 // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
8029 // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
8030 // does.
8031 // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
8032 // representation using the corresponding std::from_chars function recovers value exactly". That
8033 // indicates that single precision floating-point numbers should be recovered using
8034 // 'std::strtof'.
8035 //
8036 // NB: If the neighbors are computed for single-precision numbers, there is a single float
8037 // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
8038 // value is off by 1 ulp.
8039 #if 0
8040 const boundaries w = compute_boundaries(static_cast<double>(value));
8041 #else
8042 const boundaries w = compute_boundaries(value);
8043 #endif
8044
8045 grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
8046 }
8047
8048 /*!
8049 @brief appends a decimal representation of e to buf
8050 @return a pointer to the element following the exponent.
8051 @pre -1000 < e < 1000
8052 */
append_exponent(char * buf,int e)8053 inline char* append_exponent(char* buf, int e)
8054 {
8055 assert(e > -1000);
8056 assert(e < 1000);
8057
8058 if (e < 0)
8059 {
8060 e = -e;
8061 *buf++ = '-';
8062 }
8063 else
8064 {
8065 *buf++ = '+';
8066 }
8067
8068 uint32_t k = static_cast<uint32_t>(e);
8069 if (k < 10)
8070 {
8071 // Always print at least two digits in the exponent.
8072 // This is for compatibility with printf("%g").
8073 *buf++ = '0';
8074 *buf++ = static_cast<char>('0' + k);
8075 }
8076 else if (k < 100)
8077 {
8078 *buf++ = static_cast<char>('0' + k / 10);
8079 k %= 10;
8080 *buf++ = static_cast<char>('0' + k);
8081 }
8082 else
8083 {
8084 *buf++ = static_cast<char>('0' + k / 100);
8085 k %= 100;
8086 *buf++ = static_cast<char>('0' + k / 10);
8087 k %= 10;
8088 *buf++ = static_cast<char>('0' + k);
8089 }
8090
8091 return buf;
8092 }
8093
8094 /*!
8095 @brief prettify v = buf * 10^decimal_exponent
8096
8097 If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
8098 notation. Otherwise it will be printed in exponential notation.
8099
8100 @pre min_exp < 0
8101 @pre max_exp > 0
8102 */
format_buffer(char * buf,int len,int decimal_exponent,int min_exp,int max_exp)8103 inline char* format_buffer(char* buf, int len, int decimal_exponent,
8104 int min_exp, int max_exp)
8105 {
8106 assert(min_exp < 0);
8107 assert(max_exp > 0);
8108
8109 const int k = len;
8110 const int n = len + decimal_exponent;
8111
8112 // v = buf * 10^(n-k)
8113 // k is the length of the buffer (number of decimal digits)
8114 // n is the position of the decimal point relative to the start of the buffer.
8115
8116 if (k <= n and n <= max_exp)
8117 {
8118 // digits[000]
8119 // len <= max_exp + 2
8120
8121 std::memset(buf + k, '0', static_cast<size_t>(n - k));
8122 // Make it look like a floating-point number (#362, #378)
8123 buf[n + 0] = '.';
8124 buf[n + 1] = '0';
8125 return buf + (n + 2);
8126 }
8127
8128 if (0 < n and n <= max_exp)
8129 {
8130 // dig.its
8131 // len <= max_digits10 + 1
8132
8133 assert(k > n);
8134
8135 std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
8136 buf[n] = '.';
8137 return buf + (k + 1);
8138 }
8139
8140 if (min_exp < n and n <= 0)
8141 {
8142 // 0.[000]digits
8143 // len <= 2 + (-min_exp - 1) + max_digits10
8144
8145 std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
8146 buf[0] = '0';
8147 buf[1] = '.';
8148 std::memset(buf + 2, '0', static_cast<size_t>(-n));
8149 return buf + (2 + (-n) + k);
8150 }
8151
8152 if (k == 1)
8153 {
8154 // dE+123
8155 // len <= 1 + 5
8156
8157 buf += 1;
8158 }
8159 else
8160 {
8161 // d.igitsE+123
8162 // len <= max_digits10 + 1 + 5
8163
8164 std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
8165 buf[1] = '.';
8166 buf += 1 + k;
8167 }
8168
8169 *buf++ = 'e';
8170 return append_exponent(buf, n - 1);
8171 }
8172
8173 } // namespace dtoa_impl
8174
8175 /*!
8176 @brief generates a decimal representation of the floating-point number value in [first, last).
8177
8178 The format of the resulting decimal representation is similar to printf's %g
8179 format. Returns an iterator pointing past-the-end of the decimal representation.
8180
8181 @note The input number must be finite, i.e. NaN's and Inf's are not supported.
8182 @note The buffer must be large enough.
8183 @note The result is NOT null-terminated.
8184 */
8185 template <typename FloatType>
to_chars(char * first,char * last,FloatType value)8186 char* to_chars(char* first, char* last, FloatType value)
8187 {
8188 static_cast<void>(last); // maybe unused - fix warning
8189 assert(std::isfinite(value));
8190
8191 // Use signbit(value) instead of (value < 0) since signbit works for -0.
8192 if (std::signbit(value))
8193 {
8194 value = -value;
8195 *first++ = '-';
8196 }
8197
8198 if (value == 0) // +-0
8199 {
8200 *first++ = '0';
8201 // Make it look like a floating-point number (#362, #378)
8202 *first++ = '.';
8203 *first++ = '0';
8204 return first;
8205 }
8206
8207 assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
8208
8209 // Compute v = buffer * 10^decimal_exponent.
8210 // The decimal digits are stored in the buffer, which needs to be interpreted
8211 // as an unsigned decimal integer.
8212 // len is the length of the buffer, i.e. the number of decimal digits.
8213 int len = 0;
8214 int decimal_exponent = 0;
8215 dtoa_impl::grisu2(first, len, decimal_exponent, value);
8216
8217 assert(len <= std::numeric_limits<FloatType>::max_digits10);
8218
8219 // Format the buffer like printf("%.*g", prec, value)
8220 constexpr int kMinExp = -4;
8221 // Use digits10 here to increase compatibility with version 2.
8222 constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
8223
8224 assert(last - first >= kMaxExp + 2);
8225 assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
8226 assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
8227
8228 return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
8229 }
8230
8231 } // namespace detail
8232 } // namespace nlohmann
8233
8234 // #include <nlohmann/detail/macro_scope.hpp>
8235
8236 // #include <nlohmann/detail/meta.hpp>
8237
8238 // #include <nlohmann/detail/output/output_adapters.hpp>
8239
8240 // #include <nlohmann/detail/value_t.hpp>
8241
8242
8243 namespace nlohmann
8244 {
8245 namespace detail
8246 {
8247 ///////////////////
8248 // serialization //
8249 ///////////////////
8250
8251 template<typename BasicJsonType>
8252 class serializer
8253 {
8254 using string_t = typename BasicJsonType::string_t;
8255 using number_float_t = typename BasicJsonType::number_float_t;
8256 using number_integer_t = typename BasicJsonType::number_integer_t;
8257 using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
8258 static constexpr uint8_t UTF8_ACCEPT = 0;
8259 static constexpr uint8_t UTF8_REJECT = 1;
8260
8261 public:
8262 /*!
8263 @param[in] s output stream to serialize to
8264 @param[in] ichar indentation character to use
8265 */
serializer(output_adapter_t<char> s,const char ichar)8266 serializer(output_adapter_t<char> s, const char ichar)
8267 : o(std::move(s)), loc(std::localeconv()),
8268 thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep)),
8269 decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point)),
8270 indent_char(ichar), indent_string(512, indent_char)
8271 {}
8272
8273 // delete because of pointer members
8274 serializer(const serializer&) = delete;
8275 serializer& operator=(const serializer&) = delete;
8276
8277 /*!
8278 @brief internal implementation of the serialization function
8279
8280 This function is called by the public member function dump and organizes
8281 the serialization internally. The indentation level is propagated as
8282 additional parameter. In case of arrays and objects, the function is
8283 called recursively.
8284
8285 - strings and object keys are escaped using `escape_string()`
8286 - integer numbers are converted implicitly via `operator<<`
8287 - floating-point numbers are converted to a string using `"%g"` format
8288
8289 @param[in] val value to serialize
8290 @param[in] pretty_print whether the output shall be pretty-printed
8291 @param[in] indent_step the indent level
8292 @param[in] current_indent the current indent level (only used internally)
8293 */
dump(const BasicJsonType & val,const bool pretty_print,const bool ensure_ascii,const unsigned int indent_step,const unsigned int current_indent=0)8294 void dump(const BasicJsonType& val, const bool pretty_print,
8295 const bool ensure_ascii,
8296 const unsigned int indent_step,
8297 const unsigned int current_indent = 0)
8298 {
8299 switch (val.m_type)
8300 {
8301 case value_t::object:
8302 {
8303 if (val.m_value.object->empty())
8304 {
8305 o->write_characters("{}", 2);
8306 return;
8307 }
8308
8309 if (pretty_print)
8310 {
8311 o->write_characters("{\n", 2);
8312
8313 // variable to hold indentation for recursive calls
8314 const auto new_indent = current_indent + indent_step;
8315 if (JSON_UNLIKELY(indent_string.size() < new_indent))
8316 {
8317 indent_string.resize(indent_string.size() * 2, ' ');
8318 }
8319
8320 // first n-1 elements
8321 auto i = val.m_value.object->cbegin();
8322 for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
8323 {
8324 o->write_characters(indent_string.c_str(), new_indent);
8325 o->write_character('\"');
8326 dump_escaped(i->first, ensure_ascii);
8327 o->write_characters("\": ", 3);
8328 dump(i->second, true, ensure_ascii, indent_step, new_indent);
8329 o->write_characters(",\n", 2);
8330 }
8331
8332 // last element
8333 assert(i != val.m_value.object->cend());
8334 assert(std::next(i) == val.m_value.object->cend());
8335 o->write_characters(indent_string.c_str(), new_indent);
8336 o->write_character('\"');
8337 dump_escaped(i->first, ensure_ascii);
8338 o->write_characters("\": ", 3);
8339 dump(i->second, true, ensure_ascii, indent_step, new_indent);
8340
8341 o->write_character('\n');
8342 o->write_characters(indent_string.c_str(), current_indent);
8343 o->write_character('}');
8344 }
8345 else
8346 {
8347 o->write_character('{');
8348
8349 // first n-1 elements
8350 auto i = val.m_value.object->cbegin();
8351 for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
8352 {
8353 o->write_character('\"');
8354 dump_escaped(i->first, ensure_ascii);
8355 o->write_characters("\":", 2);
8356 dump(i->second, false, ensure_ascii, indent_step, current_indent);
8357 o->write_character(',');
8358 }
8359
8360 // last element
8361 assert(i != val.m_value.object->cend());
8362 assert(std::next(i) == val.m_value.object->cend());
8363 o->write_character('\"');
8364 dump_escaped(i->first, ensure_ascii);
8365 o->write_characters("\":", 2);
8366 dump(i->second, false, ensure_ascii, indent_step, current_indent);
8367
8368 o->write_character('}');
8369 }
8370
8371 return;
8372 }
8373
8374 case value_t::array:
8375 {
8376 if (val.m_value.array->empty())
8377 {
8378 o->write_characters("[]", 2);
8379 return;
8380 }
8381
8382 if (pretty_print)
8383 {
8384 // QISKIT EDIT this makes pretty print leave arrays on a single line
8385 bool QISKIT_FORMAT = true;
8386 if (QISKIT_FORMAT) {
8387 o->write_character('[');
8388
8389 // first n-1 elements
8390 for (auto i = val.m_value.array->cbegin();
8391 i != val.m_value.array->cend() - 1; ++i)
8392 {
8393 dump(*i, true, ensure_ascii, indent_step, current_indent);
8394 o->write_characters(", ", 2);
8395 }
8396
8397 // last element
8398 assert(not val.m_value.array->empty());
8399 dump(val.m_value.array->back(), true, ensure_ascii, indent_step, current_indent);
8400
8401 o->write_character(']');
8402 }
8403 else // ORIGINAL
8404 {
8405 o->write_characters("[\n", 2);
8406
8407 // variable to hold indentation for recursive calls
8408 const auto new_indent = current_indent + indent_step;
8409 if (JSON_UNLIKELY(indent_string.size() < new_indent))
8410 {
8411 indent_string.resize(indent_string.size() * 2, ' ');
8412 }
8413
8414 // first n-1 elements
8415 for (auto i = val.m_value.array->cbegin();
8416 i != val.m_value.array->cend() - 1; ++i)
8417 {
8418 o->write_characters(indent_string.c_str(), new_indent);
8419 dump(*i, true, ensure_ascii, indent_step, new_indent);
8420 o->write_characters(",\n", 2);
8421 }
8422
8423 // last element
8424 assert(not val.m_value.array->empty());
8425 o->write_characters(indent_string.c_str(), new_indent);
8426 dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
8427
8428 o->write_character('\n');
8429 o->write_characters(indent_string.c_str(), current_indent);
8430 o->write_character(']');
8431 }
8432 }
8433 else
8434 {
8435 o->write_character('[');
8436
8437 // first n-1 elements
8438 for (auto i = val.m_value.array->cbegin();
8439 i != val.m_value.array->cend() - 1; ++i)
8440 {
8441 dump(*i, false, ensure_ascii, indent_step, current_indent);
8442 o->write_character(',');
8443 }
8444
8445 // last element
8446 assert(not val.m_value.array->empty());
8447 dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
8448
8449 o->write_character(']');
8450 }
8451
8452 return;
8453 }
8454
8455 case value_t::string:
8456 {
8457 o->write_character('\"');
8458 dump_escaped(*val.m_value.string, ensure_ascii);
8459 o->write_character('\"');
8460 return;
8461 }
8462
8463 case value_t::boolean:
8464 {
8465 if (val.m_value.boolean)
8466 {
8467 o->write_characters("true", 4);
8468 }
8469 else
8470 {
8471 o->write_characters("false", 5);
8472 }
8473 return;
8474 }
8475
8476 case value_t::number_integer:
8477 {
8478 dump_integer(val.m_value.number_integer);
8479 return;
8480 }
8481
8482 case value_t::number_unsigned:
8483 {
8484 dump_integer(val.m_value.number_unsigned);
8485 return;
8486 }
8487
8488 case value_t::number_float:
8489 {
8490 dump_float(val.m_value.number_float);
8491 return;
8492 }
8493
8494 case value_t::discarded:
8495 {
8496 o->write_characters("<discarded>", 11);
8497 return;
8498 }
8499
8500 case value_t::null:
8501 {
8502 o->write_characters("null", 4);
8503 return;
8504 }
8505 }
8506 }
8507
8508 private:
8509 /*!
8510 @brief dump escaped string
8511
8512 Escape a string by replacing certain special characters by a sequence of an
8513 escape character (backslash) and another character and other control
8514 characters by a sequence of "\u" followed by a four-digit hex
8515 representation. The escaped string is written to output stream @a o.
8516
8517 @param[in] s the string to escape
8518 @param[in] ensure_ascii whether to escape non-ASCII characters with
8519 \uXXXX sequences
8520
8521 @complexity Linear in the length of string @a s.
8522 */
dump_escaped(const string_t & s,const bool ensure_ascii)8523 void dump_escaped(const string_t& s, const bool ensure_ascii)
8524 {
8525 uint32_t codepoint;
8526 uint8_t state = UTF8_ACCEPT;
8527 std::size_t bytes = 0; // number of bytes written to string_buffer
8528
8529 for (std::size_t i = 0; i < s.size(); ++i)
8530 {
8531 const auto byte = static_cast<uint8_t>(s[i]);
8532
8533 switch (decode(state, codepoint, byte))
8534 {
8535 case UTF8_ACCEPT: // decode found a new code point
8536 {
8537 switch (codepoint)
8538 {
8539 case 0x08: // backspace
8540 {
8541 string_buffer[bytes++] = '\\';
8542 string_buffer[bytes++] = 'b';
8543 break;
8544 }
8545
8546 case 0x09: // horizontal tab
8547 {
8548 string_buffer[bytes++] = '\\';
8549 string_buffer[bytes++] = 't';
8550 break;
8551 }
8552
8553 case 0x0A: // newline
8554 {
8555 string_buffer[bytes++] = '\\';
8556 string_buffer[bytes++] = 'n';
8557 break;
8558 }
8559
8560 case 0x0C: // formfeed
8561 {
8562 string_buffer[bytes++] = '\\';
8563 string_buffer[bytes++] = 'f';
8564 break;
8565 }
8566
8567 case 0x0D: // carriage return
8568 {
8569 string_buffer[bytes++] = '\\';
8570 string_buffer[bytes++] = 'r';
8571 break;
8572 }
8573
8574 case 0x22: // quotation mark
8575 {
8576 string_buffer[bytes++] = '\\';
8577 string_buffer[bytes++] = '\"';
8578 break;
8579 }
8580
8581 case 0x5C: // reverse solidus
8582 {
8583 string_buffer[bytes++] = '\\';
8584 string_buffer[bytes++] = '\\';
8585 break;
8586 }
8587
8588 default:
8589 {
8590 // escape control characters (0x00..0x1F) or, if
8591 // ensure_ascii parameter is used, non-ASCII characters
8592 if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
8593 {
8594 if (codepoint <= 0xFFFF)
8595 {
8596 std::snprintf(string_buffer.data() + bytes, 7, "\\u%04x",
8597 static_cast<uint16_t>(codepoint));
8598 bytes += 6;
8599 }
8600 else
8601 {
8602 std::snprintf(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
8603 static_cast<uint16_t>(0xD7C0 + (codepoint >> 10)),
8604 static_cast<uint16_t>(0xDC00 + (codepoint & 0x3FF)));
8605 bytes += 12;
8606 }
8607 }
8608 else
8609 {
8610 // copy byte to buffer (all previous bytes
8611 // been copied have in default case above)
8612 string_buffer[bytes++] = s[i];
8613 }
8614 break;
8615 }
8616 }
8617
8618 // write buffer and reset index; there must be 13 bytes
8619 // left, as this is the maximal number of bytes to be
8620 // written ("\uxxxx\uxxxx\0") for one code point
8621 if (string_buffer.size() - bytes < 13)
8622 {
8623 o->write_characters(string_buffer.data(), bytes);
8624 bytes = 0;
8625 }
8626 break;
8627 }
8628
8629 case UTF8_REJECT: // decode found invalid UTF-8 byte
8630 {
8631 std::stringstream ss;
8632 ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(byte);
8633 JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str()));
8634 }
8635
8636 default: // decode found yet incomplete multi-byte code point
8637 {
8638 if (not ensure_ascii)
8639 {
8640 // code point will not be escaped - copy byte to buffer
8641 string_buffer[bytes++] = s[i];
8642 }
8643 break;
8644 }
8645 }
8646 }
8647
8648 if (JSON_LIKELY(state == UTF8_ACCEPT))
8649 {
8650 // write buffer
8651 if (bytes > 0)
8652 {
8653 o->write_characters(string_buffer.data(), bytes);
8654 }
8655 }
8656 else
8657 {
8658 // we finish reading, but do not accept: string was incomplete
8659 std::stringstream ss;
8660 ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(static_cast<uint8_t>(s.back()));
8661 JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str()));
8662 }
8663 }
8664
8665 /*!
8666 @brief dump an integer
8667
8668 Dump a given integer to output stream @a o. Works internally with
8669 @a number_buffer.
8670
8671 @param[in] x integer number (signed or unsigned) to dump
8672 @tparam NumberType either @a number_integer_t or @a number_unsigned_t
8673 */
8674 template<typename NumberType, detail::enable_if_t<
8675 std::is_same<NumberType, number_unsigned_t>::value or
8676 std::is_same<NumberType, number_integer_t>::value,
8677 int> = 0>
dump_integer(NumberType x)8678 void dump_integer(NumberType x)
8679 {
8680 // special case for "0"
8681 if (x == 0)
8682 {
8683 o->write_character('0');
8684 return;
8685 }
8686
8687 const bool is_negative = (x <= 0) and (x != 0); // see issue #755
8688 std::size_t i = 0;
8689
8690 while (x != 0)
8691 {
8692 // spare 1 byte for '\0'
8693 assert(i < number_buffer.size() - 1);
8694
8695 const auto digit = std::labs(static_cast<long>(x % 10));
8696 number_buffer[i++] = static_cast<char>('0' + digit);
8697 x /= 10;
8698 }
8699
8700 if (is_negative)
8701 {
8702 // make sure there is capacity for the '-'
8703 assert(i < number_buffer.size() - 2);
8704 number_buffer[i++] = '-';
8705 }
8706
8707 std::reverse(number_buffer.begin(), number_buffer.begin() + i);
8708 o->write_characters(number_buffer.data(), i);
8709 }
8710
8711 /*!
8712 @brief dump a floating-point number
8713
8714 Dump a given floating-point number to output stream @a o. Works internally
8715 with @a number_buffer.
8716
8717 @param[in] x floating-point number to dump
8718 */
dump_float(number_float_t x)8719 void dump_float(number_float_t x)
8720 {
8721 // NaN / inf
8722 if (not std::isfinite(x))
8723 {
8724 o->write_characters("null", 4);
8725 return;
8726 }
8727
8728 // If number_float_t is an IEEE-754 single or double precision number,
8729 // use the Grisu2 algorithm to produce short numbers which are
8730 // guaranteed to round-trip, using strtof and strtod, resp.
8731 //
8732 // NB: The test below works if <long double> == <double>.
8733 static constexpr bool is_ieee_single_or_double
8734 = (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 24 and std::numeric_limits<number_float_t>::max_exponent == 128) or
8735 (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 53 and std::numeric_limits<number_float_t>::max_exponent == 1024);
8736
8737 dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
8738 }
8739
dump_float(number_float_t x,std::true_type)8740 void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
8741 {
8742 char* begin = number_buffer.data();
8743 char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
8744
8745 o->write_characters(begin, static_cast<size_t>(end - begin));
8746 }
8747
dump_float(number_float_t x,std::false_type)8748 void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
8749 {
8750 // get number of digits for a float -> text -> float round-trip
8751 static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
8752
8753 // the actual conversion
8754 std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
8755
8756 // negative value indicates an error
8757 assert(len > 0);
8758 // check if buffer was large enough
8759 assert(static_cast<std::size_t>(len) < number_buffer.size());
8760
8761 // erase thousands separator
8762 if (thousands_sep != '\0')
8763 {
8764 const auto end = std::remove(number_buffer.begin(),
8765 number_buffer.begin() + len, thousands_sep);
8766 std::fill(end, number_buffer.end(), '\0');
8767 assert((end - number_buffer.begin()) <= len);
8768 len = (end - number_buffer.begin());
8769 }
8770
8771 // convert decimal point to '.'
8772 if (decimal_point != '\0' and decimal_point != '.')
8773 {
8774 const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
8775 if (dec_pos != number_buffer.end())
8776 {
8777 *dec_pos = '.';
8778 }
8779 }
8780
8781 o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
8782
8783 // determine if need to append ".0"
8784 const bool value_is_int_like =
8785 std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
8786 [](char c)
8787 {
8788 return (c == '.' or c == 'e');
8789 });
8790
8791 if (value_is_int_like)
8792 {
8793 o->write_characters(".0", 2);
8794 }
8795 }
8796
8797 /*!
8798 @brief check whether a string is UTF-8 encoded
8799
8800 The function checks each byte of a string whether it is UTF-8 encoded. The
8801 result of the check is stored in the @a state parameter. The function must
8802 be called initially with state 0 (accept). State 1 means the string must
8803 be rejected, because the current byte is not allowed. If the string is
8804 completely processed, but the state is non-zero, the string ended
8805 prematurely; that is, the last byte indicated more bytes should have
8806 followed.
8807
8808 @param[in,out] state the state of the decoding
8809 @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
8810 @param[in] byte next byte to decode
8811 @return new state
8812
8813 @note The function has been edited: a std::array is used.
8814
8815 @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
8816 @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
8817 */
decode(uint8_t & state,uint32_t & codep,const uint8_t byte)8818 static uint8_t decode(uint8_t& state, uint32_t& codep, const uint8_t byte) noexcept
8819 {
8820 static const std::array<uint8_t, 400> utf8d =
8821 {
8822 {
8823 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F
8824 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F
8825 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F
8826 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F
8827 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F
8828 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF
8829 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF
8830 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
8831 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
8832 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
8833 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2
8834 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4
8835 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6
8836 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8
8837 }
8838 };
8839
8840 const uint8_t type = utf8d[byte];
8841
8842 codep = (state != UTF8_ACCEPT)
8843 ? (byte & 0x3fu) | (codep << 6)
8844 : static_cast<uint32_t>(0xff >> type) & (byte);
8845
8846 state = utf8d[256u + state * 16u + type];
8847 return state;
8848 }
8849
8850 private:
8851 /// the output of the serializer
8852 output_adapter_t<char> o = nullptr;
8853
8854 /// a (hopefully) large enough character buffer
8855 std::array<char, 64> number_buffer{{}};
8856
8857 /// the locale
8858 const std::lconv* loc = nullptr;
8859 /// the locale's thousand separator character
8860 const char thousands_sep = '\0';
8861 /// the locale's decimal point character
8862 const char decimal_point = '\0';
8863
8864 /// string buffer
8865 std::array<char, 512> string_buffer{{}};
8866
8867 /// the indentation character
8868 const char indent_char;
8869 /// the indentation string
8870 string_t indent_string;
8871 };
8872 }
8873 }
8874
8875 // #include <nlohmann/detail/json_ref.hpp>
8876
8877
8878 #include <initializer_list>
8879 #include <utility>
8880
8881 namespace nlohmann
8882 {
8883 namespace detail
8884 {
8885 template<typename BasicJsonType>
8886 class json_ref
8887 {
8888 public:
8889 using value_type = BasicJsonType;
8890
json_ref(value_type && value)8891 json_ref(value_type&& value)
8892 : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
8893 {}
8894
json_ref(const value_type & value)8895 json_ref(const value_type& value)
8896 : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
8897 {}
8898
json_ref(std::initializer_list<json_ref> init)8899 json_ref(std::initializer_list<json_ref> init)
8900 : owned_value(init), value_ref(&owned_value), is_rvalue(true)
8901 {}
8902
8903 template<class... Args>
json_ref(Args &&...args)8904 json_ref(Args&& ... args)
8905 : owned_value(std::forward<Args>(args)...), value_ref(&owned_value), is_rvalue(true)
8906 {}
8907
8908 // class should be movable only
8909 json_ref(json_ref&&) = default;
8910 json_ref(const json_ref&) = delete;
8911 json_ref& operator=(const json_ref&) = delete;
8912
moved_or_copied() const8913 value_type moved_or_copied() const
8914 {
8915 if (is_rvalue)
8916 {
8917 return std::move(*value_ref);
8918 }
8919 return *value_ref;
8920 }
8921
operator *() const8922 value_type const& operator*() const
8923 {
8924 return *static_cast<value_type const*>(value_ref);
8925 }
8926
operator ->() const8927 value_type const* operator->() const
8928 {
8929 return static_cast<value_type const*>(value_ref);
8930 }
8931
8932 private:
8933 mutable value_type owned_value = nullptr;
8934 value_type* value_ref = nullptr;
8935 const bool is_rvalue;
8936 };
8937 }
8938 }
8939
8940 // #include <nlohmann/detail/json_pointer.hpp>
8941
8942
8943 #include <cassert> // assert
8944 #include <numeric> // accumulate
8945 #include <string> // string
8946 #include <vector> // vector
8947
8948 // #include <nlohmann/detail/macro_scope.hpp>
8949
8950 // #include <nlohmann/detail/exceptions.hpp>
8951
8952 // #include <nlohmann/detail/value_t.hpp>
8953
8954
8955 namespace nlohmann
8956 {
8957 template<typename BasicJsonType>
8958 class json_pointer
8959 {
8960 // allow basic_json to access private members
8961 NLOHMANN_BASIC_JSON_TPL_DECLARATION
8962 friend class basic_json;
8963
8964 public:
8965 /*!
8966 @brief create JSON pointer
8967
8968 Create a JSON pointer according to the syntax described in
8969 [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
8970
8971 @param[in] s string representing the JSON pointer; if omitted, the empty
8972 string is assumed which references the whole JSON value
8973
8974 @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
8975 not begin with a slash (`/`); see example below
8976
8977 @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
8978 not followed by `0` (representing `~`) or `1` (representing `/`); see
8979 example below
8980
8981 @liveexample{The example shows the construction several valid JSON pointers
8982 as well as the exceptional behavior.,json_pointer}
8983
8984 @since version 2.0.0
8985 */
json_pointer(const std::string & s="")8986 explicit json_pointer(const std::string& s = "")
8987 : reference_tokens(split(s))
8988 {}
8989
8990 /*!
8991 @brief return a string representation of the JSON pointer
8992
8993 @invariant For each JSON pointer `ptr`, it holds:
8994 @code {.cpp}
8995 ptr == json_pointer(ptr.to_string());
8996 @endcode
8997
8998 @return a string representation of the JSON pointer
8999
9000 @liveexample{The example shows the result of `to_string`.,
9001 json_pointer__to_string}
9002
9003 @since version 2.0.0
9004 */
to_string() const9005 std::string to_string() const noexcept
9006 {
9007 return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
9008 std::string{},
9009 [](const std::string & a, const std::string & b)
9010 {
9011 return a + "/" + escape(b);
9012 });
9013 }
9014
9015 /// @copydoc to_string()
operator std::string() const9016 operator std::string() const
9017 {
9018 return to_string();
9019 }
9020
9021 /*!
9022 @param[in] s reference token to be converted into an array index
9023
9024 @return integer representation of @a s
9025
9026 @throw out_of_range.404 if string @a s could not be converted to an integer
9027 */
array_index(const std::string & s)9028 static int array_index(const std::string& s)
9029 {
9030 std::size_t processed_chars = 0;
9031 const int res = std::stoi(s, &processed_chars);
9032
9033 // check if the string was completely read
9034 if (JSON_UNLIKELY(processed_chars != s.size()))
9035 {
9036 JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
9037 }
9038
9039 return res;
9040 }
9041
9042 private:
9043 /*!
9044 @brief remove and return last reference pointer
9045 @throw out_of_range.405 if JSON pointer has no parent
9046 */
pop_back()9047 std::string pop_back()
9048 {
9049 if (JSON_UNLIKELY(is_root()))
9050 {
9051 JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
9052 }
9053
9054 auto last = reference_tokens.back();
9055 reference_tokens.pop_back();
9056 return last;
9057 }
9058
9059 /// return whether pointer points to the root document
is_root() const9060 bool is_root() const
9061 {
9062 return reference_tokens.empty();
9063 }
9064
top() const9065 json_pointer top() const
9066 {
9067 if (JSON_UNLIKELY(is_root()))
9068 {
9069 JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
9070 }
9071
9072 json_pointer result = *this;
9073 result.reference_tokens = {reference_tokens[0]};
9074 return result;
9075 }
9076
9077 /*!
9078 @brief create and return a reference to the pointed to value
9079
9080 @complexity Linear in the number of reference tokens.
9081
9082 @throw parse_error.109 if array index is not a number
9083 @throw type_error.313 if value cannot be unflattened
9084 */
get_and_create(BasicJsonType & j) const9085 BasicJsonType& get_and_create(BasicJsonType& j) const
9086 {
9087 using size_type = typename BasicJsonType::size_type;
9088 auto result = &j;
9089
9090 // in case no reference tokens exist, return a reference to the JSON value
9091 // j which will be overwritten by a primitive value
9092 for (const auto& reference_token : reference_tokens)
9093 {
9094 switch (result->m_type)
9095 {
9096 case detail::value_t::null:
9097 {
9098 if (reference_token == "0")
9099 {
9100 // start a new array if reference token is 0
9101 result = &result->operator[](0);
9102 }
9103 else
9104 {
9105 // start a new object otherwise
9106 result = &result->operator[](reference_token);
9107 }
9108 break;
9109 }
9110
9111 case detail::value_t::object:
9112 {
9113 // create an entry in the object
9114 result = &result->operator[](reference_token);
9115 break;
9116 }
9117
9118 case detail::value_t::array:
9119 {
9120 // create an entry in the array
9121 JSON_TRY
9122 {
9123 result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
9124 }
9125 JSON_CATCH(std::invalid_argument&)
9126 {
9127 JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
9128 }
9129 break;
9130 }
9131
9132 /*
9133 The following code is only reached if there exists a reference
9134 token _and_ the current value is primitive. In this case, we have
9135 an error situation, because primitive values may only occur as
9136 single value; that is, with an empty list of reference tokens.
9137 */
9138 default:
9139 JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
9140 }
9141 }
9142
9143 return *result;
9144 }
9145
9146 /*!
9147 @brief return a reference to the pointed to value
9148
9149 @note This version does not throw if a value is not present, but tries to
9150 create nested values instead. For instance, calling this function
9151 with pointer `"/this/that"` on a null value is equivalent to calling
9152 `operator[]("this").operator[]("that")` on that value, effectively
9153 changing the null value to an object.
9154
9155 @param[in] ptr a JSON value
9156
9157 @return reference to the JSON value pointed to by the JSON pointer
9158
9159 @complexity Linear in the length of the JSON pointer.
9160
9161 @throw parse_error.106 if an array index begins with '0'
9162 @throw parse_error.109 if an array index was not a number
9163 @throw out_of_range.404 if the JSON pointer can not be resolved
9164 */
get_unchecked(BasicJsonType * ptr) const9165 BasicJsonType& get_unchecked(BasicJsonType* ptr) const
9166 {
9167 using size_type = typename BasicJsonType::size_type;
9168 for (const auto& reference_token : reference_tokens)
9169 {
9170 // convert null values to arrays or objects before continuing
9171 if (ptr->m_type == detail::value_t::null)
9172 {
9173 // check if reference token is a number
9174 const bool nums =
9175 std::all_of(reference_token.begin(), reference_token.end(),
9176 [](const char x)
9177 {
9178 return (x >= '0' and x <= '9');
9179 });
9180
9181 // change value to array for numbers or "-" or to object otherwise
9182 *ptr = (nums or reference_token == "-")
9183 ? detail::value_t::array
9184 : detail::value_t::object;
9185 }
9186
9187 switch (ptr->m_type)
9188 {
9189 case detail::value_t::object:
9190 {
9191 // use unchecked object access
9192 ptr = &ptr->operator[](reference_token);
9193 break;
9194 }
9195
9196 case detail::value_t::array:
9197 {
9198 // error condition (cf. RFC 6901, Sect. 4)
9199 if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
9200 {
9201 JSON_THROW(detail::parse_error::create(106, 0,
9202 "array index '" + reference_token +
9203 "' must not begin with '0'"));
9204 }
9205
9206 if (reference_token == "-")
9207 {
9208 // explicitly treat "-" as index beyond the end
9209 ptr = &ptr->operator[](ptr->m_value.array->size());
9210 }
9211 else
9212 {
9213 // convert array index to number; unchecked access
9214 JSON_TRY
9215 {
9216 ptr = &ptr->operator[](
9217 static_cast<size_type>(array_index(reference_token)));
9218 }
9219 JSON_CATCH(std::invalid_argument&)
9220 {
9221 JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
9222 }
9223 }
9224 break;
9225 }
9226
9227 default:
9228 JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
9229 }
9230 }
9231
9232 return *ptr;
9233 }
9234
9235 /*!
9236 @throw parse_error.106 if an array index begins with '0'
9237 @throw parse_error.109 if an array index was not a number
9238 @throw out_of_range.402 if the array index '-' is used
9239 @throw out_of_range.404 if the JSON pointer can not be resolved
9240 */
get_checked(BasicJsonType * ptr) const9241 BasicJsonType& get_checked(BasicJsonType* ptr) const
9242 {
9243 using size_type = typename BasicJsonType::size_type;
9244 for (const auto& reference_token : reference_tokens)
9245 {
9246 switch (ptr->m_type)
9247 {
9248 case detail::value_t::object:
9249 {
9250 // note: at performs range check
9251 ptr = &ptr->at(reference_token);
9252 break;
9253 }
9254
9255 case detail::value_t::array:
9256 {
9257 if (JSON_UNLIKELY(reference_token == "-"))
9258 {
9259 // "-" always fails the range check
9260 JSON_THROW(detail::out_of_range::create(402,
9261 "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
9262 ") is out of range"));
9263 }
9264
9265 // error condition (cf. RFC 6901, Sect. 4)
9266 if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
9267 {
9268 JSON_THROW(detail::parse_error::create(106, 0,
9269 "array index '" + reference_token +
9270 "' must not begin with '0'"));
9271 }
9272
9273 // note: at performs range check
9274 JSON_TRY
9275 {
9276 ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
9277 }
9278 JSON_CATCH(std::invalid_argument&)
9279 {
9280 JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
9281 }
9282 break;
9283 }
9284
9285 default:
9286 JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
9287 }
9288 }
9289
9290 return *ptr;
9291 }
9292
9293 /*!
9294 @brief return a const reference to the pointed to value
9295
9296 @param[in] ptr a JSON value
9297
9298 @return const reference to the JSON value pointed to by the JSON
9299 pointer
9300
9301 @throw parse_error.106 if an array index begins with '0'
9302 @throw parse_error.109 if an array index was not a number
9303 @throw out_of_range.402 if the array index '-' is used
9304 @throw out_of_range.404 if the JSON pointer can not be resolved
9305 */
get_unchecked(const BasicJsonType * ptr) const9306 const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
9307 {
9308 using size_type = typename BasicJsonType::size_type;
9309 for (const auto& reference_token : reference_tokens)
9310 {
9311 switch (ptr->m_type)
9312 {
9313 case detail::value_t::object:
9314 {
9315 // use unchecked object access
9316 ptr = &ptr->operator[](reference_token);
9317 break;
9318 }
9319
9320 case detail::value_t::array:
9321 {
9322 if (JSON_UNLIKELY(reference_token == "-"))
9323 {
9324 // "-" cannot be used for const access
9325 JSON_THROW(detail::out_of_range::create(402,
9326 "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
9327 ") is out of range"));
9328 }
9329
9330 // error condition (cf. RFC 6901, Sect. 4)
9331 if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
9332 {
9333 JSON_THROW(detail::parse_error::create(106, 0,
9334 "array index '" + reference_token +
9335 "' must not begin with '0'"));
9336 }
9337
9338 // use unchecked array access
9339 JSON_TRY
9340 {
9341 ptr = &ptr->operator[](
9342 static_cast<size_type>(array_index(reference_token)));
9343 }
9344 JSON_CATCH(std::invalid_argument&)
9345 {
9346 JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
9347 }
9348 break;
9349 }
9350
9351 default:
9352 JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
9353 }
9354 }
9355
9356 return *ptr;
9357 }
9358
9359 /*!
9360 @throw parse_error.106 if an array index begins with '0'
9361 @throw parse_error.109 if an array index was not a number
9362 @throw out_of_range.402 if the array index '-' is used
9363 @throw out_of_range.404 if the JSON pointer can not be resolved
9364 */
get_checked(const BasicJsonType * ptr) const9365 const BasicJsonType& get_checked(const BasicJsonType* ptr) const
9366 {
9367 using size_type = typename BasicJsonType::size_type;
9368 for (const auto& reference_token : reference_tokens)
9369 {
9370 switch (ptr->m_type)
9371 {
9372 case detail::value_t::object:
9373 {
9374 // note: at performs range check
9375 ptr = &ptr->at(reference_token);
9376 break;
9377 }
9378
9379 case detail::value_t::array:
9380 {
9381 if (JSON_UNLIKELY(reference_token == "-"))
9382 {
9383 // "-" always fails the range check
9384 JSON_THROW(detail::out_of_range::create(402,
9385 "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
9386 ") is out of range"));
9387 }
9388
9389 // error condition (cf. RFC 6901, Sect. 4)
9390 if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
9391 {
9392 JSON_THROW(detail::parse_error::create(106, 0,
9393 "array index '" + reference_token +
9394 "' must not begin with '0'"));
9395 }
9396
9397 // note: at performs range check
9398 JSON_TRY
9399 {
9400 ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
9401 }
9402 JSON_CATCH(std::invalid_argument&)
9403 {
9404 JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
9405 }
9406 break;
9407 }
9408
9409 default:
9410 JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
9411 }
9412 }
9413
9414 return *ptr;
9415 }
9416
9417 /*!
9418 @brief split the string input to reference tokens
9419
9420 @note This function is only called by the json_pointer constructor.
9421 All exceptions below are documented there.
9422
9423 @throw parse_error.107 if the pointer is not empty or begins with '/'
9424 @throw parse_error.108 if character '~' is not followed by '0' or '1'
9425 */
split(const std::string & reference_string)9426 static std::vector<std::string> split(const std::string& reference_string)
9427 {
9428 std::vector<std::string> result;
9429
9430 // special case: empty reference string -> no reference tokens
9431 if (reference_string.empty())
9432 {
9433 return result;
9434 }
9435
9436 // check if nonempty reference string begins with slash
9437 if (JSON_UNLIKELY(reference_string[0] != '/'))
9438 {
9439 JSON_THROW(detail::parse_error::create(107, 1,
9440 "JSON pointer must be empty or begin with '/' - was: '" +
9441 reference_string + "'"));
9442 }
9443
9444 // extract the reference tokens:
9445 // - slash: position of the last read slash (or end of string)
9446 // - start: position after the previous slash
9447 for (
9448 // search for the first slash after the first character
9449 std::size_t slash = reference_string.find_first_of('/', 1),
9450 // set the beginning of the first reference token
9451 start = 1;
9452 // we can stop if start == string::npos+1 = 0
9453 start != 0;
9454 // set the beginning of the next reference token
9455 // (will eventually be 0 if slash == std::string::npos)
9456 start = slash + 1,
9457 // find next slash
9458 slash = reference_string.find_first_of('/', start))
9459 {
9460 // use the text between the beginning of the reference token
9461 // (start) and the last slash (slash).
9462 auto reference_token = reference_string.substr(start, slash - start);
9463
9464 // check reference tokens are properly escaped
9465 for (std::size_t pos = reference_token.find_first_of('~');
9466 pos != std::string::npos;
9467 pos = reference_token.find_first_of('~', pos + 1))
9468 {
9469 assert(reference_token[pos] == '~');
9470
9471 // ~ must be followed by 0 or 1
9472 if (JSON_UNLIKELY(pos == reference_token.size() - 1 or
9473 (reference_token[pos + 1] != '0' and
9474 reference_token[pos + 1] != '1')))
9475 {
9476 JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
9477 }
9478 }
9479
9480 // finally, store the reference token
9481 unescape(reference_token);
9482 result.push_back(reference_token);
9483 }
9484
9485 return result;
9486 }
9487
9488 /*!
9489 @brief replace all occurrences of a substring by another string
9490
9491 @param[in,out] s the string to manipulate; changed so that all
9492 occurrences of @a f are replaced with @a t
9493 @param[in] f the substring to replace with @a t
9494 @param[in] t the string to replace @a f
9495
9496 @pre The search string @a f must not be empty. **This precondition is
9497 enforced with an assertion.**
9498
9499 @since version 2.0.0
9500 */
replace_substring(std::string & s,const std::string & f,const std::string & t)9501 static void replace_substring(std::string& s, const std::string& f,
9502 const std::string& t)
9503 {
9504 assert(not f.empty());
9505 for (auto pos = s.find(f); // find first occurrence of f
9506 pos != std::string::npos; // make sure f was found
9507 s.replace(pos, f.size(), t), // replace with t, and
9508 pos = s.find(f, pos + t.size())) // find next occurrence of f
9509 {}
9510 }
9511
9512 /// escape "~"" to "~0" and "/" to "~1"
escape(std::string s)9513 static std::string escape(std::string s)
9514 {
9515 replace_substring(s, "~", "~0");
9516 replace_substring(s, "/", "~1");
9517 return s;
9518 }
9519
9520 /// unescape "~1" to tilde and "~0" to slash (order is important!)
unescape(std::string & s)9521 static void unescape(std::string& s)
9522 {
9523 replace_substring(s, "~1", "/");
9524 replace_substring(s, "~0", "~");
9525 }
9526
9527 /*!
9528 @param[in] reference_string the reference string to the current value
9529 @param[in] value the value to consider
9530 @param[in,out] result the result object to insert values to
9531
9532 @note Empty objects or arrays are flattened to `null`.
9533 */
flatten(const std::string & reference_string,const BasicJsonType & value,BasicJsonType & result)9534 static void flatten(const std::string& reference_string,
9535 const BasicJsonType& value,
9536 BasicJsonType& result)
9537 {
9538 switch (value.m_type)
9539 {
9540 case detail::value_t::array:
9541 {
9542 if (value.m_value.array->empty())
9543 {
9544 // flatten empty array as null
9545 result[reference_string] = nullptr;
9546 }
9547 else
9548 {
9549 // iterate array and use index as reference string
9550 for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
9551 {
9552 flatten(reference_string + "/" + std::to_string(i),
9553 value.m_value.array->operator[](i), result);
9554 }
9555 }
9556 break;
9557 }
9558
9559 case detail::value_t::object:
9560 {
9561 if (value.m_value.object->empty())
9562 {
9563 // flatten empty object as null
9564 result[reference_string] = nullptr;
9565 }
9566 else
9567 {
9568 // iterate object and use keys as reference string
9569 for (const auto& element : *value.m_value.object)
9570 {
9571 flatten(reference_string + "/" + escape(element.first), element.second, result);
9572 }
9573 }
9574 break;
9575 }
9576
9577 default:
9578 {
9579 // add primitive value with its reference string
9580 result[reference_string] = value;
9581 break;
9582 }
9583 }
9584 }
9585
9586 /*!
9587 @param[in] value flattened JSON
9588
9589 @return unflattened JSON
9590
9591 @throw parse_error.109 if array index is not a number
9592 @throw type_error.314 if value is not an object
9593 @throw type_error.315 if object values are not primitive
9594 @throw type_error.313 if value cannot be unflattened
9595 */
9596 static BasicJsonType
unflatten(const BasicJsonType & value)9597 unflatten(const BasicJsonType& value)
9598 {
9599 if (JSON_UNLIKELY(not value.is_object()))
9600 {
9601 JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
9602 }
9603
9604 BasicJsonType result;
9605
9606 // iterate the JSON object values
9607 for (const auto& element : *value.m_value.object)
9608 {
9609 if (JSON_UNLIKELY(not element.second.is_primitive()))
9610 {
9611 JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
9612 }
9613
9614 // assign value to reference pointed to by JSON pointer; Note that if
9615 // the JSON pointer is "" (i.e., points to the whole value), function
9616 // get_and_create returns a reference to result itself. An assignment
9617 // will then create a primitive value.
9618 json_pointer(element.first).get_and_create(result) = element.second;
9619 }
9620
9621 return result;
9622 }
9623
operator ==(json_pointer const & lhs,json_pointer const & rhs)9624 friend bool operator==(json_pointer const& lhs,
9625 json_pointer const& rhs) noexcept
9626 {
9627 return (lhs.reference_tokens == rhs.reference_tokens);
9628 }
9629
operator !=(json_pointer const & lhs,json_pointer const & rhs)9630 friend bool operator!=(json_pointer const& lhs,
9631 json_pointer const& rhs) noexcept
9632 {
9633 return not (lhs == rhs);
9634 }
9635
9636 /// the reference tokens
9637 std::vector<std::string> reference_tokens;
9638 };
9639 }
9640
9641 // #include <nlohmann/adl_serializer.hpp>
9642
9643
9644 #include <utility>
9645
9646 // #include <nlohmann/detail/conversions/from_json.hpp>
9647
9648 // #include <nlohmann/detail/conversions/to_json.hpp>
9649
9650
9651 namespace nlohmann
9652 {
9653 template<typename, typename>
9654 struct adl_serializer
9655 {
9656 /*!
9657 @brief convert a JSON value to any value type
9658
9659 This function is usually called by the `get()` function of the
9660 @ref basic_json class (either explicit or via conversion operators).
9661
9662 @param[in] j JSON value to read from
9663 @param[in,out] val value to write to
9664 */
9665 template<typename BasicJsonType, typename ValueType>
from_jsonnlohmann::adl_serializer9666 static void from_json(BasicJsonType&& j, ValueType& val) noexcept(
9667 noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
9668 {
9669 ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
9670 }
9671
9672 /*!
9673 @brief convert any value type to a JSON value
9674
9675 This function is usually called by the constructors of the @ref basic_json
9676 class.
9677
9678 @param[in,out] j JSON value to write to
9679 @param[in] val value to read from
9680 */
9681 template<typename BasicJsonType, typename ValueType>
to_jsonnlohmann::adl_serializer9682 static void to_json(BasicJsonType& j, ValueType&& val) noexcept(
9683 noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
9684 {
9685 ::nlohmann::to_json(j, std::forward<ValueType>(val));
9686 }
9687 };
9688 }
9689
9690
9691 /*!
9692 @brief namespace for Niels Lohmann
9693 @see https://github.com/nlohmann
9694 @since version 1.0.0
9695 */
9696 namespace nlohmann
9697 {
9698
9699 /*!
9700 @brief a class to store JSON values
9701
9702 @tparam ObjectType type for JSON objects (`std::map` by default; will be used
9703 in @ref object_t)
9704 @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
9705 in @ref array_t)
9706 @tparam StringType type for JSON strings and object keys (`std::string` by
9707 default; will be used in @ref string_t)
9708 @tparam BooleanType type for JSON booleans (`bool` by default; will be used
9709 in @ref boolean_t)
9710 @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
9711 default; will be used in @ref number_integer_t)
9712 @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
9713 `uint64_t` by default; will be used in @ref number_unsigned_t)
9714 @tparam NumberFloatType type for JSON floating-point numbers (`double` by
9715 default; will be used in @ref number_float_t)
9716 @tparam AllocatorType type of the allocator to use (`std::allocator` by
9717 default)
9718 @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
9719 and `from_json()` (@ref adl_serializer by default)
9720
9721 @requirement The class satisfies the following concept requirements:
9722 - Basic
9723 - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
9724 JSON values can be default constructed. The result will be a JSON null
9725 value.
9726 - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
9727 A JSON value can be constructed from an rvalue argument.
9728 - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
9729 A JSON value can be copy-constructed from an lvalue expression.
9730 - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
9731 A JSON value van be assigned from an rvalue argument.
9732 - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
9733 A JSON value can be copy-assigned from an lvalue expression.
9734 - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
9735 JSON values can be destructed.
9736 - Layout
9737 - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
9738 JSON values have
9739 [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
9740 All non-static data members are private and standard layout types, the
9741 class has no virtual functions or (virtual) base classes.
9742 - Library-wide
9743 - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
9744 JSON values can be compared with `==`, see @ref
9745 operator==(const_reference,const_reference).
9746 - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
9747 JSON values can be compared with `<`, see @ref
9748 operator<(const_reference,const_reference).
9749 - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
9750 Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
9751 other compatible types, using unqualified function call @ref swap().
9752 - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
9753 JSON values can be compared against `std::nullptr_t` objects which are used
9754 to model the `null` value.
9755 - Container
9756 - [Container](http://en.cppreference.com/w/cpp/concept/Container):
9757 JSON values can be used like STL containers and provide iterator access.
9758 - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
9759 JSON values can be used like STL containers and provide reverse iterator
9760 access.
9761
9762 @invariant The member variables @a m_value and @a m_type have the following
9763 relationship:
9764 - If `m_type == value_t::object`, then `m_value.object != nullptr`.
9765 - If `m_type == value_t::array`, then `m_value.array != nullptr`.
9766 - If `m_type == value_t::string`, then `m_value.string != nullptr`.
9767 The invariants are checked by member function assert_invariant().
9768
9769 @internal
9770 @note ObjectType trick from http://stackoverflow.com/a/9860911
9771 @endinternal
9772
9773 @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
9774 Format](http://rfc7159.net/rfc7159)
9775
9776 @since version 1.0.0
9777
9778 @nosubgrouping
9779 */
9780 NLOHMANN_BASIC_JSON_TPL_DECLARATION
9781 class basic_json
9782 {
9783 private:
9784 template<detail::value_t> friend struct detail::external_constructor;
9785 friend ::nlohmann::json_pointer<basic_json>;
9786 friend ::nlohmann::detail::parser<basic_json>;
9787 friend ::nlohmann::detail::serializer<basic_json>;
9788 template<typename BasicJsonType>
9789 friend class ::nlohmann::detail::iter_impl;
9790 template<typename BasicJsonType, typename CharType>
9791 friend class ::nlohmann::detail::binary_writer;
9792 template<typename BasicJsonType>
9793 friend class ::nlohmann::detail::binary_reader;
9794
9795 /// workaround type for MSVC
9796 using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
9797
9798 // convenience aliases for types residing in namespace detail;
9799 using lexer = ::nlohmann::detail::lexer<basic_json>;
9800 using parser = ::nlohmann::detail::parser<basic_json>;
9801
9802 using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
9803 template<typename BasicJsonType>
9804 using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
9805 template<typename BasicJsonType>
9806 using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
9807 template<typename Iterator>
9808 using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
9809 template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
9810
9811 template<typename CharType>
9812 using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
9813
9814 using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
9815 template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
9816
9817 using serializer = ::nlohmann::detail::serializer<basic_json>;
9818
9819 public:
9820 using value_t = detail::value_t;
9821 /// @copydoc nlohmann::json_pointer
9822 using json_pointer = ::nlohmann::json_pointer<basic_json>;
9823 template<typename T, typename SFINAE>
9824 using json_serializer = JSONSerializer<T, SFINAE>;
9825 /// helper type for initializer lists of basic_json values
9826 using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
9827
9828 ////////////////
9829 // exceptions //
9830 ////////////////
9831
9832 /// @name exceptions
9833 /// Classes to implement user-defined exceptions.
9834 /// @{
9835
9836 /// @copydoc detail::exception
9837 using exception = detail::exception;
9838 /// @copydoc detail::parse_error
9839 using parse_error = detail::parse_error;
9840 /// @copydoc detail::invalid_iterator
9841 using invalid_iterator = detail::invalid_iterator;
9842 /// @copydoc detail::type_error
9843 using type_error = detail::type_error;
9844 /// @copydoc detail::out_of_range
9845 using out_of_range = detail::out_of_range;
9846 /// @copydoc detail::other_error
9847 using other_error = detail::other_error;
9848
9849 /// @}
9850
9851
9852 /////////////////////
9853 // container types //
9854 /////////////////////
9855
9856 /// @name container types
9857 /// The canonic container types to use @ref basic_json like any other STL
9858 /// container.
9859 /// @{
9860
9861 /// the type of elements in a basic_json container
9862 using value_type = basic_json;
9863
9864 /// the type of an element reference
9865 using reference = value_type&;
9866 /// the type of an element const reference
9867 using const_reference = const value_type&;
9868
9869 /// a type to represent differences between iterators
9870 using difference_type = std::ptrdiff_t;
9871 /// a type to represent container sizes
9872 using size_type = std::size_t;
9873
9874 /// the allocator type
9875 using allocator_type = AllocatorType<basic_json>;
9876
9877 /// the type of an element pointer
9878 using pointer = typename std::allocator_traits<allocator_type>::pointer;
9879 /// the type of an element const pointer
9880 using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
9881
9882 /// an iterator for a basic_json container
9883 using iterator = iter_impl<basic_json>;
9884 /// a const iterator for a basic_json container
9885 using const_iterator = iter_impl<const basic_json>;
9886 /// a reverse iterator for a basic_json container
9887 using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
9888 /// a const reverse iterator for a basic_json container
9889 using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
9890
9891 /// @}
9892
9893
9894 /*!
9895 @brief returns the allocator associated with the container
9896 */
get_allocator()9897 static allocator_type get_allocator()
9898 {
9899 return allocator_type();
9900 }
9901
9902 /*!
9903 @brief returns version information on the library
9904
9905 This function returns a JSON object with information about the library,
9906 including the version number and information on the platform and compiler.
9907
9908 @return JSON object holding version information
9909 key | description
9910 ----------- | ---------------
9911 `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version).
9912 `copyright` | The copyright line for the library as string.
9913 `name` | The name of the library as string.
9914 `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
9915 `url` | The URL of the project as string.
9916 `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string).
9917
9918 @liveexample{The following code shows an example output of the `meta()`
9919 function.,meta}
9920
9921 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
9922 changes to any JSON value.
9923
9924 @complexity Constant.
9925
9926 @since 2.1.0
9927 */
meta()9928 static basic_json meta()
9929 {
9930 basic_json result;
9931
9932 result["copyright"] = "(C) 2013-2017 Niels Lohmann";
9933 result["name"] = "JSON for Modern C++";
9934 result["url"] = "https://github.com/nlohmann/json";
9935 result["version"]["string"] =
9936 std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
9937 std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
9938 std::to_string(NLOHMANN_JSON_VERSION_PATCH);
9939 result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
9940 result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
9941 result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
9942
9943 #ifdef _WIN32
9944 result["platform"] = "win32";
9945 #elif defined __linux__
9946 result["platform"] = "linux";
9947 #elif defined __APPLE__
9948 result["platform"] = "apple";
9949 #elif defined __unix__
9950 result["platform"] = "unix";
9951 #else
9952 result["platform"] = "unknown";
9953 #endif
9954
9955 #if defined(__ICC) || defined(__INTEL_COMPILER)
9956 result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
9957 #elif defined(__clang__)
9958 result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
9959 #elif defined(__GNUC__) || defined(__GNUG__)
9960 result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
9961 #elif defined(__HP_cc) || defined(__HP_aCC)
9962 result["compiler"] = "hp"
9963 #elif defined(__IBMCPP__)
9964 result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
9965 #elif defined(_MSC_VER)
9966 result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
9967 #elif defined(__PGI)
9968 result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
9969 #elif defined(__SUNPRO_CC)
9970 result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
9971 #else
9972 result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
9973 #endif
9974
9975 #ifdef __cplusplus
9976 result["compiler"]["c++"] = std::to_string(__cplusplus);
9977 #else
9978 result["compiler"]["c++"] = "unknown";
9979 #endif
9980 return result;
9981 }
9982
9983
9984 ///////////////////////////
9985 // JSON value data types //
9986 ///////////////////////////
9987
9988 /// @name JSON value data types
9989 /// The data types to store a JSON value. These types are derived from
9990 /// the template arguments passed to class @ref basic_json.
9991 /// @{
9992
9993 #if defined(JSON_HAS_CPP_14)
9994 // Use transparent comparator if possible, combined with perfect forwarding
9995 // on find() and count() calls prevents unnecessary string construction.
9996 using object_comparator_t = std::less<>;
9997 #else
9998 using object_comparator_t = std::less<StringType>;
9999 #endif
10000
10001 /*!
10002 @brief a type for an object
10003
10004 [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
10005 > An object is an unordered collection of zero or more name/value pairs,
10006 > where a name is a string and a value is a string, number, boolean, null,
10007 > object, or array.
10008
10009 To store objects in C++, a type is defined by the template parameters
10010 described below.
10011
10012 @tparam ObjectType the container to store objects (e.g., `std::map` or
10013 `std::unordered_map`)
10014 @tparam StringType the type of the keys or names (e.g., `std::string`).
10015 The comparison function `std::less<StringType>` is used to order elements
10016 inside the container.
10017 @tparam AllocatorType the allocator to use for objects (e.g.,
10018 `std::allocator`)
10019
10020 #### Default type
10021
10022 With the default values for @a ObjectType (`std::map`), @a StringType
10023 (`std::string`), and @a AllocatorType (`std::allocator`), the default
10024 value for @a object_t is:
10025
10026 @code {.cpp}
10027 std::map<
10028 std::string, // key_type
10029 basic_json, // value_type
10030 std::less<std::string>, // key_compare
10031 std::allocator<std::pair<const std::string, basic_json>> // allocator_type
10032 >
10033 @endcode
10034
10035 #### Behavior
10036
10037 The choice of @a object_t influences the behavior of the JSON class. With
10038 the default type, objects have the following behavior:
10039
10040 - When all names are unique, objects will be interoperable in the sense
10041 that all software implementations receiving that object will agree on
10042 the name-value mappings.
10043 - When the names within an object are not unique, it is unspecified which
10044 one of the values for a given key will be chosen. For instance,
10045 `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
10046 `{"key": 2}`.
10047 - Internally, name/value pairs are stored in lexicographical order of the
10048 names. Objects will also be serialized (see @ref dump) in this order.
10049 For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
10050 and serialized as `{"a": 2, "b": 1}`.
10051 - When comparing objects, the order of the name/value pairs is irrelevant.
10052 This makes objects interoperable in the sense that they will not be
10053 affected by these differences. For instance, `{"b": 1, "a": 2}` and
10054 `{"a": 2, "b": 1}` will be treated as equal.
10055
10056 #### Limits
10057
10058 [RFC 7159](http://rfc7159.net/rfc7159) specifies:
10059 > An implementation may set limits on the maximum depth of nesting.
10060
10061 In this class, the object's limit of nesting is not explicitly constrained.
10062 However, a maximum depth of nesting may be introduced by the compiler or
10063 runtime environment. A theoretical limit can be queried by calling the
10064 @ref max_size function of a JSON object.
10065
10066 #### Storage
10067
10068 Objects are stored as pointers in a @ref basic_json type. That is, for any
10069 access to object values, a pointer of type `object_t*` must be
10070 dereferenced.
10071
10072 @sa @ref array_t -- type for an array value
10073
10074 @since version 1.0.0
10075
10076 @note The order name/value pairs are added to the object is *not*
10077 preserved by the library. Therefore, iterating an object may return
10078 name/value pairs in a different order than they were originally stored. In
10079 fact, keys will be traversed in alphabetical order as `std::map` with
10080 `std::less` is used by default. Please note this behavior conforms to [RFC
10081 7159](http://rfc7159.net/rfc7159), because any order implements the
10082 specified "unordered" nature of JSON objects.
10083 */
10084 using object_t = ObjectType<StringType,
10085 basic_json,
10086 object_comparator_t,
10087 AllocatorType<std::pair<const StringType,
10088 basic_json>>>;
10089
10090 /*!
10091 @brief a type for an array
10092
10093 [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
10094 > An array is an ordered sequence of zero or more values.
10095
10096 To store objects in C++, a type is defined by the template parameters
10097 explained below.
10098
10099 @tparam ArrayType container type to store arrays (e.g., `std::vector` or
10100 `std::list`)
10101 @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
10102
10103 #### Default type
10104
10105 With the default values for @a ArrayType (`std::vector`) and @a
10106 AllocatorType (`std::allocator`), the default value for @a array_t is:
10107
10108 @code {.cpp}
10109 std::vector<
10110 basic_json, // value_type
10111 std::allocator<basic_json> // allocator_type
10112 >
10113 @endcode
10114
10115 #### Limits
10116
10117 [RFC 7159](http://rfc7159.net/rfc7159) specifies:
10118 > An implementation may set limits on the maximum depth of nesting.
10119
10120 In this class, the array's limit of nesting is not explicitly constrained.
10121 However, a maximum depth of nesting may be introduced by the compiler or
10122 runtime environment. A theoretical limit can be queried by calling the
10123 @ref max_size function of a JSON array.
10124
10125 #### Storage
10126
10127 Arrays are stored as pointers in a @ref basic_json type. That is, for any
10128 access to array values, a pointer of type `array_t*` must be dereferenced.
10129
10130 @sa @ref object_t -- type for an object value
10131
10132 @since version 1.0.0
10133 */
10134 using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
10135
10136 /*!
10137 @brief a type for a string
10138
10139 [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
10140 > A string is a sequence of zero or more Unicode characters.
10141
10142 To store objects in C++, a type is defined by the template parameter
10143 described below. Unicode values are split by the JSON class into
10144 byte-sized characters during deserialization.
10145
10146 @tparam StringType the container to store strings (e.g., `std::string`).
10147 Note this container is used for keys/names in objects, see @ref object_t.
10148
10149 #### Default type
10150
10151 With the default values for @a StringType (`std::string`), the default
10152 value for @a string_t is:
10153
10154 @code {.cpp}
10155 std::string
10156 @endcode
10157
10158 #### Encoding
10159
10160 Strings are stored in UTF-8 encoding. Therefore, functions like
10161 `std::string::size()` or `std::string::length()` return the number of
10162 bytes in the string rather than the number of characters or glyphs.
10163
10164 #### String comparison
10165
10166 [RFC 7159](http://rfc7159.net/rfc7159) states:
10167 > Software implementations are typically required to test names of object
10168 > members for equality. Implementations that transform the textual
10169 > representation into sequences of Unicode code units and then perform the
10170 > comparison numerically, code unit by code unit, are interoperable in the
10171 > sense that implementations will agree in all cases on equality or
10172 > inequality of two strings. For example, implementations that compare
10173 > strings with escaped characters unconverted may incorrectly find that
10174 > `"a\\b"` and `"a\u005Cb"` are not equal.
10175
10176 This implementation is interoperable as it does compare strings code unit
10177 by code unit.
10178
10179 #### Storage
10180
10181 String values are stored as pointers in a @ref basic_json type. That is,
10182 for any access to string values, a pointer of type `string_t*` must be
10183 dereferenced.
10184
10185 @since version 1.0.0
10186 */
10187 using string_t = StringType;
10188
10189 /*!
10190 @brief a type for a boolean
10191
10192 [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
10193 type which differentiates the two literals `true` and `false`.
10194
10195 To store objects in C++, a type is defined by the template parameter @a
10196 BooleanType which chooses the type to use.
10197
10198 #### Default type
10199
10200 With the default values for @a BooleanType (`bool`), the default value for
10201 @a boolean_t is:
10202
10203 @code {.cpp}
10204 bool
10205 @endcode
10206
10207 #### Storage
10208
10209 Boolean values are stored directly inside a @ref basic_json type.
10210
10211 @since version 1.0.0
10212 */
10213 using boolean_t = BooleanType;
10214
10215 /*!
10216 @brief a type for a number (integer)
10217
10218 [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
10219 > The representation of numbers is similar to that used in most
10220 > programming languages. A number is represented in base 10 using decimal
10221 > digits. It contains an integer component that may be prefixed with an
10222 > optional minus sign, which may be followed by a fraction part and/or an
10223 > exponent part. Leading zeros are not allowed. (...) Numeric values that
10224 > cannot be represented in the grammar below (such as Infinity and NaN)
10225 > are not permitted.
10226
10227 This description includes both integer and floating-point numbers.
10228 However, C++ allows more precise storage if it is known whether the number
10229 is a signed integer, an unsigned integer or a floating-point number.
10230 Therefore, three different types, @ref number_integer_t, @ref
10231 number_unsigned_t and @ref number_float_t are used.
10232
10233 To store integer numbers in C++, a type is defined by the template
10234 parameter @a NumberIntegerType which chooses the type to use.
10235
10236 #### Default type
10237
10238 With the default values for @a NumberIntegerType (`int64_t`), the default
10239 value for @a number_integer_t is:
10240
10241 @code {.cpp}
10242 int64_t
10243 @endcode
10244
10245 #### Default behavior
10246
10247 - The restrictions about leading zeros is not enforced in C++. Instead,
10248 leading zeros in integer literals lead to an interpretation as octal
10249 number. Internally, the value will be stored as decimal number. For
10250 instance, the C++ integer literal `010` will be serialized to `8`.
10251 During deserialization, leading zeros yield an error.
10252 - Not-a-number (NaN) values will be serialized to `null`.
10253
10254 #### Limits
10255
10256 [RFC 7159](http://rfc7159.net/rfc7159) specifies:
10257 > An implementation may set limits on the range and precision of numbers.
10258
10259 When the default type is used, the maximal integer number that can be
10260 stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
10261 that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
10262 that are out of range will yield over/underflow when used in a
10263 constructor. During deserialization, too large or small integer numbers
10264 will be automatically be stored as @ref number_unsigned_t or @ref
10265 number_float_t.
10266
10267 [RFC 7159](http://rfc7159.net/rfc7159) further states:
10268 > Note that when such software is used, numbers that are integers and are
10269 > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
10270 > that implementations will agree exactly on their numeric values.
10271
10272 As this range is a subrange of the exactly supported range [INT64_MIN,
10273 INT64_MAX], this class's integer type is interoperable.
10274
10275 #### Storage
10276
10277 Integer number values are stored directly inside a @ref basic_json type.
10278
10279 @sa @ref number_float_t -- type for number values (floating-point)
10280
10281 @sa @ref number_unsigned_t -- type for number values (unsigned integer)
10282
10283 @since version 1.0.0
10284 */
10285 using number_integer_t = NumberIntegerType;
10286
10287 /*!
10288 @brief a type for a number (unsigned)
10289
10290 [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
10291 > The representation of numbers is similar to that used in most
10292 > programming languages. A number is represented in base 10 using decimal
10293 > digits. It contains an integer component that may be prefixed with an
10294 > optional minus sign, which may be followed by a fraction part and/or an
10295 > exponent part. Leading zeros are not allowed. (...) Numeric values that
10296 > cannot be represented in the grammar below (such as Infinity and NaN)
10297 > are not permitted.
10298
10299 This description includes both integer and floating-point numbers.
10300 However, C++ allows more precise storage if it is known whether the number
10301 is a signed integer, an unsigned integer or a floating-point number.
10302 Therefore, three different types, @ref number_integer_t, @ref
10303 number_unsigned_t and @ref number_float_t are used.
10304
10305 To store unsigned integer numbers in C++, a type is defined by the
10306 template parameter @a NumberUnsignedType which chooses the type to use.
10307
10308 #### Default type
10309
10310 With the default values for @a NumberUnsignedType (`uint64_t`), the
10311 default value for @a number_unsigned_t is:
10312
10313 @code {.cpp}
10314 uint64_t
10315 @endcode
10316
10317 #### Default behavior
10318
10319 - The restrictions about leading zeros is not enforced in C++. Instead,
10320 leading zeros in integer literals lead to an interpretation as octal
10321 number. Internally, the value will be stored as decimal number. For
10322 instance, the C++ integer literal `010` will be serialized to `8`.
10323 During deserialization, leading zeros yield an error.
10324 - Not-a-number (NaN) values will be serialized to `null`.
10325
10326 #### Limits
10327
10328 [RFC 7159](http://rfc7159.net/rfc7159) specifies:
10329 > An implementation may set limits on the range and precision of numbers.
10330
10331 When the default type is used, the maximal integer number that can be
10332 stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
10333 number that can be stored is `0`. Integer numbers that are out of range
10334 will yield over/underflow when used in a constructor. During
10335 deserialization, too large or small integer numbers will be automatically
10336 be stored as @ref number_integer_t or @ref number_float_t.
10337
10338 [RFC 7159](http://rfc7159.net/rfc7159) further states:
10339 > Note that when such software is used, numbers that are integers and are
10340 > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
10341 > that implementations will agree exactly on their numeric values.
10342
10343 As this range is a subrange (when considered in conjunction with the
10344 number_integer_t type) of the exactly supported range [0, UINT64_MAX],
10345 this class's integer type is interoperable.
10346
10347 #### Storage
10348
10349 Integer number values are stored directly inside a @ref basic_json type.
10350
10351 @sa @ref number_float_t -- type for number values (floating-point)
10352 @sa @ref number_integer_t -- type for number values (integer)
10353
10354 @since version 2.0.0
10355 */
10356 using number_unsigned_t = NumberUnsignedType;
10357
10358 /*!
10359 @brief a type for a number (floating-point)
10360
10361 [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
10362 > The representation of numbers is similar to that used in most
10363 > programming languages. A number is represented in base 10 using decimal
10364 > digits. It contains an integer component that may be prefixed with an
10365 > optional minus sign, which may be followed by a fraction part and/or an
10366 > exponent part. Leading zeros are not allowed. (...) Numeric values that
10367 > cannot be represented in the grammar below (such as Infinity and NaN)
10368 > are not permitted.
10369
10370 This description includes both integer and floating-point numbers.
10371 However, C++ allows more precise storage if it is known whether the number
10372 is a signed integer, an unsigned integer or a floating-point number.
10373 Therefore, three different types, @ref number_integer_t, @ref
10374 number_unsigned_t and @ref number_float_t are used.
10375
10376 To store floating-point numbers in C++, a type is defined by the template
10377 parameter @a NumberFloatType which chooses the type to use.
10378
10379 #### Default type
10380
10381 With the default values for @a NumberFloatType (`double`), the default
10382 value for @a number_float_t is:
10383
10384 @code {.cpp}
10385 double
10386 @endcode
10387
10388 #### Default behavior
10389
10390 - The restrictions about leading zeros is not enforced in C++. Instead,
10391 leading zeros in floating-point literals will be ignored. Internally,
10392 the value will be stored as decimal number. For instance, the C++
10393 floating-point literal `01.2` will be serialized to `1.2`. During
10394 deserialization, leading zeros yield an error.
10395 - Not-a-number (NaN) values will be serialized to `null`.
10396
10397 #### Limits
10398
10399 [RFC 7159](http://rfc7159.net/rfc7159) states:
10400 > This specification allows implementations to set limits on the range and
10401 > precision of numbers accepted. Since software that implements IEEE
10402 > 754-2008 binary64 (double precision) numbers is generally available and
10403 > widely used, good interoperability can be achieved by implementations
10404 > that expect no more precision or range than these provide, in the sense
10405 > that implementations will approximate JSON numbers within the expected
10406 > precision.
10407
10408 This implementation does exactly follow this approach, as it uses double
10409 precision floating-point numbers. Note values smaller than
10410 `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
10411 will be stored as NaN internally and be serialized to `null`.
10412
10413 #### Storage
10414
10415 Floating-point number values are stored directly inside a @ref basic_json
10416 type.
10417
10418 @sa @ref number_integer_t -- type for number values (integer)
10419
10420 @sa @ref number_unsigned_t -- type for number values (unsigned integer)
10421
10422 @since version 1.0.0
10423 */
10424 using number_float_t = NumberFloatType;
10425
10426 /// @}
10427
10428 private:
10429
10430 /// helper for exception-safe object creation
10431 template<typename T, typename... Args>
create(Args &&...args)10432 static T* create(Args&& ... args)
10433 {
10434 AllocatorType<T> alloc;
10435 using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
10436
10437 auto deleter = [&](T * object)
10438 {
10439 AllocatorTraits::deallocate(alloc, object, 1);
10440 };
10441 std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
10442 AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
10443 assert(object != nullptr);
10444 return object.release();
10445 }
10446
10447 ////////////////////////
10448 // JSON value storage //
10449 ////////////////////////
10450
10451 /*!
10452 @brief a JSON value
10453
10454 The actual storage for a JSON value of the @ref basic_json class. This
10455 union combines the different storage types for the JSON value types
10456 defined in @ref value_t.
10457
10458 JSON type | value_t type | used type
10459 --------- | --------------- | ------------------------
10460 object | object | pointer to @ref object_t
10461 array | array | pointer to @ref array_t
10462 string | string | pointer to @ref string_t
10463 boolean | boolean | @ref boolean_t
10464 number | number_integer | @ref number_integer_t
10465 number | number_unsigned | @ref number_unsigned_t
10466 number | number_float | @ref number_float_t
10467 null | null | *no value is stored*
10468
10469 @note Variable-length types (objects, arrays, and strings) are stored as
10470 pointers. The size of the union should not exceed 64 bits if the default
10471 value types are used.
10472
10473 @since version 1.0.0
10474 */
10475 union json_value
10476 {
10477 /// object (stored with pointer to save storage)
10478 object_t* object;
10479 /// array (stored with pointer to save storage)
10480 array_t* array;
10481 /// string (stored with pointer to save storage)
10482 string_t* string;
10483 /// boolean
10484 boolean_t boolean;
10485 /// number (integer)
10486 number_integer_t number_integer;
10487 /// number (unsigned integer)
10488 number_unsigned_t number_unsigned;
10489 /// number (floating-point)
10490 number_float_t number_float;
10491
10492 /// default constructor (for null values)
10493 json_value() = default;
10494 /// constructor for booleans
json_value(boolean_t v)10495 json_value(boolean_t v) noexcept : boolean(v) {}
10496 /// constructor for numbers (integer)
json_value(number_integer_t v)10497 json_value(number_integer_t v) noexcept : number_integer(v) {}
10498 /// constructor for numbers (unsigned)
json_value(number_unsigned_t v)10499 json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
10500 /// constructor for numbers (floating-point)
json_value(number_float_t v)10501 json_value(number_float_t v) noexcept : number_float(v) {}
10502 /// constructor for empty values of a given type
json_value(value_t t)10503 json_value(value_t t)
10504 {
10505 switch (t)
10506 {
10507 case value_t::object:
10508 {
10509 object = create<object_t>();
10510 break;
10511 }
10512
10513 case value_t::array:
10514 {
10515 array = create<array_t>();
10516 break;
10517 }
10518
10519 case value_t::string:
10520 {
10521 string = create<string_t>("");
10522 break;
10523 }
10524
10525 case value_t::boolean:
10526 {
10527 boolean = boolean_t(false);
10528 break;
10529 }
10530
10531 case value_t::number_integer:
10532 {
10533 number_integer = number_integer_t(0);
10534 break;
10535 }
10536
10537 case value_t::number_unsigned:
10538 {
10539 number_unsigned = number_unsigned_t(0);
10540 break;
10541 }
10542
10543 case value_t::number_float:
10544 {
10545 number_float = number_float_t(0.0);
10546 break;
10547 }
10548
10549 case value_t::null:
10550 {
10551 object = nullptr; // silence warning, see #821
10552 break;
10553 }
10554
10555 default:
10556 {
10557 object = nullptr; // silence warning, see #821
10558 if (JSON_UNLIKELY(t == value_t::null))
10559 {
10560 JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.1.1")); // LCOV_EXCL_LINE
10561 }
10562 break;
10563 }
10564 }
10565 }
10566
10567 /// constructor for strings
json_value(const string_t & value)10568 json_value(const string_t& value)
10569 {
10570 string = create<string_t>(value);
10571 }
10572
10573 /// constructor for rvalue strings
json_value(string_t && value)10574 json_value(string_t&& value)
10575 {
10576 string = create<string_t>(std::move(value));
10577 }
10578
10579 /// constructor for objects
json_value(const object_t & value)10580 json_value(const object_t& value)
10581 {
10582 object = create<object_t>(value);
10583 }
10584
10585 /// constructor for rvalue objects
json_value(object_t && value)10586 json_value(object_t&& value)
10587 {
10588 object = create<object_t>(std::move(value));
10589 }
10590
10591 /// constructor for arrays
json_value(const array_t & value)10592 json_value(const array_t& value)
10593 {
10594 array = create<array_t>(value);
10595 }
10596
10597 /// constructor for rvalue arrays
json_value(array_t && value)10598 json_value(array_t&& value)
10599 {
10600 array = create<array_t>(std::move(value));
10601 }
10602
destroy(value_t t)10603 void destroy(value_t t) noexcept
10604 {
10605 switch (t)
10606 {
10607 case value_t::object:
10608 {
10609 AllocatorType<object_t> alloc;
10610 std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
10611 std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
10612 break;
10613 }
10614
10615 case value_t::array:
10616 {
10617 AllocatorType<array_t> alloc;
10618 std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
10619 std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
10620 break;
10621 }
10622
10623 case value_t::string:
10624 {
10625 AllocatorType<string_t> alloc;
10626 std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
10627 std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
10628 break;
10629 }
10630
10631 default:
10632 {
10633 break;
10634 }
10635 }
10636 }
10637 };
10638
10639 /*!
10640 @brief checks the class invariants
10641
10642 This function asserts the class invariants. It needs to be called at the
10643 end of every constructor to make sure that created objects respect the
10644 invariant. Furthermore, it has to be called each time the type of a JSON
10645 value is changed, because the invariant expresses a relationship between
10646 @a m_type and @a m_value.
10647 */
assert_invariant() const10648 void assert_invariant() const noexcept
10649 {
10650 assert(m_type != value_t::object or m_value.object != nullptr);
10651 assert(m_type != value_t::array or m_value.array != nullptr);
10652 assert(m_type != value_t::string or m_value.string != nullptr);
10653 }
10654
10655 public:
10656 //////////////////////////
10657 // JSON parser callback //
10658 //////////////////////////
10659
10660 /*!
10661 @brief parser event types
10662
10663 The parser callback distinguishes the following events:
10664 - `object_start`: the parser read `{` and started to process a JSON object
10665 - `key`: the parser read a key of a value in an object
10666 - `object_end`: the parser read `}` and finished processing a JSON object
10667 - `array_start`: the parser read `[` and started to process a JSON array
10668 - `array_end`: the parser read `]` and finished processing a JSON array
10669 - `value`: the parser finished reading a JSON value
10670
10671 @image html callback_events.png "Example when certain parse events are triggered"
10672
10673 @sa @ref parser_callback_t for more information and examples
10674 */
10675 using parse_event_t = typename parser::parse_event_t;
10676
10677 /*!
10678 @brief per-element parser callback type
10679
10680 With a parser callback function, the result of parsing a JSON text can be
10681 influenced. When passed to @ref parse, it is called on certain events
10682 (passed as @ref parse_event_t via parameter @a event) with a set recursion
10683 depth @a depth and context JSON value @a parsed. The return value of the
10684 callback function is a boolean indicating whether the element that emitted
10685 the callback shall be kept or not.
10686
10687 We distinguish six scenarios (determined by the event type) in which the
10688 callback function can be called. The following table describes the values
10689 of the parameters @a depth, @a event, and @a parsed.
10690
10691 parameter @a event | description | parameter @a depth | parameter @a parsed
10692 ------------------ | ----------- | ------------------ | -------------------
10693 parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded
10694 parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key
10695 parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object
10696 parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded
10697 parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array
10698 parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
10699
10700 @image html callback_events.png "Example when certain parse events are triggered"
10701
10702 Discarding a value (i.e., returning `false`) has different effects
10703 depending on the context in which function was called:
10704
10705 - Discarded values in structured types are skipped. That is, the parser
10706 will behave as if the discarded value was never read.
10707 - In case a value outside a structured type is skipped, it is replaced
10708 with `null`. This case happens if the top-level element is skipped.
10709
10710 @param[in] depth the depth of the recursion during parsing
10711
10712 @param[in] event an event of type parse_event_t indicating the context in
10713 the callback function has been called
10714
10715 @param[in,out] parsed the current intermediate parse result; note that
10716 writing to this value has no effect for parse_event_t::key events
10717
10718 @return Whether the JSON value which called the function during parsing
10719 should be kept (`true`) or not (`false`). In the latter case, it is either
10720 skipped completely or replaced by an empty discarded object.
10721
10722 @sa @ref parse for examples
10723
10724 @since version 1.0.0
10725 */
10726 using parser_callback_t = typename parser::parser_callback_t;
10727
10728
10729 //////////////////
10730 // constructors //
10731 //////////////////
10732
10733 /// @name constructors and destructors
10734 /// Constructors of class @ref basic_json, copy/move constructor, copy
10735 /// assignment, static functions creating objects, and the destructor.
10736 /// @{
10737
10738 /*!
10739 @brief create an empty value with a given type
10740
10741 Create an empty JSON value with a given type. The value will be default
10742 initialized with an empty value which depends on the type:
10743
10744 Value type | initial value
10745 ----------- | -------------
10746 null | `null`
10747 boolean | `false`
10748 string | `""`
10749 number | `0`
10750 object | `{}`
10751 array | `[]`
10752
10753 @param[in] v the type of the value to create
10754
10755 @complexity Constant.
10756
10757 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
10758 changes to any JSON value.
10759
10760 @liveexample{The following code shows the constructor for different @ref
10761 value_t values,basic_json__value_t}
10762
10763 @sa @ref clear() -- restores the postcondition of this constructor
10764
10765 @since version 1.0.0
10766 */
basic_json(const value_t v)10767 basic_json(const value_t v)
10768 : m_type(v), m_value(v)
10769 {
10770 assert_invariant();
10771 }
10772
10773 /*!
10774 @brief create a null object
10775
10776 Create a `null` JSON value. It either takes a null pointer as parameter
10777 (explicitly creating `null`) or no parameter (implicitly creating `null`).
10778 The passed null pointer itself is not read -- it is only used to choose
10779 the right constructor.
10780
10781 @complexity Constant.
10782
10783 @exceptionsafety No-throw guarantee: this constructor never throws
10784 exceptions.
10785
10786 @liveexample{The following code shows the constructor with and without a
10787 null pointer parameter.,basic_json__nullptr_t}
10788
10789 @since version 1.0.0
10790 */
basic_json(std::nullptr_t=nullptr)10791 basic_json(std::nullptr_t = nullptr) noexcept
10792 : basic_json(value_t::null)
10793 {
10794 assert_invariant();
10795 }
10796
10797 /*!
10798 @brief create a JSON value
10799
10800 This is a "catch all" constructor for all compatible JSON types; that is,
10801 types for which a `to_json()` method exists. The constructor forwards the
10802 parameter @a val to that method (to `json_serializer<U>::to_json` method
10803 with `U = uncvref_t<CompatibleType>`, to be exact).
10804
10805 Template type @a CompatibleType includes, but is not limited to, the
10806 following types:
10807 - **arrays**: @ref array_t and all kinds of compatible containers such as
10808 `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
10809 `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
10810 `std::multiset`, and `std::unordered_multiset` with a `value_type` from
10811 which a @ref basic_json value can be constructed.
10812 - **objects**: @ref object_t and all kinds of compatible associative
10813 containers such as `std::map`, `std::unordered_map`, `std::multimap`,
10814 and `std::unordered_multimap` with a `key_type` compatible to
10815 @ref string_t and a `value_type` from which a @ref basic_json value can
10816 be constructed.
10817 - **strings**: @ref string_t, string literals, and all compatible string
10818 containers can be used.
10819 - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
10820 @ref number_float_t, and all convertible number types such as `int`,
10821 `size_t`, `int64_t`, `float` or `double` can be used.
10822 - **boolean**: @ref boolean_t / `bool` can be used.
10823
10824 See the examples below.
10825
10826 @tparam CompatibleType a type such that:
10827 - @a CompatibleType is not derived from `std::istream`,
10828 - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
10829 constructors),
10830 - @a CompatibleType is not a @ref basic_json nested type (e.g.,
10831 @ref json_pointer, @ref iterator, etc ...)
10832 - @ref @ref json_serializer<U> has a
10833 `to_json(basic_json_t&, CompatibleType&&)` method
10834
10835 @tparam U = `uncvref_t<CompatibleType>`
10836
10837 @param[in] val the value to be forwarded to the respective constructor
10838
10839 @complexity Usually linear in the size of the passed @a val, also
10840 depending on the implementation of the called `to_json()`
10841 method.
10842
10843 @exceptionsafety Depends on the called constructor. For types directly
10844 supported by the library (i.e., all types for which no `to_json()` function
10845 was provided), strong guarantee holds: if an exception is thrown, there are
10846 no changes to any JSON value.
10847
10848 @liveexample{The following code shows the constructor with several
10849 compatible types.,basic_json__CompatibleType}
10850
10851 @since version 2.1.0
10852 */
10853 template <typename CompatibleType,
10854 typename U = detail::uncvref_t<CompatibleType>,
10855 detail::enable_if_t<
10856 detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
basic_json(CompatibleType && val)10857 basic_json(CompatibleType && val) noexcept(noexcept(
10858 JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
10859 std::forward<CompatibleType>(val))))
10860 {
10861 JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
10862 assert_invariant();
10863 }
10864
10865 /*!
10866 @brief create a container (array or object) from an initializer list
10867
10868 Creates a JSON value of type array or object from the passed initializer
10869 list @a init. In case @a type_deduction is `true` (default), the type of
10870 the JSON value to be created is deducted from the initializer list @a init
10871 according to the following rules:
10872
10873 1. If the list is empty, an empty JSON object value `{}` is created.
10874 2. If the list consists of pairs whose first element is a string, a JSON
10875 object value is created where the first elements of the pairs are
10876 treated as keys and the second elements are as values.
10877 3. In all other cases, an array is created.
10878
10879 The rules aim to create the best fit between a C++ initializer list and
10880 JSON values. The rationale is as follows:
10881
10882 1. The empty initializer list is written as `{}` which is exactly an empty
10883 JSON object.
10884 2. C++ has no way of describing mapped types other than to list a list of
10885 pairs. As JSON requires that keys must be of type string, rule 2 is the
10886 weakest constraint one can pose on initializer lists to interpret them
10887 as an object.
10888 3. In all other cases, the initializer list could not be interpreted as
10889 JSON object type, so interpreting it as JSON array type is safe.
10890
10891 With the rules described above, the following JSON values cannot be
10892 expressed by an initializer list:
10893
10894 - the empty array (`[]`): use @ref array(initializer_list_t)
10895 with an empty initializer list in this case
10896 - arrays whose elements satisfy rule 2: use @ref
10897 array(initializer_list_t) with the same initializer list
10898 in this case
10899
10900 @note When used without parentheses around an empty initializer list, @ref
10901 basic_json() is called instead of this function, yielding the JSON null
10902 value.
10903
10904 @param[in] init initializer list with JSON values
10905
10906 @param[in] type_deduction internal parameter; when set to `true`, the type
10907 of the JSON value is deducted from the initializer list @a init; when set
10908 to `false`, the type provided via @a manual_type is forced. This mode is
10909 used by the functions @ref array(initializer_list_t) and
10910 @ref object(initializer_list_t).
10911
10912 @param[in] manual_type internal parameter; when @a type_deduction is set
10913 to `false`, the created JSON value will use the provided type (only @ref
10914 value_t::array and @ref value_t::object are valid); when @a type_deduction
10915 is set to `true`, this parameter has no effect
10916
10917 @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
10918 `value_t::object`, but @a init contains an element which is not a pair
10919 whose first element is a string. In this case, the constructor could not
10920 create an object. If @a type_deduction would have be `true`, an array
10921 would have been created. See @ref object(initializer_list_t)
10922 for an example.
10923
10924 @complexity Linear in the size of the initializer list @a init.
10925
10926 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
10927 changes to any JSON value.
10928
10929 @liveexample{The example below shows how JSON values are created from
10930 initializer lists.,basic_json__list_init_t}
10931
10932 @sa @ref array(initializer_list_t) -- create a JSON array
10933 value from an initializer list
10934 @sa @ref object(initializer_list_t) -- create a JSON object
10935 value from an initializer list
10936
10937 @since version 1.0.0
10938 */
basic_json(initializer_list_t init,bool type_deduction=true,value_t manual_type=value_t::array)10939 basic_json(initializer_list_t init,
10940 bool type_deduction = true,
10941 value_t manual_type = value_t::array)
10942 {
10943 // check if each element is an array with two elements whose first
10944 // element is a string
10945 bool is_an_object = std::all_of(init.begin(), init.end(),
10946 [](const detail::json_ref<basic_json>& element_ref)
10947 {
10948 return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string());
10949 });
10950
10951 // adjust type if type deduction is not wanted
10952 if (not type_deduction)
10953 {
10954 // if array is wanted, do not create an object though possible
10955 if (manual_type == value_t::array)
10956 {
10957 is_an_object = false;
10958 }
10959
10960 // if object is wanted but impossible, throw an exception
10961 if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object))
10962 {
10963 JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
10964 }
10965 }
10966
10967 if (is_an_object)
10968 {
10969 // the initializer list is a list of pairs -> create object
10970 m_type = value_t::object;
10971 m_value = value_t::object;
10972
10973 std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
10974 {
10975 auto element = element_ref.moved_or_copied();
10976 m_value.object->emplace(
10977 std::move(*((*element.m_value.array)[0].m_value.string)),
10978 std::move((*element.m_value.array)[1]));
10979 });
10980 }
10981 else
10982 {
10983 // the initializer list describes an array -> create array
10984 m_type = value_t::array;
10985 m_value.array = create<array_t>(init.begin(), init.end());
10986 }
10987
10988 assert_invariant();
10989 }
10990
10991 /*!
10992 @brief explicitly create an array from an initializer list
10993
10994 Creates a JSON array value from a given initializer list. That is, given a
10995 list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
10996 initializer list is empty, the empty array `[]` is created.
10997
10998 @note This function is only needed to express two edge cases that cannot
10999 be realized with the initializer list constructor (@ref
11000 basic_json(initializer_list_t, bool, value_t)). These cases
11001 are:
11002 1. creating an array whose elements are all pairs whose first element is a
11003 string -- in this case, the initializer list constructor would create an
11004 object, taking the first elements as keys
11005 2. creating an empty array -- passing the empty initializer list to the
11006 initializer list constructor yields an empty object
11007
11008 @param[in] init initializer list with JSON values to create an array from
11009 (optional)
11010
11011 @return JSON array value
11012
11013 @complexity Linear in the size of @a init.
11014
11015 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
11016 changes to any JSON value.
11017
11018 @liveexample{The following code shows an example for the `array`
11019 function.,array}
11020
11021 @sa @ref basic_json(initializer_list_t, bool, value_t) --
11022 create a JSON value from an initializer list
11023 @sa @ref object(initializer_list_t) -- create a JSON object
11024 value from an initializer list
11025
11026 @since version 1.0.0
11027 */
array(initializer_list_t init={})11028 static basic_json array(initializer_list_t init = {})
11029 {
11030 return basic_json(init, false, value_t::array);
11031 }
11032
11033 /*!
11034 @brief explicitly create an object from an initializer list
11035
11036 Creates a JSON object value from a given initializer list. The initializer
11037 lists elements must be pairs, and their first elements must be strings. If
11038 the initializer list is empty, the empty object `{}` is created.
11039
11040 @note This function is only added for symmetry reasons. In contrast to the
11041 related function @ref array(initializer_list_t), there are
11042 no cases which can only be expressed by this function. That is, any
11043 initializer list @a init can also be passed to the initializer list
11044 constructor @ref basic_json(initializer_list_t, bool, value_t).
11045
11046 @param[in] init initializer list to create an object from (optional)
11047
11048 @return JSON object value
11049
11050 @throw type_error.301 if @a init is not a list of pairs whose first
11051 elements are strings. In this case, no object can be created. When such a
11052 value is passed to @ref basic_json(initializer_list_t, bool, value_t),
11053 an array would have been created from the passed initializer list @a init.
11054 See example below.
11055
11056 @complexity Linear in the size of @a init.
11057
11058 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
11059 changes to any JSON value.
11060
11061 @liveexample{The following code shows an example for the `object`
11062 function.,object}
11063
11064 @sa @ref basic_json(initializer_list_t, bool, value_t) --
11065 create a JSON value from an initializer list
11066 @sa @ref array(initializer_list_t) -- create a JSON array
11067 value from an initializer list
11068
11069 @since version 1.0.0
11070 */
object(initializer_list_t init={})11071 static basic_json object(initializer_list_t init = {})
11072 {
11073 return basic_json(init, false, value_t::object);
11074 }
11075
11076 /*!
11077 @brief construct an array with count copies of given value
11078
11079 Constructs a JSON array value by creating @a cnt copies of a passed value.
11080 In case @a cnt is `0`, an empty array is created.
11081
11082 @param[in] cnt the number of JSON copies of @a val to create
11083 @param[in] val the JSON value to copy
11084
11085 @post `std::distance(begin(),end()) == cnt` holds.
11086
11087 @complexity Linear in @a cnt.
11088
11089 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
11090 changes to any JSON value.
11091
11092 @liveexample{The following code shows examples for the @ref
11093 basic_json(size_type\, const basic_json&)
11094 constructor.,basic_json__size_type_basic_json}
11095
11096 @since version 1.0.0
11097 */
basic_json(size_type cnt,const basic_json & val)11098 basic_json(size_type cnt, const basic_json& val)
11099 : m_type(value_t::array)
11100 {
11101 m_value.array = create<array_t>(cnt, val);
11102 assert_invariant();
11103 }
11104
11105 /*!
11106 @brief construct a JSON container given an iterator range
11107
11108 Constructs the JSON value with the contents of the range `[first, last)`.
11109 The semantics depends on the different types a JSON value can have:
11110 - In case of a null type, invalid_iterator.206 is thrown.
11111 - In case of other primitive types (number, boolean, or string), @a first
11112 must be `begin()` and @a last must be `end()`. In this case, the value is
11113 copied. Otherwise, invalid_iterator.204 is thrown.
11114 - In case of structured types (array, object), the constructor behaves as
11115 similar versions for `std::vector` or `std::map`; that is, a JSON array
11116 or object is constructed from the values in the range.
11117
11118 @tparam InputIT an input iterator type (@ref iterator or @ref
11119 const_iterator)
11120
11121 @param[in] first begin of the range to copy from (included)
11122 @param[in] last end of the range to copy from (excluded)
11123
11124 @pre Iterators @a first and @a last must be initialized. **This
11125 precondition is enforced with an assertion (see warning).** If
11126 assertions are switched off, a violation of this precondition yields
11127 undefined behavior.
11128
11129 @pre Range `[first, last)` is valid. Usually, this precondition cannot be
11130 checked efficiently. Only certain edge cases are detected; see the
11131 description of the exceptions below. A violation of this precondition
11132 yields undefined behavior.
11133
11134 @warning A precondition is enforced with a runtime assertion that will
11135 result in calling `std::abort` if this precondition is not met.
11136 Assertions can be disabled by defining `NDEBUG` at compile time.
11137 See http://en.cppreference.com/w/cpp/error/assert for more
11138 information.
11139
11140 @throw invalid_iterator.201 if iterators @a first and @a last are not
11141 compatible (i.e., do not belong to the same JSON value). In this case,
11142 the range `[first, last)` is undefined.
11143 @throw invalid_iterator.204 if iterators @a first and @a last belong to a
11144 primitive type (number, boolean, or string), but @a first does not point
11145 to the first element any more. In this case, the range `[first, last)` is
11146 undefined. See example code below.
11147 @throw invalid_iterator.206 if iterators @a first and @a last belong to a
11148 null value. In this case, the range `[first, last)` is undefined.
11149
11150 @complexity Linear in distance between @a first and @a last.
11151
11152 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
11153 changes to any JSON value.
11154
11155 @liveexample{The example below shows several ways to create JSON values by
11156 specifying a subrange with iterators.,basic_json__InputIt_InputIt}
11157
11158 @since version 1.0.0
11159 */
11160 template<class InputIT, typename std::enable_if<
11161 std::is_same<InputIT, typename basic_json_t::iterator>::value or
11162 std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
basic_json(InputIT first,InputIT last)11163 basic_json(InputIT first, InputIT last)
11164 {
11165 assert(first.m_object != nullptr);
11166 assert(last.m_object != nullptr);
11167
11168 // make sure iterator fits the current value
11169 if (JSON_UNLIKELY(first.m_object != last.m_object))
11170 {
11171 JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
11172 }
11173
11174 // copy type from first iterator
11175 m_type = first.m_object->m_type;
11176
11177 // check if iterator range is complete for primitive values
11178 switch (m_type)
11179 {
11180 case value_t::boolean:
11181 case value_t::number_float:
11182 case value_t::number_integer:
11183 case value_t::number_unsigned:
11184 case value_t::string:
11185 {
11186 if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
11187 or not last.m_it.primitive_iterator.is_end()))
11188 {
11189 JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
11190 }
11191 break;
11192 }
11193
11194 default:
11195 break;
11196 }
11197
11198 switch (m_type)
11199 {
11200 case value_t::number_integer:
11201 {
11202 m_value.number_integer = first.m_object->m_value.number_integer;
11203 break;
11204 }
11205
11206 case value_t::number_unsigned:
11207 {
11208 m_value.number_unsigned = first.m_object->m_value.number_unsigned;
11209 break;
11210 }
11211
11212 case value_t::number_float:
11213 {
11214 m_value.number_float = first.m_object->m_value.number_float;
11215 break;
11216 }
11217
11218 case value_t::boolean:
11219 {
11220 m_value.boolean = first.m_object->m_value.boolean;
11221 break;
11222 }
11223
11224 case value_t::string:
11225 {
11226 m_value = *first.m_object->m_value.string;
11227 break;
11228 }
11229
11230 case value_t::object:
11231 {
11232 m_value.object = create<object_t>(first.m_it.object_iterator,
11233 last.m_it.object_iterator);
11234 break;
11235 }
11236
11237 case value_t::array:
11238 {
11239 m_value.array = create<array_t>(first.m_it.array_iterator,
11240 last.m_it.array_iterator);
11241 break;
11242 }
11243
11244 default:
11245 JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
11246 std::string(first.m_object->type_name())));
11247 }
11248
11249 assert_invariant();
11250 }
11251
11252
11253 ///////////////////////////////////////
11254 // other constructors and destructor //
11255 ///////////////////////////////////////
11256
11257 /// @private
basic_json(const detail::json_ref<basic_json> & ref)11258 basic_json(const detail::json_ref<basic_json>& ref)
11259 : basic_json(ref.moved_or_copied())
11260 {}
11261
11262 /*!
11263 @brief copy constructor
11264
11265 Creates a copy of a given JSON value.
11266
11267 @param[in] other the JSON value to copy
11268
11269 @post `*this == other`
11270
11271 @complexity Linear in the size of @a other.
11272
11273 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
11274 changes to any JSON value.
11275
11276 @requirement This function helps `basic_json` satisfying the
11277 [Container](http://en.cppreference.com/w/cpp/concept/Container)
11278 requirements:
11279 - The complexity is linear.
11280 - As postcondition, it holds: `other == basic_json(other)`.
11281
11282 @liveexample{The following code shows an example for the copy
11283 constructor.,basic_json__basic_json}
11284
11285 @since version 1.0.0
11286 */
basic_json(const basic_json & other)11287 basic_json(const basic_json& other)
11288 : m_type(other.m_type)
11289 {
11290 // check of passed value is valid
11291 other.assert_invariant();
11292
11293 switch (m_type)
11294 {
11295 case value_t::object:
11296 {
11297 m_value = *other.m_value.object;
11298 break;
11299 }
11300
11301 case value_t::array:
11302 {
11303 m_value = *other.m_value.array;
11304 break;
11305 }
11306
11307 case value_t::string:
11308 {
11309 m_value = *other.m_value.string;
11310 break;
11311 }
11312
11313 case value_t::boolean:
11314 {
11315 m_value = other.m_value.boolean;
11316 break;
11317 }
11318
11319 case value_t::number_integer:
11320 {
11321 m_value = other.m_value.number_integer;
11322 break;
11323 }
11324
11325 case value_t::number_unsigned:
11326 {
11327 m_value = other.m_value.number_unsigned;
11328 break;
11329 }
11330
11331 case value_t::number_float:
11332 {
11333 m_value = other.m_value.number_float;
11334 break;
11335 }
11336
11337 default:
11338 break;
11339 }
11340
11341 assert_invariant();
11342 }
11343
11344 /*!
11345 @brief move constructor
11346
11347 Move constructor. Constructs a JSON value with the contents of the given
11348 value @a other using move semantics. It "steals" the resources from @a
11349 other and leaves it as JSON null value.
11350
11351 @param[in,out] other value to move to this object
11352
11353 @post `*this` has the same value as @a other before the call.
11354 @post @a other is a JSON null value.
11355
11356 @complexity Constant.
11357
11358 @exceptionsafety No-throw guarantee: this constructor never throws
11359 exceptions.
11360
11361 @requirement This function helps `basic_json` satisfying the
11362 [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible)
11363 requirements.
11364
11365 @liveexample{The code below shows the move constructor explicitly called
11366 via std::move.,basic_json__moveconstructor}
11367
11368 @since version 1.0.0
11369 */
basic_json(basic_json && other)11370 basic_json(basic_json&& other) noexcept
11371 : m_type(std::move(other.m_type)),
11372 m_value(std::move(other.m_value))
11373 {
11374 // check that passed value is valid
11375 other.assert_invariant();
11376
11377 // invalidate payload
11378 other.m_type = value_t::null;
11379 other.m_value = {};
11380
11381 assert_invariant();
11382 }
11383
11384 /*!
11385 @brief copy assignment
11386
11387 Copy assignment operator. Copies a JSON value via the "copy and swap"
11388 strategy: It is expressed in terms of the copy constructor, destructor,
11389 and the `swap()` member function.
11390
11391 @param[in] other value to copy from
11392
11393 @complexity Linear.
11394
11395 @requirement This function helps `basic_json` satisfying the
11396 [Container](http://en.cppreference.com/w/cpp/concept/Container)
11397 requirements:
11398 - The complexity is linear.
11399
11400 @liveexample{The code below shows and example for the copy assignment. It
11401 creates a copy of value `a` which is then swapped with `b`. Finally\, the
11402 copy of `a` (which is the null value after the swap) is
11403 destroyed.,basic_json__copyassignment}
11404
11405 @since version 1.0.0
11406 */
operator =(basic_json other)11407 reference& operator=(basic_json other) noexcept (
11408 std::is_nothrow_move_constructible<value_t>::value and
11409 std::is_nothrow_move_assignable<value_t>::value and
11410 std::is_nothrow_move_constructible<json_value>::value and
11411 std::is_nothrow_move_assignable<json_value>::value
11412 )
11413 {
11414 // check that passed value is valid
11415 other.assert_invariant();
11416
11417 using std::swap;
11418 swap(m_type, other.m_type);
11419 swap(m_value, other.m_value);
11420
11421 assert_invariant();
11422 return *this;
11423 }
11424
11425 /*!
11426 @brief destructor
11427
11428 Destroys the JSON value and frees all allocated memory.
11429
11430 @complexity Linear.
11431
11432 @requirement This function helps `basic_json` satisfying the
11433 [Container](http://en.cppreference.com/w/cpp/concept/Container)
11434 requirements:
11435 - The complexity is linear.
11436 - All stored elements are destroyed and all memory is freed.
11437
11438 @since version 1.0.0
11439 */
~basic_json()11440 ~basic_json() noexcept
11441 {
11442 assert_invariant();
11443 m_value.destroy(m_type);
11444 }
11445
11446 /// @}
11447
11448 public:
11449 ///////////////////////
11450 // object inspection //
11451 ///////////////////////
11452
11453 /// @name object inspection
11454 /// Functions to inspect the type of a JSON value.
11455 /// @{
11456
11457 /*!
11458 @brief serialization
11459
11460 Serialization function for JSON values. The function tries to mimic
11461 Python's `json.dumps()` function, and currently supports its @a indent
11462 and @a ensure_ascii parameters.
11463
11464 @param[in] indent If indent is nonnegative, then array elements and object
11465 members will be pretty-printed with that indent level. An indent level of
11466 `0` will only insert newlines. `-1` (the default) selects the most compact
11467 representation.
11468 @param[in] indent_char The character to use for indentation if @a indent is
11469 greater than `0`. The default is ` ` (space).
11470 @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
11471 in the output are escaped with `\uXXXX` sequences, and the result consists
11472 of ASCII characters only.
11473
11474 @return string containing the serialization of the JSON value
11475
11476 @throw type_error.316 if a string stored inside the JSON value is not
11477 UTF-8 encoded
11478
11479 @complexity Linear.
11480
11481 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
11482 changes in the JSON value.
11483
11484 @liveexample{The following example shows the effect of different @a indent\,
11485 @a indent_char\, and @a ensure_ascii parameters to the result of the
11486 serialization.,dump}
11487
11488 @see https://docs.python.org/2/library/json.html#json.dump
11489
11490 @since version 1.0.0; indentation character @a indent_char, option
11491 @a ensure_ascii and exceptions added in version 3.0.0
11492 */
dump(const int indent=-1,const char indent_char=' ',const bool ensure_ascii=false) const11493 string_t dump(const int indent = -1, const char indent_char = ' ',
11494 const bool ensure_ascii = false) const
11495 {
11496 string_t result;
11497 serializer s(detail::output_adapter<char>(result), indent_char);
11498
11499 if (indent >= 0)
11500 {
11501 s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
11502 }
11503 else
11504 {
11505 s.dump(*this, false, ensure_ascii, 0);
11506 }
11507
11508 return result;
11509 }
11510
11511 /*!
11512 @brief return the type of the JSON value (explicit)
11513
11514 Return the type of the JSON value as a value from the @ref value_t
11515 enumeration.
11516
11517 @return the type of the JSON value
11518 Value type | return value
11519 ------------------------- | -------------------------
11520 null | value_t::null
11521 boolean | value_t::boolean
11522 string | value_t::string
11523 number (integer) | value_t::number_integer
11524 number (unsigned integer) | value_t::number_unsigned
11525 number (floating-point) | value_t::number_float
11526 object | value_t::object
11527 array | value_t::array
11528 discarded | value_t::discarded
11529
11530 @complexity Constant.
11531
11532 @exceptionsafety No-throw guarantee: this member function never throws
11533 exceptions.
11534
11535 @liveexample{The following code exemplifies `type()` for all JSON
11536 types.,type}
11537
11538 @sa @ref operator value_t() -- return the type of the JSON value (implicit)
11539 @sa @ref type_name() -- return the type as string
11540
11541 @since version 1.0.0
11542 */
type() const11543 constexpr value_t type() const noexcept
11544 {
11545 return m_type;
11546 }
11547
11548 /*!
11549 @brief return whether type is primitive
11550
11551 This function returns true if and only if the JSON type is primitive
11552 (string, number, boolean, or null).
11553
11554 @return `true` if type is primitive (string, number, boolean, or null),
11555 `false` otherwise.
11556
11557 @complexity Constant.
11558
11559 @exceptionsafety No-throw guarantee: this member function never throws
11560 exceptions.
11561
11562 @liveexample{The following code exemplifies `is_primitive()` for all JSON
11563 types.,is_primitive}
11564
11565 @sa @ref is_structured() -- returns whether JSON value is structured
11566 @sa @ref is_null() -- returns whether JSON value is `null`
11567 @sa @ref is_string() -- returns whether JSON value is a string
11568 @sa @ref is_boolean() -- returns whether JSON value is a boolean
11569 @sa @ref is_number() -- returns whether JSON value is a number
11570
11571 @since version 1.0.0
11572 */
is_primitive() const11573 constexpr bool is_primitive() const noexcept
11574 {
11575 return is_null() or is_string() or is_boolean() or is_number();
11576 }
11577
11578 /*!
11579 @brief return whether type is structured
11580
11581 This function returns true if and only if the JSON type is structured
11582 (array or object).
11583
11584 @return `true` if type is structured (array or object), `false` otherwise.
11585
11586 @complexity Constant.
11587
11588 @exceptionsafety No-throw guarantee: this member function never throws
11589 exceptions.
11590
11591 @liveexample{The following code exemplifies `is_structured()` for all JSON
11592 types.,is_structured}
11593
11594 @sa @ref is_primitive() -- returns whether value is primitive
11595 @sa @ref is_array() -- returns whether value is an array
11596 @sa @ref is_object() -- returns whether value is an object
11597
11598 @since version 1.0.0
11599 */
is_structured() const11600 constexpr bool is_structured() const noexcept
11601 {
11602 return is_array() or is_object();
11603 }
11604
11605 /*!
11606 @brief return whether value is null
11607
11608 This function returns true if and only if the JSON value is null.
11609
11610 @return `true` if type is null, `false` otherwise.
11611
11612 @complexity Constant.
11613
11614 @exceptionsafety No-throw guarantee: this member function never throws
11615 exceptions.
11616
11617 @liveexample{The following code exemplifies `is_null()` for all JSON
11618 types.,is_null}
11619
11620 @since version 1.0.0
11621 */
is_null() const11622 constexpr bool is_null() const noexcept
11623 {
11624 return (m_type == value_t::null);
11625 }
11626
11627 /*!
11628 @brief return whether value is a boolean
11629
11630 This function returns true if and only if the JSON value is a boolean.
11631
11632 @return `true` if type is boolean, `false` otherwise.
11633
11634 @complexity Constant.
11635
11636 @exceptionsafety No-throw guarantee: this member function never throws
11637 exceptions.
11638
11639 @liveexample{The following code exemplifies `is_boolean()` for all JSON
11640 types.,is_boolean}
11641
11642 @since version 1.0.0
11643 */
is_boolean() const11644 constexpr bool is_boolean() const noexcept
11645 {
11646 return (m_type == value_t::boolean);
11647 }
11648
11649 /*!
11650 @brief return whether value is a number
11651
11652 This function returns true if and only if the JSON value is a number. This
11653 includes both integer (signed and unsigned) and floating-point values.
11654
11655 @return `true` if type is number (regardless whether integer, unsigned
11656 integer or floating-type), `false` otherwise.
11657
11658 @complexity Constant.
11659
11660 @exceptionsafety No-throw guarantee: this member function never throws
11661 exceptions.
11662
11663 @liveexample{The following code exemplifies `is_number()` for all JSON
11664 types.,is_number}
11665
11666 @sa @ref is_number_integer() -- check if value is an integer or unsigned
11667 integer number
11668 @sa @ref is_number_unsigned() -- check if value is an unsigned integer
11669 number
11670 @sa @ref is_number_float() -- check if value is a floating-point number
11671
11672 @since version 1.0.0
11673 */
is_number() const11674 constexpr bool is_number() const noexcept
11675 {
11676 return is_number_integer() or is_number_float();
11677 }
11678
11679 /*!
11680 @brief return whether value is an integer number
11681
11682 This function returns true if and only if the JSON value is a signed or
11683 unsigned integer number. This excludes floating-point values.
11684
11685 @return `true` if type is an integer or unsigned integer number, `false`
11686 otherwise.
11687
11688 @complexity Constant.
11689
11690 @exceptionsafety No-throw guarantee: this member function never throws
11691 exceptions.
11692
11693 @liveexample{The following code exemplifies `is_number_integer()` for all
11694 JSON types.,is_number_integer}
11695
11696 @sa @ref is_number() -- check if value is a number
11697 @sa @ref is_number_unsigned() -- check if value is an unsigned integer
11698 number
11699 @sa @ref is_number_float() -- check if value is a floating-point number
11700
11701 @since version 1.0.0
11702 */
is_number_integer() const11703 constexpr bool is_number_integer() const noexcept
11704 {
11705 return (m_type == value_t::number_integer or m_type == value_t::number_unsigned);
11706 }
11707
11708 /*!
11709 @brief return whether value is an unsigned integer number
11710
11711 This function returns true if and only if the JSON value is an unsigned
11712 integer number. This excludes floating-point and signed integer values.
11713
11714 @return `true` if type is an unsigned integer number, `false` otherwise.
11715
11716 @complexity Constant.
11717
11718 @exceptionsafety No-throw guarantee: this member function never throws
11719 exceptions.
11720
11721 @liveexample{The following code exemplifies `is_number_unsigned()` for all
11722 JSON types.,is_number_unsigned}
11723
11724 @sa @ref is_number() -- check if value is a number
11725 @sa @ref is_number_integer() -- check if value is an integer or unsigned
11726 integer number
11727 @sa @ref is_number_float() -- check if value is a floating-point number
11728
11729 @since version 2.0.0
11730 */
is_number_unsigned() const11731 constexpr bool is_number_unsigned() const noexcept
11732 {
11733 return (m_type == value_t::number_unsigned);
11734 }
11735
11736 /*!
11737 @brief return whether value is a floating-point number
11738
11739 This function returns true if and only if the JSON value is a
11740 floating-point number. This excludes signed and unsigned integer values.
11741
11742 @return `true` if type is a floating-point number, `false` otherwise.
11743
11744 @complexity Constant.
11745
11746 @exceptionsafety No-throw guarantee: this member function never throws
11747 exceptions.
11748
11749 @liveexample{The following code exemplifies `is_number_float()` for all
11750 JSON types.,is_number_float}
11751
11752 @sa @ref is_number() -- check if value is number
11753 @sa @ref is_number_integer() -- check if value is an integer number
11754 @sa @ref is_number_unsigned() -- check if value is an unsigned integer
11755 number
11756
11757 @since version 1.0.0
11758 */
is_number_float() const11759 constexpr bool is_number_float() const noexcept
11760 {
11761 return (m_type == value_t::number_float);
11762 }
11763
11764 /*!
11765 @brief return whether value is an object
11766
11767 This function returns true if and only if the JSON value is an object.
11768
11769 @return `true` if type is object, `false` otherwise.
11770
11771 @complexity Constant.
11772
11773 @exceptionsafety No-throw guarantee: this member function never throws
11774 exceptions.
11775
11776 @liveexample{The following code exemplifies `is_object()` for all JSON
11777 types.,is_object}
11778
11779 @since version 1.0.0
11780 */
is_object() const11781 constexpr bool is_object() const noexcept
11782 {
11783 return (m_type == value_t::object);
11784 }
11785
11786 /*!
11787 @brief return whether value is an array
11788
11789 This function returns true if and only if the JSON value is an array.
11790
11791 @return `true` if type is array, `false` otherwise.
11792
11793 @complexity Constant.
11794
11795 @exceptionsafety No-throw guarantee: this member function never throws
11796 exceptions.
11797
11798 @liveexample{The following code exemplifies `is_array()` for all JSON
11799 types.,is_array}
11800
11801 @since version 1.0.0
11802 */
is_array() const11803 constexpr bool is_array() const noexcept
11804 {
11805 return (m_type == value_t::array);
11806 }
11807
11808 /*!
11809 @brief return whether value is a string
11810
11811 This function returns true if and only if the JSON value is a string.
11812
11813 @return `true` if type is string, `false` otherwise.
11814
11815 @complexity Constant.
11816
11817 @exceptionsafety No-throw guarantee: this member function never throws
11818 exceptions.
11819
11820 @liveexample{The following code exemplifies `is_string()` for all JSON
11821 types.,is_string}
11822
11823 @since version 1.0.0
11824 */
is_string() const11825 constexpr bool is_string() const noexcept
11826 {
11827 return (m_type == value_t::string);
11828 }
11829
11830 /*!
11831 @brief return whether value is discarded
11832
11833 This function returns true if and only if the JSON value was discarded
11834 during parsing with a callback function (see @ref parser_callback_t).
11835
11836 @note This function will always be `false` for JSON values after parsing.
11837 That is, discarded values can only occur during parsing, but will be
11838 removed when inside a structured value or replaced by null in other cases.
11839
11840 @return `true` if type is discarded, `false` otherwise.
11841
11842 @complexity Constant.
11843
11844 @exceptionsafety No-throw guarantee: this member function never throws
11845 exceptions.
11846
11847 @liveexample{The following code exemplifies `is_discarded()` for all JSON
11848 types.,is_discarded}
11849
11850 @since version 1.0.0
11851 */
is_discarded() const11852 constexpr bool is_discarded() const noexcept
11853 {
11854 return (m_type == value_t::discarded);
11855 }
11856
11857 /*!
11858 @brief return the type of the JSON value (implicit)
11859
11860 Implicitly return the type of the JSON value as a value from the @ref
11861 value_t enumeration.
11862
11863 @return the type of the JSON value
11864
11865 @complexity Constant.
11866
11867 @exceptionsafety No-throw guarantee: this member function never throws
11868 exceptions.
11869
11870 @liveexample{The following code exemplifies the @ref value_t operator for
11871 all JSON types.,operator__value_t}
11872
11873 @sa @ref type() -- return the type of the JSON value (explicit)
11874 @sa @ref type_name() -- return the type as string
11875
11876 @since version 1.0.0
11877 */
operator value_t() const11878 constexpr operator value_t() const noexcept
11879 {
11880 return m_type;
11881 }
11882
11883 /// @}
11884
11885 private:
11886 //////////////////
11887 // value access //
11888 //////////////////
11889
11890 /// get a boolean (explicit)
get_impl(boolean_t *) const11891 boolean_t get_impl(boolean_t* /*unused*/) const
11892 {
11893 if (JSON_LIKELY(is_boolean()))
11894 {
11895 return m_value.boolean;
11896 }
11897
11898 JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
11899 }
11900
11901 /// get a pointer to the value (object)
get_impl_ptr(object_t *)11902 object_t* get_impl_ptr(object_t* /*unused*/) noexcept
11903 {
11904 return is_object() ? m_value.object : nullptr;
11905 }
11906
11907 /// get a pointer to the value (object)
get_impl_ptr(const object_t *) const11908 constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
11909 {
11910 return is_object() ? m_value.object : nullptr;
11911 }
11912
11913 /// get a pointer to the value (array)
get_impl_ptr(array_t *)11914 array_t* get_impl_ptr(array_t* /*unused*/) noexcept
11915 {
11916 return is_array() ? m_value.array : nullptr;
11917 }
11918
11919 /// get a pointer to the value (array)
get_impl_ptr(const array_t *) const11920 constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
11921 {
11922 return is_array() ? m_value.array : nullptr;
11923 }
11924
11925 /// get a pointer to the value (string)
get_impl_ptr(string_t *)11926 string_t* get_impl_ptr(string_t* /*unused*/) noexcept
11927 {
11928 return is_string() ? m_value.string : nullptr;
11929 }
11930
11931 /// get a pointer to the value (string)
get_impl_ptr(const string_t *) const11932 constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
11933 {
11934 return is_string() ? m_value.string : nullptr;
11935 }
11936
11937 /// get a pointer to the value (boolean)
get_impl_ptr(boolean_t *)11938 boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
11939 {
11940 return is_boolean() ? &m_value.boolean : nullptr;
11941 }
11942
11943 /// get a pointer to the value (boolean)
get_impl_ptr(const boolean_t *) const11944 constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
11945 {
11946 return is_boolean() ? &m_value.boolean : nullptr;
11947 }
11948
11949 /// get a pointer to the value (integer number)
get_impl_ptr(number_integer_t *)11950 number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
11951 {
11952 return is_number_integer() ? &m_value.number_integer : nullptr;
11953 }
11954
11955 /// get a pointer to the value (integer number)
get_impl_ptr(const number_integer_t *) const11956 constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
11957 {
11958 return is_number_integer() ? &m_value.number_integer : nullptr;
11959 }
11960
11961 /// get a pointer to the value (unsigned number)
get_impl_ptr(number_unsigned_t *)11962 number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
11963 {
11964 return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
11965 }
11966
11967 /// get a pointer to the value (unsigned number)
get_impl_ptr(const number_unsigned_t *) const11968 constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
11969 {
11970 return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
11971 }
11972
11973 /// get a pointer to the value (floating-point number)
get_impl_ptr(number_float_t *)11974 number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
11975 {
11976 return is_number_float() ? &m_value.number_float : nullptr;
11977 }
11978
11979 /// get a pointer to the value (floating-point number)
get_impl_ptr(const number_float_t *) const11980 constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
11981 {
11982 return is_number_float() ? &m_value.number_float : nullptr;
11983 }
11984
11985 /*!
11986 @brief helper function to implement get_ref()
11987
11988 This function helps to implement get_ref() without code duplication for
11989 const and non-const overloads
11990
11991 @tparam ThisType will be deduced as `basic_json` or `const basic_json`
11992
11993 @throw type_error.303 if ReferenceType does not match underlying value
11994 type of the current JSON
11995 */
11996 template<typename ReferenceType, typename ThisType>
get_ref_impl(ThisType & obj)11997 static ReferenceType get_ref_impl(ThisType& obj)
11998 {
11999 // delegate the call to get_ptr<>()
12000 auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
12001
12002 if (JSON_LIKELY(ptr != nullptr))
12003 {
12004 return *ptr;
12005 }
12006
12007 JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
12008 }
12009
12010 public:
12011 /// @name value access
12012 /// Direct access to the stored value of a JSON value.
12013 /// @{
12014
12015 /*!
12016 @brief get special-case overload
12017
12018 This overloads avoids a lot of template boilerplate, it can be seen as the
12019 identity method
12020
12021 @tparam BasicJsonType == @ref basic_json
12022
12023 @return a copy of *this
12024
12025 @complexity Constant.
12026
12027 @since version 2.1.0
12028 */
12029 template<typename BasicJsonType, detail::enable_if_t<
12030 std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
12031 int> = 0>
get() const12032 basic_json get() const
12033 {
12034 return *this;
12035 }
12036
12037 /*!
12038 @brief get a value (explicit)
12039
12040 Explicit type conversion between the JSON value and a compatible value
12041 which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
12042 and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
12043 The value is converted by calling the @ref json_serializer<ValueType>
12044 `from_json()` method.
12045
12046 The function is equivalent to executing
12047 @code {.cpp}
12048 ValueType ret;
12049 JSONSerializer<ValueType>::from_json(*this, ret);
12050 return ret;
12051 @endcode
12052
12053 This overloads is chosen if:
12054 - @a ValueType is not @ref basic_json,
12055 - @ref json_serializer<ValueType> has a `from_json()` method of the form
12056 `void from_json(const basic_json&, ValueType&)`, and
12057 - @ref json_serializer<ValueType> does not have a `from_json()` method of
12058 the form `ValueType from_json(const basic_json&)`
12059
12060 @tparam ValueTypeCV the provided value type
12061 @tparam ValueType the returned value type
12062
12063 @return copy of the JSON value, converted to @a ValueType
12064
12065 @throw what @ref json_serializer<ValueType> `from_json()` method throws
12066
12067 @liveexample{The example below shows several conversions from JSON values
12068 to other types. There a few things to note: (1) Floating-point numbers can
12069 be converted to integers\, (2) A JSON array can be converted to a standard
12070 `std::vector<short>`\, (3) A JSON object can be converted to C++
12071 associative containers such as `std::unordered_map<std::string\,
12072 json>`.,get__ValueType_const}
12073
12074 @since version 2.1.0
12075 */
12076 template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
12077 detail::enable_if_t <
12078 not std::is_same<basic_json_t, ValueType>::value and
12079 detail::has_from_json<basic_json_t, ValueType>::value and
12080 not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
12081 int> = 0>
12082 ValueType get() const noexcept(noexcept(
12083 JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
12084 {
12085 // we cannot static_assert on ValueTypeCV being non-const, because
12086 // there is support for get<const basic_json_t>(), which is why we
12087 // still need the uncvref
12088 static_assert(not std::is_reference<ValueTypeCV>::value,
12089 "get() cannot be used with reference types, you might want to use get_ref()");
12090 static_assert(std::is_default_constructible<ValueType>::value,
12091 "types must be DefaultConstructible when used with get()");
12092
12093 ValueType ret;
12094 JSONSerializer<ValueType>::from_json(*this, ret);
12095 return ret;
12096 }
12097
12098 /*!
12099 @brief get a value (explicit); special case
12100
12101 Explicit type conversion between the JSON value and a compatible value
12102 which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
12103 and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
12104 The value is converted by calling the @ref json_serializer<ValueType>
12105 `from_json()` method.
12106
12107 The function is equivalent to executing
12108 @code {.cpp}
12109 return JSONSerializer<ValueTypeCV>::from_json(*this);
12110 @endcode
12111
12112 This overloads is chosen if:
12113 - @a ValueType is not @ref basic_json and
12114 - @ref json_serializer<ValueType> has a `from_json()` method of the form
12115 `ValueType from_json(const basic_json&)`
12116
12117 @note If @ref json_serializer<ValueType> has both overloads of
12118 `from_json()`, this one is chosen.
12119
12120 @tparam ValueTypeCV the provided value type
12121 @tparam ValueType the returned value type
12122
12123 @return copy of the JSON value, converted to @a ValueType
12124
12125 @throw what @ref json_serializer<ValueType> `from_json()` method throws
12126
12127 @since version 2.1.0
12128 */
12129 template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
12130 detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
12131 detail::has_non_default_from_json<basic_json_t, ValueType>::value,
12132 int> = 0>
12133 ValueType get() const noexcept(noexcept(
12134 JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
12135 {
12136 static_assert(not std::is_reference<ValueTypeCV>::value,
12137 "get() cannot be used with reference types, you might want to use get_ref()");
12138 return JSONSerializer<ValueTypeCV>::from_json(*this);
12139 }
12140
12141 /*!
12142 @brief get a pointer value (explicit)
12143
12144 Explicit pointer access to the internally stored JSON value. No copies are
12145 made.
12146
12147 @warning The pointer becomes invalid if the underlying JSON object
12148 changes.
12149
12150 @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
12151 object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
12152 @ref number_unsigned_t, or @ref number_float_t.
12153
12154 @return pointer to the internally stored JSON value if the requested
12155 pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
12156
12157 @complexity Constant.
12158
12159 @liveexample{The example below shows how pointers to internal values of a
12160 JSON value can be requested. Note that no type conversions are made and a
12161 `nullptr` is returned if the value and the requested pointer type does not
12162 match.,get__PointerType}
12163
12164 @sa @ref get_ptr() for explicit pointer-member access
12165
12166 @since version 1.0.0
12167 */
12168 template<typename PointerType, typename std::enable_if<
12169 std::is_pointer<PointerType>::value, int>::type = 0>
12170 PointerType get() noexcept
12171 {
12172 // delegate the call to get_ptr
12173 return get_ptr<PointerType>();
12174 }
12175
12176 /*!
12177 @brief get a pointer value (explicit)
12178 @copydoc get()
12179 */
12180 template<typename PointerType, typename std::enable_if<
12181 std::is_pointer<PointerType>::value, int>::type = 0>
get() const12182 constexpr const PointerType get() const noexcept
12183 {
12184 // delegate the call to get_ptr
12185 return get_ptr<PointerType>();
12186 }
12187
12188 /*!
12189 @brief get a pointer value (implicit)
12190
12191 Implicit pointer access to the internally stored JSON value. No copies are
12192 made.
12193
12194 @warning Writing data to the pointee of the result yields an undefined
12195 state.
12196
12197 @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
12198 object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
12199 @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
12200 assertion.
12201
12202 @return pointer to the internally stored JSON value if the requested
12203 pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
12204
12205 @complexity Constant.
12206
12207 @liveexample{The example below shows how pointers to internal values of a
12208 JSON value can be requested. Note that no type conversions are made and a
12209 `nullptr` is returned if the value and the requested pointer type does not
12210 match.,get_ptr}
12211
12212 @since version 1.0.0
12213 */
12214 template<typename PointerType, typename std::enable_if<
12215 std::is_pointer<PointerType>::value, int>::type = 0>
12216 PointerType get_ptr() noexcept
12217 {
12218 // get the type of the PointerType (remove pointer and const)
12219 using pointee_t = typename std::remove_const<typename
12220 std::remove_pointer<typename
12221 std::remove_const<PointerType>::type>::type>::type;
12222 // make sure the type matches the allowed types
12223 static_assert(
12224 std::is_same<object_t, pointee_t>::value
12225 or std::is_same<array_t, pointee_t>::value
12226 or std::is_same<string_t, pointee_t>::value
12227 or std::is_same<boolean_t, pointee_t>::value
12228 or std::is_same<number_integer_t, pointee_t>::value
12229 or std::is_same<number_unsigned_t, pointee_t>::value
12230 or std::is_same<number_float_t, pointee_t>::value
12231 , "incompatible pointer type");
12232
12233 // delegate the call to get_impl_ptr<>()
12234 return get_impl_ptr(static_cast<PointerType>(nullptr));
12235 }
12236
12237 /*!
12238 @brief get a pointer value (implicit)
12239 @copydoc get_ptr()
12240 */
12241 template<typename PointerType, typename std::enable_if<
12242 std::is_pointer<PointerType>::value and
12243 std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
get_ptr() const12244 constexpr const PointerType get_ptr() const noexcept
12245 {
12246 // get the type of the PointerType (remove pointer and const)
12247 using pointee_t = typename std::remove_const<typename
12248 std::remove_pointer<typename
12249 std::remove_const<PointerType>::type>::type>::type;
12250 // make sure the type matches the allowed types
12251 static_assert(
12252 std::is_same<object_t, pointee_t>::value
12253 or std::is_same<array_t, pointee_t>::value
12254 or std::is_same<string_t, pointee_t>::value
12255 or std::is_same<boolean_t, pointee_t>::value
12256 or std::is_same<number_integer_t, pointee_t>::value
12257 or std::is_same<number_unsigned_t, pointee_t>::value
12258 or std::is_same<number_float_t, pointee_t>::value
12259 , "incompatible pointer type");
12260
12261 // delegate the call to get_impl_ptr<>() const
12262 return get_impl_ptr(static_cast<PointerType>(nullptr));
12263 }
12264
12265 /*!
12266 @brief get a reference value (implicit)
12267
12268 Implicit reference access to the internally stored JSON value. No copies
12269 are made.
12270
12271 @warning Writing data to the referee of the result yields an undefined
12272 state.
12273
12274 @tparam ReferenceType reference type; must be a reference to @ref array_t,
12275 @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
12276 @ref number_float_t. Enforced by static assertion.
12277
12278 @return reference to the internally stored JSON value if the requested
12279 reference type @a ReferenceType fits to the JSON value; throws
12280 type_error.303 otherwise
12281
12282 @throw type_error.303 in case passed type @a ReferenceType is incompatible
12283 with the stored JSON value; see example below
12284
12285 @complexity Constant.
12286
12287 @liveexample{The example shows several calls to `get_ref()`.,get_ref}
12288
12289 @since version 1.1.0
12290 */
12291 template<typename ReferenceType, typename std::enable_if<
12292 std::is_reference<ReferenceType>::value, int>::type = 0>
12293 ReferenceType get_ref()
12294 {
12295 // delegate call to get_ref_impl
12296 return get_ref_impl<ReferenceType>(*this);
12297 }
12298
12299 /*!
12300 @brief get a reference value (implicit)
12301 @copydoc get_ref()
12302 */
12303 template<typename ReferenceType, typename std::enable_if<
12304 std::is_reference<ReferenceType>::value and
12305 std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
12306 ReferenceType get_ref() const
12307 {
12308 // delegate call to get_ref_impl
12309 return get_ref_impl<ReferenceType>(*this);
12310 }
12311
12312 /*!
12313 @brief get a value (implicit)
12314
12315 Implicit type conversion between the JSON value and a compatible value.
12316 The call is realized by calling @ref get() const.
12317
12318 @tparam ValueType non-pointer type compatible to the JSON value, for
12319 instance `int` for JSON integer numbers, `bool` for JSON booleans, or
12320 `std::vector` types for JSON arrays. The character type of @ref string_t
12321 as well as an initializer list of this type is excluded to avoid
12322 ambiguities as these types implicitly convert to `std::string`.
12323
12324 @return copy of the JSON value, converted to type @a ValueType
12325
12326 @throw type_error.302 in case passed type @a ValueType is incompatible
12327 to the JSON value type (e.g., the JSON value is of type boolean, but a
12328 string is requested); see example below
12329
12330 @complexity Linear in the size of the JSON value.
12331
12332 @liveexample{The example below shows several conversions from JSON values
12333 to other types. There a few things to note: (1) Floating-point numbers can
12334 be converted to integers\, (2) A JSON array can be converted to a standard
12335 `std::vector<short>`\, (3) A JSON object can be converted to C++
12336 associative containers such as `std::unordered_map<std::string\,
12337 json>`.,operator__ValueType}
12338
12339 @since version 1.0.0
12340 */
12341 template < typename ValueType, typename std::enable_if <
12342 not std::is_pointer<ValueType>::value and
12343 not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
12344 not std::is_same<ValueType, typename string_t::value_type>::value
12345 #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
12346 and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
12347 #endif
12348 #if defined(JSON_HAS_CPP_17)
12349 and not std::is_same<ValueType, typename std::string_view>::value
12350 #endif
12351 , int >::type = 0 >
operator ValueType() const12352 operator ValueType() const
12353 {
12354 // delegate the call to get<>() const
12355 return get<ValueType>();
12356 }
12357
12358 /// @}
12359
12360
12361 ////////////////////
12362 // element access //
12363 ////////////////////
12364
12365 /// @name element access
12366 /// Access to the JSON value.
12367 /// @{
12368
12369 /*!
12370 @brief access specified array element with bounds checking
12371
12372 Returns a reference to the element at specified location @a idx, with
12373 bounds checking.
12374
12375 @param[in] idx index of the element to access
12376
12377 @return reference to the element at index @a idx
12378
12379 @throw type_error.304 if the JSON value is not an array; in this case,
12380 calling `at` with an index makes no sense. See example below.
12381 @throw out_of_range.401 if the index @a idx is out of range of the array;
12382 that is, `idx >= size()`. See example below.
12383
12384 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
12385 changes in the JSON value.
12386
12387 @complexity Constant.
12388
12389 @since version 1.0.0
12390
12391 @liveexample{The example below shows how array elements can be read and
12392 written using `at()`. It also demonstrates the different exceptions that
12393 can be thrown.,at__size_type}
12394 */
at(size_type idx)12395 reference at(size_type idx)
12396 {
12397 // at only works for arrays
12398 if (JSON_LIKELY(is_array()))
12399 {
12400 JSON_TRY
12401 {
12402 return m_value.array->at(idx);
12403 }
12404 JSON_CATCH (std::out_of_range&)
12405 {
12406 // create better exception explanation
12407 JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
12408 }
12409 }
12410 else
12411 {
12412 JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
12413 }
12414 }
12415
12416 /*!
12417 @brief access specified array element with bounds checking
12418
12419 Returns a const reference to the element at specified location @a idx,
12420 with bounds checking.
12421
12422 @param[in] idx index of the element to access
12423
12424 @return const reference to the element at index @a idx
12425
12426 @throw type_error.304 if the JSON value is not an array; in this case,
12427 calling `at` with an index makes no sense. See example below.
12428 @throw out_of_range.401 if the index @a idx is out of range of the array;
12429 that is, `idx >= size()`. See example below.
12430
12431 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
12432 changes in the JSON value.
12433
12434 @complexity Constant.
12435
12436 @since version 1.0.0
12437
12438 @liveexample{The example below shows how array elements can be read using
12439 `at()`. It also demonstrates the different exceptions that can be thrown.,
12440 at__size_type_const}
12441 */
at(size_type idx) const12442 const_reference at(size_type idx) const
12443 {
12444 // at only works for arrays
12445 if (JSON_LIKELY(is_array()))
12446 {
12447 JSON_TRY
12448 {
12449 return m_value.array->at(idx);
12450 }
12451 JSON_CATCH (std::out_of_range&)
12452 {
12453 // create better exception explanation
12454 JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
12455 }
12456 }
12457 else
12458 {
12459 JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
12460 }
12461 }
12462
12463 /*!
12464 @brief access specified object element with bounds checking
12465
12466 Returns a reference to the element at with specified key @a key, with
12467 bounds checking.
12468
12469 @param[in] key key of the element to access
12470
12471 @return reference to the element at key @a key
12472
12473 @throw type_error.304 if the JSON value is not an object; in this case,
12474 calling `at` with a key makes no sense. See example below.
12475 @throw out_of_range.403 if the key @a key is is not stored in the object;
12476 that is, `find(key) == end()`. See example below.
12477
12478 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
12479 changes in the JSON value.
12480
12481 @complexity Logarithmic in the size of the container.
12482
12483 @sa @ref operator[](const typename object_t::key_type&) for unchecked
12484 access by reference
12485 @sa @ref value() for access by value with a default value
12486
12487 @since version 1.0.0
12488
12489 @liveexample{The example below shows how object elements can be read and
12490 written using `at()`. It also demonstrates the different exceptions that
12491 can be thrown.,at__object_t_key_type}
12492 */
at(const typename object_t::key_type & key)12493 reference at(const typename object_t::key_type& key)
12494 {
12495 // at only works for objects
12496 if (JSON_LIKELY(is_object()))
12497 {
12498 JSON_TRY
12499 {
12500 return m_value.object->at(key);
12501 }
12502 JSON_CATCH (std::out_of_range&)
12503 {
12504 // create better exception explanation
12505 JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
12506 }
12507 }
12508 else
12509 {
12510 JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
12511 }
12512 }
12513
12514 /*!
12515 @brief access specified object element with bounds checking
12516
12517 Returns a const reference to the element at with specified key @a key,
12518 with bounds checking.
12519
12520 @param[in] key key of the element to access
12521
12522 @return const reference to the element at key @a key
12523
12524 @throw type_error.304 if the JSON value is not an object; in this case,
12525 calling `at` with a key makes no sense. See example below.
12526 @throw out_of_range.403 if the key @a key is is not stored in the object;
12527 that is, `find(key) == end()`. See example below.
12528
12529 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
12530 changes in the JSON value.
12531
12532 @complexity Logarithmic in the size of the container.
12533
12534 @sa @ref operator[](const typename object_t::key_type&) for unchecked
12535 access by reference
12536 @sa @ref value() for access by value with a default value
12537
12538 @since version 1.0.0
12539
12540 @liveexample{The example below shows how object elements can be read using
12541 `at()`. It also demonstrates the different exceptions that can be thrown.,
12542 at__object_t_key_type_const}
12543 */
at(const typename object_t::key_type & key) const12544 const_reference at(const typename object_t::key_type& key) const
12545 {
12546 // at only works for objects
12547 if (JSON_LIKELY(is_object()))
12548 {
12549 JSON_TRY
12550 {
12551 return m_value.object->at(key);
12552 }
12553 JSON_CATCH (std::out_of_range&)
12554 {
12555 // create better exception explanation
12556 JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
12557 }
12558 }
12559 else
12560 {
12561 JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
12562 }
12563 }
12564
12565 /*!
12566 @brief access specified array element
12567
12568 Returns a reference to the element at specified location @a idx.
12569
12570 @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
12571 then the array is silently filled up with `null` values to make `idx` a
12572 valid reference to the last stored element.
12573
12574 @param[in] idx index of the element to access
12575
12576 @return reference to the element at index @a idx
12577
12578 @throw type_error.305 if the JSON value is not an array or null; in that
12579 cases, using the [] operator with an index makes no sense.
12580
12581 @complexity Constant if @a idx is in the range of the array. Otherwise
12582 linear in `idx - size()`.
12583
12584 @liveexample{The example below shows how array elements can be read and
12585 written using `[]` operator. Note the addition of `null`
12586 values.,operatorarray__size_type}
12587
12588 @since version 1.0.0
12589 */
operator [](size_type idx)12590 reference operator[](size_type idx)
12591 {
12592 // implicitly convert null value to an empty array
12593 if (is_null())
12594 {
12595 m_type = value_t::array;
12596 m_value.array = create<array_t>();
12597 assert_invariant();
12598 }
12599
12600 // operator[] only works for arrays
12601 if (JSON_LIKELY(is_array()))
12602 {
12603 // fill up array with null values if given idx is outside range
12604 if (idx >= m_value.array->size())
12605 {
12606 m_value.array->insert(m_value.array->end(),
12607 idx - m_value.array->size() + 1,
12608 basic_json());
12609 }
12610
12611 return m_value.array->operator[](idx);
12612 }
12613
12614 JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
12615 }
12616
12617 /*!
12618 @brief access specified array element
12619
12620 Returns a const reference to the element at specified location @a idx.
12621
12622 @param[in] idx index of the element to access
12623
12624 @return const reference to the element at index @a idx
12625
12626 @throw type_error.305 if the JSON value is not an array; in that case,
12627 using the [] operator with an index makes no sense.
12628
12629 @complexity Constant.
12630
12631 @liveexample{The example below shows how array elements can be read using
12632 the `[]` operator.,operatorarray__size_type_const}
12633
12634 @since version 1.0.0
12635 */
operator [](size_type idx) const12636 const_reference operator[](size_type idx) const
12637 {
12638 // const operator[] only works for arrays
12639 if (JSON_LIKELY(is_array()))
12640 {
12641 return m_value.array->operator[](idx);
12642 }
12643
12644 JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
12645 }
12646
12647 /*!
12648 @brief access specified object element
12649
12650 Returns a reference to the element at with specified key @a key.
12651
12652 @note If @a key is not found in the object, then it is silently added to
12653 the object and filled with a `null` value to make `key` a valid reference.
12654 In case the value was `null` before, it is converted to an object.
12655
12656 @param[in] key key of the element to access
12657
12658 @return reference to the element at key @a key
12659
12660 @throw type_error.305 if the JSON value is not an object or null; in that
12661 cases, using the [] operator with a key makes no sense.
12662
12663 @complexity Logarithmic in the size of the container.
12664
12665 @liveexample{The example below shows how object elements can be read and
12666 written using the `[]` operator.,operatorarray__key_type}
12667
12668 @sa @ref at(const typename object_t::key_type&) for access by reference
12669 with range checking
12670 @sa @ref value() for access by value with a default value
12671
12672 @since version 1.0.0
12673 */
operator [](const typename object_t::key_type & key)12674 reference operator[](const typename object_t::key_type& key)
12675 {
12676 // implicitly convert null value to an empty object
12677 if (is_null())
12678 {
12679 m_type = value_t::object;
12680 m_value.object = create<object_t>();
12681 assert_invariant();
12682 }
12683
12684 // operator[] only works for objects
12685 if (JSON_LIKELY(is_object()))
12686 {
12687 return m_value.object->operator[](key);
12688 }
12689
12690 JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
12691 }
12692
12693 /*!
12694 @brief read-only access specified object element
12695
12696 Returns a const reference to the element at with specified key @a key. No
12697 bounds checking is performed.
12698
12699 @warning If the element with key @a key does not exist, the behavior is
12700 undefined.
12701
12702 @param[in] key key of the element to access
12703
12704 @return const reference to the element at key @a key
12705
12706 @pre The element with key @a key must exist. **This precondition is
12707 enforced with an assertion.**
12708
12709 @throw type_error.305 if the JSON value is not an object; in that case,
12710 using the [] operator with a key makes no sense.
12711
12712 @complexity Logarithmic in the size of the container.
12713
12714 @liveexample{The example below shows how object elements can be read using
12715 the `[]` operator.,operatorarray__key_type_const}
12716
12717 @sa @ref at(const typename object_t::key_type&) for access by reference
12718 with range checking
12719 @sa @ref value() for access by value with a default value
12720
12721 @since version 1.0.0
12722 */
operator [](const typename object_t::key_type & key) const12723 const_reference operator[](const typename object_t::key_type& key) const
12724 {
12725 // const operator[] only works for objects
12726 if (JSON_LIKELY(is_object()))
12727 {
12728 assert(m_value.object->find(key) != m_value.object->end());
12729 return m_value.object->find(key)->second;
12730 }
12731
12732 JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
12733 }
12734
12735 /*!
12736 @brief access specified object element
12737
12738 Returns a reference to the element at with specified key @a key.
12739
12740 @note If @a key is not found in the object, then it is silently added to
12741 the object and filled with a `null` value to make `key` a valid reference.
12742 In case the value was `null` before, it is converted to an object.
12743
12744 @param[in] key key of the element to access
12745
12746 @return reference to the element at key @a key
12747
12748 @throw type_error.305 if the JSON value is not an object or null; in that
12749 cases, using the [] operator with a key makes no sense.
12750
12751 @complexity Logarithmic in the size of the container.
12752
12753 @liveexample{The example below shows how object elements can be read and
12754 written using the `[]` operator.,operatorarray__key_type}
12755
12756 @sa @ref at(const typename object_t::key_type&) for access by reference
12757 with range checking
12758 @sa @ref value() for access by value with a default value
12759
12760 @since version 1.1.0
12761 */
12762 template<typename T>
operator [](T * key)12763 reference operator[](T* key)
12764 {
12765 // implicitly convert null to object
12766 if (is_null())
12767 {
12768 m_type = value_t::object;
12769 m_value = value_t::object;
12770 assert_invariant();
12771 }
12772
12773 // at only works for objects
12774 if (JSON_LIKELY(is_object()))
12775 {
12776 return m_value.object->operator[](key);
12777 }
12778
12779 JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
12780 }
12781
12782 /*!
12783 @brief read-only access specified object element
12784
12785 Returns a const reference to the element at with specified key @a key. No
12786 bounds checking is performed.
12787
12788 @warning If the element with key @a key does not exist, the behavior is
12789 undefined.
12790
12791 @param[in] key key of the element to access
12792
12793 @return const reference to the element at key @a key
12794
12795 @pre The element with key @a key must exist. **This precondition is
12796 enforced with an assertion.**
12797
12798 @throw type_error.305 if the JSON value is not an object; in that case,
12799 using the [] operator with a key makes no sense.
12800
12801 @complexity Logarithmic in the size of the container.
12802
12803 @liveexample{The example below shows how object elements can be read using
12804 the `[]` operator.,operatorarray__key_type_const}
12805
12806 @sa @ref at(const typename object_t::key_type&) for access by reference
12807 with range checking
12808 @sa @ref value() for access by value with a default value
12809
12810 @since version 1.1.0
12811 */
12812 template<typename T>
operator [](T * key) const12813 const_reference operator[](T* key) const
12814 {
12815 // at only works for objects
12816 if (JSON_LIKELY(is_object()))
12817 {
12818 assert(m_value.object->find(key) != m_value.object->end());
12819 return m_value.object->find(key)->second;
12820 }
12821
12822 JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
12823 }
12824
12825 /*!
12826 @brief access specified object element with default value
12827
12828 Returns either a copy of an object's element at the specified key @a key
12829 or a given default value if no element with key @a key exists.
12830
12831 The function is basically equivalent to executing
12832 @code {.cpp}
12833 try {
12834 return at(key);
12835 } catch(out_of_range) {
12836 return default_value;
12837 }
12838 @endcode
12839
12840 @note Unlike @ref at(const typename object_t::key_type&), this function
12841 does not throw if the given key @a key was not found.
12842
12843 @note Unlike @ref operator[](const typename object_t::key_type& key), this
12844 function does not implicitly add an element to the position defined by @a
12845 key. This function is furthermore also applicable to const objects.
12846
12847 @param[in] key key of the element to access
12848 @param[in] default_value the value to return if @a key is not found
12849
12850 @tparam ValueType type compatible to JSON values, for instance `int` for
12851 JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
12852 JSON arrays. Note the type of the expected value at @a key and the default
12853 value @a default_value must be compatible.
12854
12855 @return copy of the element at key @a key or @a default_value if @a key
12856 is not found
12857
12858 @throw type_error.306 if the JSON value is not an object; in that case,
12859 using `value()` with a key makes no sense.
12860
12861 @complexity Logarithmic in the size of the container.
12862
12863 @liveexample{The example below shows how object elements can be queried
12864 with a default value.,basic_json__value}
12865
12866 @sa @ref at(const typename object_t::key_type&) for access by reference
12867 with range checking
12868 @sa @ref operator[](const typename object_t::key_type&) for unchecked
12869 access by reference
12870
12871 @since version 1.0.0
12872 */
12873 template<class ValueType, typename std::enable_if<
12874 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
12875 ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
12876 {
12877 // at only works for objects
12878 if (JSON_LIKELY(is_object()))
12879 {
12880 // if key is found, return value and given default value otherwise
12881 const auto it = find(key);
12882 if (it != end())
12883 {
12884 return *it;
12885 }
12886
12887 return default_value;
12888 }
12889
12890 JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
12891 }
12892
12893 /*!
12894 @brief overload for a default value of type const char*
12895 @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
12896 */
value(const typename object_t::key_type & key,const char * default_value) const12897 string_t value(const typename object_t::key_type& key, const char* default_value) const
12898 {
12899 return value(key, string_t(default_value));
12900 }
12901
12902 /*!
12903 @brief access specified object element via JSON Pointer with default value
12904
12905 Returns either a copy of an object's element at the specified key @a key
12906 or a given default value if no element with key @a key exists.
12907
12908 The function is basically equivalent to executing
12909 @code {.cpp}
12910 try {
12911 return at(ptr);
12912 } catch(out_of_range) {
12913 return default_value;
12914 }
12915 @endcode
12916
12917 @note Unlike @ref at(const json_pointer&), this function does not throw
12918 if the given key @a key was not found.
12919
12920 @param[in] ptr a JSON pointer to the element to access
12921 @param[in] default_value the value to return if @a ptr found no value
12922
12923 @tparam ValueType type compatible to JSON values, for instance `int` for
12924 JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
12925 JSON arrays. Note the type of the expected value at @a key and the default
12926 value @a default_value must be compatible.
12927
12928 @return copy of the element at key @a key or @a default_value if @a key
12929 is not found
12930
12931 @throw type_error.306 if the JSON value is not an objec; in that case,
12932 using `value()` with a key makes no sense.
12933
12934 @complexity Logarithmic in the size of the container.
12935
12936 @liveexample{The example below shows how object elements can be queried
12937 with a default value.,basic_json__value_ptr}
12938
12939 @sa @ref operator[](const json_pointer&) for unchecked access by reference
12940
12941 @since version 2.0.2
12942 */
12943 template<class ValueType, typename std::enable_if<
12944 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
12945 ValueType value(const json_pointer& ptr, const ValueType& default_value) const
12946 {
12947 // at only works for objects
12948 if (JSON_LIKELY(is_object()))
12949 {
12950 // if pointer resolves a value, return it or use default value
12951 JSON_TRY
12952 {
12953 return ptr.get_checked(this);
12954 }
12955 JSON_CATCH (out_of_range&)
12956 {
12957 return default_value;
12958 }
12959 }
12960
12961 JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
12962 }
12963
12964 /*!
12965 @brief overload for a default value of type const char*
12966 @copydoc basic_json::value(const json_pointer&, ValueType) const
12967 */
value(const json_pointer & ptr,const char * default_value) const12968 string_t value(const json_pointer& ptr, const char* default_value) const
12969 {
12970 return value(ptr, string_t(default_value));
12971 }
12972
12973 /*!
12974 @brief access the first element
12975
12976 Returns a reference to the first element in the container. For a JSON
12977 container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
12978
12979 @return In case of a structured type (array or object), a reference to the
12980 first element is returned. In case of number, string, or boolean values, a
12981 reference to the value is returned.
12982
12983 @complexity Constant.
12984
12985 @pre The JSON value must not be `null` (would throw `std::out_of_range`)
12986 or an empty array or object (undefined behavior, **guarded by
12987 assertions**).
12988 @post The JSON value remains unchanged.
12989
12990 @throw invalid_iterator.214 when called on `null` value
12991
12992 @liveexample{The following code shows an example for `front()`.,front}
12993
12994 @sa @ref back() -- access the last element
12995
12996 @since version 1.0.0
12997 */
front()12998 reference front()
12999 {
13000 return *begin();
13001 }
13002
13003 /*!
13004 @copydoc basic_json::front()
13005 */
front() const13006 const_reference front() const
13007 {
13008 return *cbegin();
13009 }
13010
13011 /*!
13012 @brief access the last element
13013
13014 Returns a reference to the last element in the container. For a JSON
13015 container `c`, the expression `c.back()` is equivalent to
13016 @code {.cpp}
13017 auto tmp = c.end();
13018 --tmp;
13019 return *tmp;
13020 @endcode
13021
13022 @return In case of a structured type (array or object), a reference to the
13023 last element is returned. In case of number, string, or boolean values, a
13024 reference to the value is returned.
13025
13026 @complexity Constant.
13027
13028 @pre The JSON value must not be `null` (would throw `std::out_of_range`)
13029 or an empty array or object (undefined behavior, **guarded by
13030 assertions**).
13031 @post The JSON value remains unchanged.
13032
13033 @throw invalid_iterator.214 when called on a `null` value. See example
13034 below.
13035
13036 @liveexample{The following code shows an example for `back()`.,back}
13037
13038 @sa @ref front() -- access the first element
13039
13040 @since version 1.0.0
13041 */
back()13042 reference back()
13043 {
13044 auto tmp = end();
13045 --tmp;
13046 return *tmp;
13047 }
13048
13049 /*!
13050 @copydoc basic_json::back()
13051 */
back() const13052 const_reference back() const
13053 {
13054 auto tmp = cend();
13055 --tmp;
13056 return *tmp;
13057 }
13058
13059 /*!
13060 @brief remove element given an iterator
13061
13062 Removes the element specified by iterator @a pos. The iterator @a pos must
13063 be valid and dereferenceable. Thus the `end()` iterator (which is valid,
13064 but is not dereferenceable) cannot be used as a value for @a pos.
13065
13066 If called on a primitive type other than `null`, the resulting JSON value
13067 will be `null`.
13068
13069 @param[in] pos iterator to the element to remove
13070 @return Iterator following the last removed element. If the iterator @a
13071 pos refers to the last element, the `end()` iterator is returned.
13072
13073 @tparam IteratorType an @ref iterator or @ref const_iterator
13074
13075 @post Invalidates iterators and references at or after the point of the
13076 erase, including the `end()` iterator.
13077
13078 @throw type_error.307 if called on a `null` value; example: `"cannot use
13079 erase() with null"`
13080 @throw invalid_iterator.202 if called on an iterator which does not belong
13081 to the current JSON value; example: `"iterator does not fit current
13082 value"`
13083 @throw invalid_iterator.205 if called on a primitive type with invalid
13084 iterator (i.e., any iterator which is not `begin()`); example: `"iterator
13085 out of range"`
13086
13087 @complexity The complexity depends on the type:
13088 - objects: amortized constant
13089 - arrays: linear in distance between @a pos and the end of the container
13090 - strings: linear in the length of the string
13091 - other types: constant
13092
13093 @liveexample{The example shows the result of `erase()` for different JSON
13094 types.,erase__IteratorType}
13095
13096 @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
13097 the given range
13098 @sa @ref erase(const typename object_t::key_type&) -- removes the element
13099 from an object at the given key
13100 @sa @ref erase(const size_type) -- removes the element from an array at
13101 the given index
13102
13103 @since version 1.0.0
13104 */
13105 template<class IteratorType, typename std::enable_if<
13106 std::is_same<IteratorType, typename basic_json_t::iterator>::value or
13107 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
13108 = 0>
13109 IteratorType erase(IteratorType pos)
13110 {
13111 // make sure iterator fits the current value
13112 if (JSON_UNLIKELY(this != pos.m_object))
13113 {
13114 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
13115 }
13116
13117 IteratorType result = end();
13118
13119 switch (m_type)
13120 {
13121 case value_t::boolean:
13122 case value_t::number_float:
13123 case value_t::number_integer:
13124 case value_t::number_unsigned:
13125 case value_t::string:
13126 {
13127 if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
13128 {
13129 JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
13130 }
13131
13132 if (is_string())
13133 {
13134 AllocatorType<string_t> alloc;
13135 std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
13136 std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
13137 m_value.string = nullptr;
13138 }
13139
13140 m_type = value_t::null;
13141 assert_invariant();
13142 break;
13143 }
13144
13145 case value_t::object:
13146 {
13147 result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
13148 break;
13149 }
13150
13151 case value_t::array:
13152 {
13153 result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
13154 break;
13155 }
13156
13157 default:
13158 JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
13159 }
13160
13161 return result;
13162 }
13163
13164 /*!
13165 @brief remove elements given an iterator range
13166
13167 Removes the element specified by the range `[first; last)`. The iterator
13168 @a first does not need to be dereferenceable if `first == last`: erasing
13169 an empty range is a no-op.
13170
13171 If called on a primitive type other than `null`, the resulting JSON value
13172 will be `null`.
13173
13174 @param[in] first iterator to the beginning of the range to remove
13175 @param[in] last iterator past the end of the range to remove
13176 @return Iterator following the last removed element. If the iterator @a
13177 second refers to the last element, the `end()` iterator is returned.
13178
13179 @tparam IteratorType an @ref iterator or @ref const_iterator
13180
13181 @post Invalidates iterators and references at or after the point of the
13182 erase, including the `end()` iterator.
13183
13184 @throw type_error.307 if called on a `null` value; example: `"cannot use
13185 erase() with null"`
13186 @throw invalid_iterator.203 if called on iterators which does not belong
13187 to the current JSON value; example: `"iterators do not fit current value"`
13188 @throw invalid_iterator.204 if called on a primitive type with invalid
13189 iterators (i.e., if `first != begin()` and `last != end()`); example:
13190 `"iterators out of range"`
13191
13192 @complexity The complexity depends on the type:
13193 - objects: `log(size()) + std::distance(first, last)`
13194 - arrays: linear in the distance between @a first and @a last, plus linear
13195 in the distance between @a last and end of the container
13196 - strings: linear in the length of the string
13197 - other types: constant
13198
13199 @liveexample{The example shows the result of `erase()` for different JSON
13200 types.,erase__IteratorType_IteratorType}
13201
13202 @sa @ref erase(IteratorType) -- removes the element at a given position
13203 @sa @ref erase(const typename object_t::key_type&) -- removes the element
13204 from an object at the given key
13205 @sa @ref erase(const size_type) -- removes the element from an array at
13206 the given index
13207
13208 @since version 1.0.0
13209 */
13210 template<class IteratorType, typename std::enable_if<
13211 std::is_same<IteratorType, typename basic_json_t::iterator>::value or
13212 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
13213 = 0>
13214 IteratorType erase(IteratorType first, IteratorType last)
13215 {
13216 // make sure iterator fits the current value
13217 if (JSON_UNLIKELY(this != first.m_object or this != last.m_object))
13218 {
13219 JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
13220 }
13221
13222 IteratorType result = end();
13223
13224 switch (m_type)
13225 {
13226 case value_t::boolean:
13227 case value_t::number_float:
13228 case value_t::number_integer:
13229 case value_t::number_unsigned:
13230 case value_t::string:
13231 {
13232 if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin()
13233 or not last.m_it.primitive_iterator.is_end()))
13234 {
13235 JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
13236 }
13237
13238 if (is_string())
13239 {
13240 AllocatorType<string_t> alloc;
13241 std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
13242 std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
13243 m_value.string = nullptr;
13244 }
13245
13246 m_type = value_t::null;
13247 assert_invariant();
13248 break;
13249 }
13250
13251 case value_t::object:
13252 {
13253 result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
13254 last.m_it.object_iterator);
13255 break;
13256 }
13257
13258 case value_t::array:
13259 {
13260 result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
13261 last.m_it.array_iterator);
13262 break;
13263 }
13264
13265 default:
13266 JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
13267 }
13268
13269 return result;
13270 }
13271
13272 /*!
13273 @brief remove element from a JSON object given a key
13274
13275 Removes elements from a JSON object with the key value @a key.
13276
13277 @param[in] key value of the elements to remove
13278
13279 @return Number of elements removed. If @a ObjectType is the default
13280 `std::map` type, the return value will always be `0` (@a key was not
13281 found) or `1` (@a key was found).
13282
13283 @post References and iterators to the erased elements are invalidated.
13284 Other references and iterators are not affected.
13285
13286 @throw type_error.307 when called on a type other than JSON object;
13287 example: `"cannot use erase() with null"`
13288
13289 @complexity `log(size()) + count(key)`
13290
13291 @liveexample{The example shows the effect of `erase()`.,erase__key_type}
13292
13293 @sa @ref erase(IteratorType) -- removes the element at a given position
13294 @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
13295 the given range
13296 @sa @ref erase(const size_type) -- removes the element from an array at
13297 the given index
13298
13299 @since version 1.0.0
13300 */
erase(const typename object_t::key_type & key)13301 size_type erase(const typename object_t::key_type& key)
13302 {
13303 // this erase only works for objects
13304 if (JSON_LIKELY(is_object()))
13305 {
13306 return m_value.object->erase(key);
13307 }
13308
13309 JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
13310 }
13311
13312 /*!
13313 @brief remove element from a JSON array given an index
13314
13315 Removes element from a JSON array at the index @a idx.
13316
13317 @param[in] idx index of the element to remove
13318
13319 @throw type_error.307 when called on a type other than JSON object;
13320 example: `"cannot use erase() with null"`
13321 @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
13322 is out of range"`
13323
13324 @complexity Linear in distance between @a idx and the end of the container.
13325
13326 @liveexample{The example shows the effect of `erase()`.,erase__size_type}
13327
13328 @sa @ref erase(IteratorType) -- removes the element at a given position
13329 @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
13330 the given range
13331 @sa @ref erase(const typename object_t::key_type&) -- removes the element
13332 from an object at the given key
13333
13334 @since version 1.0.0
13335 */
erase(const size_type idx)13336 void erase(const size_type idx)
13337 {
13338 // this erase only works for arrays
13339 if (JSON_LIKELY(is_array()))
13340 {
13341 if (JSON_UNLIKELY(idx >= size()))
13342 {
13343 JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
13344 }
13345
13346 m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
13347 }
13348 else
13349 {
13350 JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
13351 }
13352 }
13353
13354 /// @}
13355
13356
13357 ////////////
13358 // lookup //
13359 ////////////
13360
13361 /// @name lookup
13362 /// @{
13363
13364 /*!
13365 @brief find an element in a JSON object
13366
13367 Finds an element in a JSON object with key equivalent to @a key. If the
13368 element is not found or the JSON value is not an object, end() is
13369 returned.
13370
13371 @note This method always returns @ref end() when executed on a JSON type
13372 that is not an object.
13373
13374 @param[in] key key value of the element to search for.
13375
13376 @return Iterator to an element with key equivalent to @a key. If no such
13377 element is found or the JSON value is not an object, past-the-end (see
13378 @ref end()) iterator is returned.
13379
13380 @complexity Logarithmic in the size of the JSON object.
13381
13382 @liveexample{The example shows how `find()` is used.,find__key_type}
13383
13384 @since version 1.0.0
13385 */
13386 template<typename KeyT>
find(KeyT && key)13387 iterator find(KeyT&& key)
13388 {
13389 auto result = end();
13390
13391 if (is_object())
13392 {
13393 result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
13394 }
13395
13396 return result;
13397 }
13398
13399 /*!
13400 @brief find an element in a JSON object
13401 @copydoc find(KeyT&&)
13402 */
13403 template<typename KeyT>
find(KeyT && key) const13404 const_iterator find(KeyT&& key) const
13405 {
13406 auto result = cend();
13407
13408 if (is_object())
13409 {
13410 result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
13411 }
13412
13413 return result;
13414 }
13415
13416 /*!
13417 @brief returns the number of occurrences of a key in a JSON object
13418
13419 Returns the number of elements with key @a key. If ObjectType is the
13420 default `std::map` type, the return value will always be `0` (@a key was
13421 not found) or `1` (@a key was found).
13422
13423 @note This method always returns `0` when executed on a JSON type that is
13424 not an object.
13425
13426 @param[in] key key value of the element to count
13427
13428 @return Number of elements with key @a key. If the JSON value is not an
13429 object, the return value will be `0`.
13430
13431 @complexity Logarithmic in the size of the JSON object.
13432
13433 @liveexample{The example shows how `count()` is used.,count}
13434
13435 @since version 1.0.0
13436 */
13437 template<typename KeyT>
count(KeyT && key) const13438 size_type count(KeyT&& key) const
13439 {
13440 // return 0 for all nonobject types
13441 return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
13442 }
13443
13444 /// @}
13445
13446
13447 ///////////////
13448 // iterators //
13449 ///////////////
13450
13451 /// @name iterators
13452 /// @{
13453
13454 /*!
13455 @brief returns an iterator to the first element
13456
13457 Returns an iterator to the first element.
13458
13459 @image html range-begin-end.svg "Illustration from cppreference.com"
13460
13461 @return iterator to the first element
13462
13463 @complexity Constant.
13464
13465 @requirement This function helps `basic_json` satisfying the
13466 [Container](http://en.cppreference.com/w/cpp/concept/Container)
13467 requirements:
13468 - The complexity is constant.
13469
13470 @liveexample{The following code shows an example for `begin()`.,begin}
13471
13472 @sa @ref cbegin() -- returns a const iterator to the beginning
13473 @sa @ref end() -- returns an iterator to the end
13474 @sa @ref cend() -- returns a const iterator to the end
13475
13476 @since version 1.0.0
13477 */
begin()13478 iterator begin() noexcept
13479 {
13480 iterator result(this);
13481 result.set_begin();
13482 return result;
13483 }
13484
13485 /*!
13486 @copydoc basic_json::cbegin()
13487 */
begin() const13488 const_iterator begin() const noexcept
13489 {
13490 return cbegin();
13491 }
13492
13493 /*!
13494 @brief returns a const iterator to the first element
13495
13496 Returns a const iterator to the first element.
13497
13498 @image html range-begin-end.svg "Illustration from cppreference.com"
13499
13500 @return const iterator to the first element
13501
13502 @complexity Constant.
13503
13504 @requirement This function helps `basic_json` satisfying the
13505 [Container](http://en.cppreference.com/w/cpp/concept/Container)
13506 requirements:
13507 - The complexity is constant.
13508 - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
13509
13510 @liveexample{The following code shows an example for `cbegin()`.,cbegin}
13511
13512 @sa @ref begin() -- returns an iterator to the beginning
13513 @sa @ref end() -- returns an iterator to the end
13514 @sa @ref cend() -- returns a const iterator to the end
13515
13516 @since version 1.0.0
13517 */
cbegin() const13518 const_iterator cbegin() const noexcept
13519 {
13520 const_iterator result(this);
13521 result.set_begin();
13522 return result;
13523 }
13524
13525 /*!
13526 @brief returns an iterator to one past the last element
13527
13528 Returns an iterator to one past the last element.
13529
13530 @image html range-begin-end.svg "Illustration from cppreference.com"
13531
13532 @return iterator one past the last element
13533
13534 @complexity Constant.
13535
13536 @requirement This function helps `basic_json` satisfying the
13537 [Container](http://en.cppreference.com/w/cpp/concept/Container)
13538 requirements:
13539 - The complexity is constant.
13540
13541 @liveexample{The following code shows an example for `end()`.,end}
13542
13543 @sa @ref cend() -- returns a const iterator to the end
13544 @sa @ref begin() -- returns an iterator to the beginning
13545 @sa @ref cbegin() -- returns a const iterator to the beginning
13546
13547 @since version 1.0.0
13548 */
end()13549 iterator end() noexcept
13550 {
13551 iterator result(this);
13552 result.set_end();
13553 return result;
13554 }
13555
13556 /*!
13557 @copydoc basic_json::cend()
13558 */
end() const13559 const_iterator end() const noexcept
13560 {
13561 return cend();
13562 }
13563
13564 /*!
13565 @brief returns a const iterator to one past the last element
13566
13567 Returns a const iterator to one past the last element.
13568
13569 @image html range-begin-end.svg "Illustration from cppreference.com"
13570
13571 @return const iterator one past the last element
13572
13573 @complexity Constant.
13574
13575 @requirement This function helps `basic_json` satisfying the
13576 [Container](http://en.cppreference.com/w/cpp/concept/Container)
13577 requirements:
13578 - The complexity is constant.
13579 - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
13580
13581 @liveexample{The following code shows an example for `cend()`.,cend}
13582
13583 @sa @ref end() -- returns an iterator to the end
13584 @sa @ref begin() -- returns an iterator to the beginning
13585 @sa @ref cbegin() -- returns a const iterator to the beginning
13586
13587 @since version 1.0.0
13588 */
cend() const13589 const_iterator cend() const noexcept
13590 {
13591 const_iterator result(this);
13592 result.set_end();
13593 return result;
13594 }
13595
13596 /*!
13597 @brief returns an iterator to the reverse-beginning
13598
13599 Returns an iterator to the reverse-beginning; that is, the last element.
13600
13601 @image html range-rbegin-rend.svg "Illustration from cppreference.com"
13602
13603 @complexity Constant.
13604
13605 @requirement This function helps `basic_json` satisfying the
13606 [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
13607 requirements:
13608 - The complexity is constant.
13609 - Has the semantics of `reverse_iterator(end())`.
13610
13611 @liveexample{The following code shows an example for `rbegin()`.,rbegin}
13612
13613 @sa @ref crbegin() -- returns a const reverse iterator to the beginning
13614 @sa @ref rend() -- returns a reverse iterator to the end
13615 @sa @ref crend() -- returns a const reverse iterator to the end
13616
13617 @since version 1.0.0
13618 */
rbegin()13619 reverse_iterator rbegin() noexcept
13620 {
13621 return reverse_iterator(end());
13622 }
13623
13624 /*!
13625 @copydoc basic_json::crbegin()
13626 */
rbegin() const13627 const_reverse_iterator rbegin() const noexcept
13628 {
13629 return crbegin();
13630 }
13631
13632 /*!
13633 @brief returns an iterator to the reverse-end
13634
13635 Returns an iterator to the reverse-end; that is, one before the first
13636 element.
13637
13638 @image html range-rbegin-rend.svg "Illustration from cppreference.com"
13639
13640 @complexity Constant.
13641
13642 @requirement This function helps `basic_json` satisfying the
13643 [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
13644 requirements:
13645 - The complexity is constant.
13646 - Has the semantics of `reverse_iterator(begin())`.
13647
13648 @liveexample{The following code shows an example for `rend()`.,rend}
13649
13650 @sa @ref crend() -- returns a const reverse iterator to the end
13651 @sa @ref rbegin() -- returns a reverse iterator to the beginning
13652 @sa @ref crbegin() -- returns a const reverse iterator to the beginning
13653
13654 @since version 1.0.0
13655 */
rend()13656 reverse_iterator rend() noexcept
13657 {
13658 return reverse_iterator(begin());
13659 }
13660
13661 /*!
13662 @copydoc basic_json::crend()
13663 */
rend() const13664 const_reverse_iterator rend() const noexcept
13665 {
13666 return crend();
13667 }
13668
13669 /*!
13670 @brief returns a const reverse iterator to the last element
13671
13672 Returns a const iterator to the reverse-beginning; that is, the last
13673 element.
13674
13675 @image html range-rbegin-rend.svg "Illustration from cppreference.com"
13676
13677 @complexity Constant.
13678
13679 @requirement This function helps `basic_json` satisfying the
13680 [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
13681 requirements:
13682 - The complexity is constant.
13683 - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
13684
13685 @liveexample{The following code shows an example for `crbegin()`.,crbegin}
13686
13687 @sa @ref rbegin() -- returns a reverse iterator to the beginning
13688 @sa @ref rend() -- returns a reverse iterator to the end
13689 @sa @ref crend() -- returns a const reverse iterator to the end
13690
13691 @since version 1.0.0
13692 */
crbegin() const13693 const_reverse_iterator crbegin() const noexcept
13694 {
13695 return const_reverse_iterator(cend());
13696 }
13697
13698 /*!
13699 @brief returns a const reverse iterator to one before the first
13700
13701 Returns a const reverse iterator to the reverse-end; that is, one before
13702 the first element.
13703
13704 @image html range-rbegin-rend.svg "Illustration from cppreference.com"
13705
13706 @complexity Constant.
13707
13708 @requirement This function helps `basic_json` satisfying the
13709 [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
13710 requirements:
13711 - The complexity is constant.
13712 - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
13713
13714 @liveexample{The following code shows an example for `crend()`.,crend}
13715
13716 @sa @ref rend() -- returns a reverse iterator to the end
13717 @sa @ref rbegin() -- returns a reverse iterator to the beginning
13718 @sa @ref crbegin() -- returns a const reverse iterator to the beginning
13719
13720 @since version 1.0.0
13721 */
crend() const13722 const_reverse_iterator crend() const noexcept
13723 {
13724 return const_reverse_iterator(cbegin());
13725 }
13726
13727 public:
13728 /*!
13729 @brief wrapper to access iterator member functions in range-based for
13730
13731 This function allows to access @ref iterator::key() and @ref
13732 iterator::value() during range-based for loops. In these loops, a
13733 reference to the JSON values is returned, so there is no access to the
13734 underlying iterator.
13735
13736 For loop without iterator_wrapper:
13737
13738 @code{cpp}
13739 for (auto it = j_object.begin(); it != j_object.end(); ++it)
13740 {
13741 std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
13742 }
13743 @endcode
13744
13745 Range-based for loop without iterator proxy:
13746
13747 @code{cpp}
13748 for (auto it : j_object)
13749 {
13750 // "it" is of type json::reference and has no key() member
13751 std::cout << "value: " << it << '\n';
13752 }
13753 @endcode
13754
13755 Range-based for loop with iterator proxy:
13756
13757 @code{cpp}
13758 for (auto it : json::iterator_wrapper(j_object))
13759 {
13760 std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
13761 }
13762 @endcode
13763
13764 @note When iterating over an array, `key()` will return the index of the
13765 element as string (see example).
13766
13767 @param[in] ref reference to a JSON value
13768 @return iteration proxy object wrapping @a ref with an interface to use in
13769 range-based for loops
13770
13771 @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
13772
13773 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
13774 changes in the JSON value.
13775
13776 @complexity Constant.
13777
13778 @note The name of this function is not yet final and may change in the
13779 future.
13780
13781 @deprecated This stream operator is deprecated and will be removed in
13782 future 4.0.0 of the library. Please use @ref items() instead;
13783 that is, replace `json::iterator_wrapper(j)` with `j.items()`.
13784 */
13785 JSON_DEPRECATED
iterator_wrapper(reference ref)13786 static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
13787 {
13788 return ref.items();
13789 }
13790
13791 /*!
13792 @copydoc iterator_wrapper(reference)
13793 */
13794 JSON_DEPRECATED
iterator_wrapper(const_reference ref)13795 static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
13796 {
13797 return ref.items();
13798 }
13799
13800 /*!
13801 @brief helper to access iterator member functions in range-based for
13802
13803 This function allows to access @ref iterator::key() and @ref
13804 iterator::value() during range-based for loops. In these loops, a
13805 reference to the JSON values is returned, so there is no access to the
13806 underlying iterator.
13807
13808 For loop without `items()` function:
13809
13810 @code{cpp}
13811 for (auto it = j_object.begin(); it != j_object.end(); ++it)
13812 {
13813 std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
13814 }
13815 @endcode
13816
13817 Range-based for loop without `items()` function:
13818
13819 @code{cpp}
13820 for (auto it : j_object)
13821 {
13822 // "it" is of type json::reference and has no key() member
13823 std::cout << "value: " << it << '\n';
13824 }
13825 @endcode
13826
13827 Range-based for loop with `items()` function:
13828
13829 @code{cpp}
13830 for (auto it : j_object.items())
13831 {
13832 std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
13833 }
13834 @endcode
13835
13836 @note When iterating over an array, `key()` will return the index of the
13837 element as string (see example). For primitive types (e.g., numbers),
13838 `key()` returns an empty string.
13839
13840 @return iteration proxy object wrapping @a ref with an interface to use in
13841 range-based for loops
13842
13843 @liveexample{The following code shows how the function is used.,items}
13844
13845 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
13846 changes in the JSON value.
13847
13848 @complexity Constant.
13849
13850 @since version 3.x.x.
13851 */
items()13852 iteration_proxy<iterator> items() noexcept
13853 {
13854 return iteration_proxy<iterator>(*this);
13855 }
13856
13857 /*!
13858 @copydoc items()
13859 */
items() const13860 iteration_proxy<const_iterator> items() const noexcept
13861 {
13862 return iteration_proxy<const_iterator>(*this);
13863 }
13864
13865 /// @}
13866
13867
13868 //////////////
13869 // capacity //
13870 //////////////
13871
13872 /// @name capacity
13873 /// @{
13874
13875 /*!
13876 @brief checks whether the container is empty.
13877
13878 Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
13879
13880 @return The return value depends on the different types and is
13881 defined as follows:
13882 Value type | return value
13883 ----------- | -------------
13884 null | `true`
13885 boolean | `false`
13886 string | `false`
13887 number | `false`
13888 object | result of function `object_t::empty()`
13889 array | result of function `array_t::empty()`
13890
13891 @liveexample{The following code uses `empty()` to check if a JSON
13892 object contains any elements.,empty}
13893
13894 @complexity Constant, as long as @ref array_t and @ref object_t satisfy
13895 the Container concept; that is, their `empty()` functions have constant
13896 complexity.
13897
13898 @iterators No changes.
13899
13900 @exceptionsafety No-throw guarantee: this function never throws exceptions.
13901
13902 @note This function does not return whether a string stored as JSON value
13903 is empty - it returns whether the JSON container itself is empty which is
13904 false in the case of a string.
13905
13906 @requirement This function helps `basic_json` satisfying the
13907 [Container](http://en.cppreference.com/w/cpp/concept/Container)
13908 requirements:
13909 - The complexity is constant.
13910 - Has the semantics of `begin() == end()`.
13911
13912 @sa @ref size() -- returns the number of elements
13913
13914 @since version 1.0.0
13915 */
empty() const13916 bool empty() const noexcept
13917 {
13918 switch (m_type)
13919 {
13920 case value_t::null:
13921 {
13922 // null values are empty
13923 return true;
13924 }
13925
13926 case value_t::array:
13927 {
13928 // delegate call to array_t::empty()
13929 return m_value.array->empty();
13930 }
13931
13932 case value_t::object:
13933 {
13934 // delegate call to object_t::empty()
13935 return m_value.object->empty();
13936 }
13937
13938 default:
13939 {
13940 // all other types are nonempty
13941 return false;
13942 }
13943 }
13944 }
13945
13946 /*!
13947 @brief returns the number of elements
13948
13949 Returns the number of elements in a JSON value.
13950
13951 @return The return value depends on the different types and is
13952 defined as follows:
13953 Value type | return value
13954 ----------- | -------------
13955 null | `0`
13956 boolean | `1`
13957 string | `1`
13958 number | `1`
13959 object | result of function object_t::size()
13960 array | result of function array_t::size()
13961
13962 @liveexample{The following code calls `size()` on the different value
13963 types.,size}
13964
13965 @complexity Constant, as long as @ref array_t and @ref object_t satisfy
13966 the Container concept; that is, their size() functions have constant
13967 complexity.
13968
13969 @iterators No changes.
13970
13971 @exceptionsafety No-throw guarantee: this function never throws exceptions.
13972
13973 @note This function does not return the length of a string stored as JSON
13974 value - it returns the number of elements in the JSON value which is 1 in
13975 the case of a string.
13976
13977 @requirement This function helps `basic_json` satisfying the
13978 [Container](http://en.cppreference.com/w/cpp/concept/Container)
13979 requirements:
13980 - The complexity is constant.
13981 - Has the semantics of `std::distance(begin(), end())`.
13982
13983 @sa @ref empty() -- checks whether the container is empty
13984 @sa @ref max_size() -- returns the maximal number of elements
13985
13986 @since version 1.0.0
13987 */
size() const13988 size_type size() const noexcept
13989 {
13990 switch (m_type)
13991 {
13992 case value_t::null:
13993 {
13994 // null values are empty
13995 return 0;
13996 }
13997
13998 case value_t::array:
13999 {
14000 // delegate call to array_t::size()
14001 return m_value.array->size();
14002 }
14003
14004 case value_t::object:
14005 {
14006 // delegate call to object_t::size()
14007 return m_value.object->size();
14008 }
14009
14010 default:
14011 {
14012 // all other types have size 1
14013 return 1;
14014 }
14015 }
14016 }
14017
14018 /*!
14019 @brief returns the maximum possible number of elements
14020
14021 Returns the maximum number of elements a JSON value is able to hold due to
14022 system or library implementation limitations, i.e. `std::distance(begin(),
14023 end())` for the JSON value.
14024
14025 @return The return value depends on the different types and is
14026 defined as follows:
14027 Value type | return value
14028 ----------- | -------------
14029 null | `0` (same as `size()`)
14030 boolean | `1` (same as `size()`)
14031 string | `1` (same as `size()`)
14032 number | `1` (same as `size()`)
14033 object | result of function `object_t::max_size()`
14034 array | result of function `array_t::max_size()`
14035
14036 @liveexample{The following code calls `max_size()` on the different value
14037 types. Note the output is implementation specific.,max_size}
14038
14039 @complexity Constant, as long as @ref array_t and @ref object_t satisfy
14040 the Container concept; that is, their `max_size()` functions have constant
14041 complexity.
14042
14043 @iterators No changes.
14044
14045 @exceptionsafety No-throw guarantee: this function never throws exceptions.
14046
14047 @requirement This function helps `basic_json` satisfying the
14048 [Container](http://en.cppreference.com/w/cpp/concept/Container)
14049 requirements:
14050 - The complexity is constant.
14051 - Has the semantics of returning `b.size()` where `b` is the largest
14052 possible JSON value.
14053
14054 @sa @ref size() -- returns the number of elements
14055
14056 @since version 1.0.0
14057 */
max_size() const14058 size_type max_size() const noexcept
14059 {
14060 switch (m_type)
14061 {
14062 case value_t::array:
14063 {
14064 // delegate call to array_t::max_size()
14065 return m_value.array->max_size();
14066 }
14067
14068 case value_t::object:
14069 {
14070 // delegate call to object_t::max_size()
14071 return m_value.object->max_size();
14072 }
14073
14074 default:
14075 {
14076 // all other types have max_size() == size()
14077 return size();
14078 }
14079 }
14080 }
14081
14082 /// @}
14083
14084
14085 ///////////////
14086 // modifiers //
14087 ///////////////
14088
14089 /// @name modifiers
14090 /// @{
14091
14092 /*!
14093 @brief clears the contents
14094
14095 Clears the content of a JSON value and resets it to the default value as
14096 if @ref basic_json(value_t) would have been called with the current value
14097 type from @ref type():
14098
14099 Value type | initial value
14100 ----------- | -------------
14101 null | `null`
14102 boolean | `false`
14103 string | `""`
14104 number | `0`
14105 object | `{}`
14106 array | `[]`
14107
14108 @post Has the same effect as calling
14109 @code {.cpp}
14110 *this = basic_json(type());
14111 @endcode
14112
14113 @liveexample{The example below shows the effect of `clear()` to different
14114 JSON types.,clear}
14115
14116 @complexity Linear in the size of the JSON value.
14117
14118 @iterators All iterators, pointers and references related to this container
14119 are invalidated.
14120
14121 @exceptionsafety No-throw guarantee: this function never throws exceptions.
14122
14123 @sa @ref basic_json(value_t) -- constructor that creates an object with the
14124 same value than calling `clear()`
14125
14126 @since version 1.0.0
14127 */
clear()14128 void clear() noexcept
14129 {
14130 switch (m_type)
14131 {
14132 case value_t::number_integer:
14133 {
14134 m_value.number_integer = 0;
14135 break;
14136 }
14137
14138 case value_t::number_unsigned:
14139 {
14140 m_value.number_unsigned = 0;
14141 break;
14142 }
14143
14144 case value_t::number_float:
14145 {
14146 m_value.number_float = 0.0;
14147 break;
14148 }
14149
14150 case value_t::boolean:
14151 {
14152 m_value.boolean = false;
14153 break;
14154 }
14155
14156 case value_t::string:
14157 {
14158 m_value.string->clear();
14159 break;
14160 }
14161
14162 case value_t::array:
14163 {
14164 m_value.array->clear();
14165 break;
14166 }
14167
14168 case value_t::object:
14169 {
14170 m_value.object->clear();
14171 break;
14172 }
14173
14174 default:
14175 break;
14176 }
14177 }
14178
14179 /*!
14180 @brief add an object to an array
14181
14182 Appends the given element @a val to the end of the JSON value. If the
14183 function is called on a JSON null value, an empty array is created before
14184 appending @a val.
14185
14186 @param[in] val the value to add to the JSON array
14187
14188 @throw type_error.308 when called on a type other than JSON array or
14189 null; example: `"cannot use push_back() with number"`
14190
14191 @complexity Amortized constant.
14192
14193 @liveexample{The example shows how `push_back()` and `+=` can be used to
14194 add elements to a JSON array. Note how the `null` value was silently
14195 converted to a JSON array.,push_back}
14196
14197 @since version 1.0.0
14198 */
push_back(basic_json && val)14199 void push_back(basic_json&& val)
14200 {
14201 // push_back only works for null objects or arrays
14202 if (JSON_UNLIKELY(not(is_null() or is_array())))
14203 {
14204 JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
14205 }
14206
14207 // transform null object into an array
14208 if (is_null())
14209 {
14210 m_type = value_t::array;
14211 m_value = value_t::array;
14212 assert_invariant();
14213 }
14214
14215 // add element to array (move semantics)
14216 m_value.array->push_back(std::move(val));
14217 // invalidate object
14218 val.m_type = value_t::null;
14219 }
14220
14221 /*!
14222 @brief add an object to an array
14223 @copydoc push_back(basic_json&&)
14224 */
operator +=(basic_json && val)14225 reference operator+=(basic_json&& val)
14226 {
14227 push_back(std::move(val));
14228 return *this;
14229 }
14230
14231 /*!
14232 @brief add an object to an array
14233 @copydoc push_back(basic_json&&)
14234 */
push_back(const basic_json & val)14235 void push_back(const basic_json& val)
14236 {
14237 // push_back only works for null objects or arrays
14238 if (JSON_UNLIKELY(not(is_null() or is_array())))
14239 {
14240 JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
14241 }
14242
14243 // transform null object into an array
14244 if (is_null())
14245 {
14246 m_type = value_t::array;
14247 m_value = value_t::array;
14248 assert_invariant();
14249 }
14250
14251 // add element to array
14252 m_value.array->push_back(val);
14253 }
14254
14255 /*!
14256 @brief add an object to an array
14257 @copydoc push_back(basic_json&&)
14258 */
operator +=(const basic_json & val)14259 reference operator+=(const basic_json& val)
14260 {
14261 push_back(val);
14262 return *this;
14263 }
14264
14265 /*!
14266 @brief add an object to an object
14267
14268 Inserts the given element @a val to the JSON object. If the function is
14269 called on a JSON null value, an empty object is created before inserting
14270 @a val.
14271
14272 @param[in] val the value to add to the JSON object
14273
14274 @throw type_error.308 when called on a type other than JSON object or
14275 null; example: `"cannot use push_back() with number"`
14276
14277 @complexity Logarithmic in the size of the container, O(log(`size()`)).
14278
14279 @liveexample{The example shows how `push_back()` and `+=` can be used to
14280 add elements to a JSON object. Note how the `null` value was silently
14281 converted to a JSON object.,push_back__object_t__value}
14282
14283 @since version 1.0.0
14284 */
push_back(const typename object_t::value_type & val)14285 void push_back(const typename object_t::value_type& val)
14286 {
14287 // push_back only works for null objects or objects
14288 if (JSON_UNLIKELY(not(is_null() or is_object())))
14289 {
14290 JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
14291 }
14292
14293 // transform null object into an object
14294 if (is_null())
14295 {
14296 m_type = value_t::object;
14297 m_value = value_t::object;
14298 assert_invariant();
14299 }
14300
14301 // add element to array
14302 m_value.object->insert(val);
14303 }
14304
14305 /*!
14306 @brief add an object to an object
14307 @copydoc push_back(const typename object_t::value_type&)
14308 */
operator +=(const typename object_t::value_type & val)14309 reference operator+=(const typename object_t::value_type& val)
14310 {
14311 push_back(val);
14312 return *this;
14313 }
14314
14315 /*!
14316 @brief add an object to an object
14317
14318 This function allows to use `push_back` with an initializer list. In case
14319
14320 1. the current value is an object,
14321 2. the initializer list @a init contains only two elements, and
14322 3. the first element of @a init is a string,
14323
14324 @a init is converted into an object element and added using
14325 @ref push_back(const typename object_t::value_type&). Otherwise, @a init
14326 is converted to a JSON value and added using @ref push_back(basic_json&&).
14327
14328 @param[in] init an initializer list
14329
14330 @complexity Linear in the size of the initializer list @a init.
14331
14332 @note This function is required to resolve an ambiguous overload error,
14333 because pairs like `{"key", "value"}` can be both interpreted as
14334 `object_t::value_type` or `std::initializer_list<basic_json>`, see
14335 https://github.com/nlohmann/json/issues/235 for more information.
14336
14337 @liveexample{The example shows how initializer lists are treated as
14338 objects when possible.,push_back__initializer_list}
14339 */
push_back(initializer_list_t init)14340 void push_back(initializer_list_t init)
14341 {
14342 if (is_object() and init.size() == 2 and (*init.begin())->is_string())
14343 {
14344 basic_json&& key = init.begin()->moved_or_copied();
14345 push_back(typename object_t::value_type(
14346 std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
14347 }
14348 else
14349 {
14350 push_back(basic_json(init));
14351 }
14352 }
14353
14354 /*!
14355 @brief add an object to an object
14356 @copydoc push_back(initializer_list_t)
14357 */
operator +=(initializer_list_t init)14358 reference operator+=(initializer_list_t init)
14359 {
14360 push_back(init);
14361 return *this;
14362 }
14363
14364 /*!
14365 @brief add an object to an array
14366
14367 Creates a JSON value from the passed parameters @a args to the end of the
14368 JSON value. If the function is called on a JSON null value, an empty array
14369 is created before appending the value created from @a args.
14370
14371 @param[in] args arguments to forward to a constructor of @ref basic_json
14372 @tparam Args compatible types to create a @ref basic_json object
14373
14374 @throw type_error.311 when called on a type other than JSON array or
14375 null; example: `"cannot use emplace_back() with number"`
14376
14377 @complexity Amortized constant.
14378
14379 @liveexample{The example shows how `push_back()` can be used to add
14380 elements to a JSON array. Note how the `null` value was silently converted
14381 to a JSON array.,emplace_back}
14382
14383 @since version 2.0.8
14384 */
14385 template<class... Args>
emplace_back(Args &&...args)14386 void emplace_back(Args&& ... args)
14387 {
14388 // emplace_back only works for null objects or arrays
14389 if (JSON_UNLIKELY(not(is_null() or is_array())))
14390 {
14391 JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
14392 }
14393
14394 // transform null object into an array
14395 if (is_null())
14396 {
14397 m_type = value_t::array;
14398 m_value = value_t::array;
14399 assert_invariant();
14400 }
14401
14402 // add element to array (perfect forwarding)
14403 m_value.array->emplace_back(std::forward<Args>(args)...);
14404 }
14405
14406 /*!
14407 @brief add an object to an object if key does not exist
14408
14409 Inserts a new element into a JSON object constructed in-place with the
14410 given @a args if there is no element with the key in the container. If the
14411 function is called on a JSON null value, an empty object is created before
14412 appending the value created from @a args.
14413
14414 @param[in] args arguments to forward to a constructor of @ref basic_json
14415 @tparam Args compatible types to create a @ref basic_json object
14416
14417 @return a pair consisting of an iterator to the inserted element, or the
14418 already-existing element if no insertion happened, and a bool
14419 denoting whether the insertion took place.
14420
14421 @throw type_error.311 when called on a type other than JSON object or
14422 null; example: `"cannot use emplace() with number"`
14423
14424 @complexity Logarithmic in the size of the container, O(log(`size()`)).
14425
14426 @liveexample{The example shows how `emplace()` can be used to add elements
14427 to a JSON object. Note how the `null` value was silently converted to a
14428 JSON object. Further note how no value is added if there was already one
14429 value stored with the same key.,emplace}
14430
14431 @since version 2.0.8
14432 */
14433 template<class... Args>
emplace(Args &&...args)14434 std::pair<iterator, bool> emplace(Args&& ... args)
14435 {
14436 // emplace only works for null objects or arrays
14437 if (JSON_UNLIKELY(not(is_null() or is_object())))
14438 {
14439 JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
14440 }
14441
14442 // transform null object into an object
14443 if (is_null())
14444 {
14445 m_type = value_t::object;
14446 m_value = value_t::object;
14447 assert_invariant();
14448 }
14449
14450 // add element to array (perfect forwarding)
14451 auto res = m_value.object->emplace(std::forward<Args>(args)...);
14452 // create result iterator and set iterator to the result of emplace
14453 auto it = begin();
14454 it.m_it.object_iterator = res.first;
14455
14456 // return pair of iterator and boolean
14457 return {it, res.second};
14458 }
14459
14460 /*!
14461 @brief inserts element
14462
14463 Inserts element @a val before iterator @a pos.
14464
14465 @param[in] pos iterator before which the content will be inserted; may be
14466 the end() iterator
14467 @param[in] val element to insert
14468 @return iterator pointing to the inserted @a val.
14469
14470 @throw type_error.309 if called on JSON values other than arrays;
14471 example: `"cannot use insert() with string"`
14472 @throw invalid_iterator.202 if @a pos is not an iterator of *this;
14473 example: `"iterator does not fit current value"`
14474
14475 @complexity Constant plus linear in the distance between @a pos and end of
14476 the container.
14477
14478 @liveexample{The example shows how `insert()` is used.,insert}
14479
14480 @since version 1.0.0
14481 */
insert(const_iterator pos,const basic_json & val)14482 iterator insert(const_iterator pos, const basic_json& val)
14483 {
14484 // insert only works for arrays
14485 if (JSON_LIKELY(is_array()))
14486 {
14487 // check if iterator pos fits to this JSON value
14488 if (JSON_UNLIKELY(pos.m_object != this))
14489 {
14490 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
14491 }
14492
14493 // insert to array and return iterator
14494 iterator result(this);
14495 result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
14496 return result;
14497 }
14498
14499 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
14500 }
14501
14502 /*!
14503 @brief inserts element
14504 @copydoc insert(const_iterator, const basic_json&)
14505 */
insert(const_iterator pos,basic_json && val)14506 iterator insert(const_iterator pos, basic_json&& val)
14507 {
14508 return insert(pos, val);
14509 }
14510
14511 /*!
14512 @brief inserts elements
14513
14514 Inserts @a cnt copies of @a val before iterator @a pos.
14515
14516 @param[in] pos iterator before which the content will be inserted; may be
14517 the end() iterator
14518 @param[in] cnt number of copies of @a val to insert
14519 @param[in] val element to insert
14520 @return iterator pointing to the first element inserted, or @a pos if
14521 `cnt==0`
14522
14523 @throw type_error.309 if called on JSON values other than arrays; example:
14524 `"cannot use insert() with string"`
14525 @throw invalid_iterator.202 if @a pos is not an iterator of *this;
14526 example: `"iterator does not fit current value"`
14527
14528 @complexity Linear in @a cnt plus linear in the distance between @a pos
14529 and end of the container.
14530
14531 @liveexample{The example shows how `insert()` is used.,insert__count}
14532
14533 @since version 1.0.0
14534 */
insert(const_iterator pos,size_type cnt,const basic_json & val)14535 iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
14536 {
14537 // insert only works for arrays
14538 if (JSON_LIKELY(is_array()))
14539 {
14540 // check if iterator pos fits to this JSON value
14541 if (JSON_UNLIKELY(pos.m_object != this))
14542 {
14543 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
14544 }
14545
14546 // insert to array and return iterator
14547 iterator result(this);
14548 result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
14549 return result;
14550 }
14551
14552 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
14553 }
14554
14555 /*!
14556 @brief inserts elements
14557
14558 Inserts elements from range `[first, last)` before iterator @a pos.
14559
14560 @param[in] pos iterator before which the content will be inserted; may be
14561 the end() iterator
14562 @param[in] first begin of the range of elements to insert
14563 @param[in] last end of the range of elements to insert
14564
14565 @throw type_error.309 if called on JSON values other than arrays; example:
14566 `"cannot use insert() with string"`
14567 @throw invalid_iterator.202 if @a pos is not an iterator of *this;
14568 example: `"iterator does not fit current value"`
14569 @throw invalid_iterator.210 if @a first and @a last do not belong to the
14570 same JSON value; example: `"iterators do not fit"`
14571 @throw invalid_iterator.211 if @a first or @a last are iterators into
14572 container for which insert is called; example: `"passed iterators may not
14573 belong to container"`
14574
14575 @return iterator pointing to the first element inserted, or @a pos if
14576 `first==last`
14577
14578 @complexity Linear in `std::distance(first, last)` plus linear in the
14579 distance between @a pos and end of the container.
14580
14581 @liveexample{The example shows how `insert()` is used.,insert__range}
14582
14583 @since version 1.0.0
14584 */
insert(const_iterator pos,const_iterator first,const_iterator last)14585 iterator insert(const_iterator pos, const_iterator first, const_iterator last)
14586 {
14587 // insert only works for arrays
14588 if (JSON_UNLIKELY(not is_array()))
14589 {
14590 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
14591 }
14592
14593 // check if iterator pos fits to this JSON value
14594 if (JSON_UNLIKELY(pos.m_object != this))
14595 {
14596 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
14597 }
14598
14599 // check if range iterators belong to the same JSON object
14600 if (JSON_UNLIKELY(first.m_object != last.m_object))
14601 {
14602 JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
14603 }
14604
14605 if (JSON_UNLIKELY(first.m_object == this))
14606 {
14607 JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
14608 }
14609
14610 // insert to array and return iterator
14611 iterator result(this);
14612 result.m_it.array_iterator = m_value.array->insert(
14613 pos.m_it.array_iterator,
14614 first.m_it.array_iterator,
14615 last.m_it.array_iterator);
14616 return result;
14617 }
14618
14619 /*!
14620 @brief inserts elements
14621
14622 Inserts elements from initializer list @a ilist before iterator @a pos.
14623
14624 @param[in] pos iterator before which the content will be inserted; may be
14625 the end() iterator
14626 @param[in] ilist initializer list to insert the values from
14627
14628 @throw type_error.309 if called on JSON values other than arrays; example:
14629 `"cannot use insert() with string"`
14630 @throw invalid_iterator.202 if @a pos is not an iterator of *this;
14631 example: `"iterator does not fit current value"`
14632
14633 @return iterator pointing to the first element inserted, or @a pos if
14634 `ilist` is empty
14635
14636 @complexity Linear in `ilist.size()` plus linear in the distance between
14637 @a pos and end of the container.
14638
14639 @liveexample{The example shows how `insert()` is used.,insert__ilist}
14640
14641 @since version 1.0.0
14642 */
insert(const_iterator pos,initializer_list_t ilist)14643 iterator insert(const_iterator pos, initializer_list_t ilist)
14644 {
14645 // insert only works for arrays
14646 if (JSON_UNLIKELY(not is_array()))
14647 {
14648 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
14649 }
14650
14651 // check if iterator pos fits to this JSON value
14652 if (JSON_UNLIKELY(pos.m_object != this))
14653 {
14654 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
14655 }
14656
14657 // insert to array and return iterator
14658 iterator result(this);
14659 result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end());
14660 return result;
14661 }
14662
14663 /*!
14664 @brief inserts elements
14665
14666 Inserts elements from range `[first, last)`.
14667
14668 @param[in] first begin of the range of elements to insert
14669 @param[in] last end of the range of elements to insert
14670
14671 @throw type_error.309 if called on JSON values other than objects; example:
14672 `"cannot use insert() with string"`
14673 @throw invalid_iterator.202 if iterator @a first or @a last does does not
14674 point to an object; example: `"iterators first and last must point to
14675 objects"`
14676 @throw invalid_iterator.210 if @a first and @a last do not belong to the
14677 same JSON value; example: `"iterators do not fit"`
14678
14679 @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
14680 of elements to insert.
14681
14682 @liveexample{The example shows how `insert()` is used.,insert__range_object}
14683
14684 @since version 3.0.0
14685 */
insert(const_iterator first,const_iterator last)14686 void insert(const_iterator first, const_iterator last)
14687 {
14688 // insert only works for objects
14689 if (JSON_UNLIKELY(not is_object()))
14690 {
14691 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
14692 }
14693
14694 // check if range iterators belong to the same JSON object
14695 if (JSON_UNLIKELY(first.m_object != last.m_object))
14696 {
14697 JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
14698 }
14699
14700 // passed iterators must belong to objects
14701 if (JSON_UNLIKELY(not first.m_object->is_object()))
14702 {
14703 JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
14704 }
14705
14706 m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
14707 }
14708
14709 /*!
14710 @brief updates a JSON object from another object, overwriting existing keys
14711
14712 Inserts all values from JSON object @a j and overwrites existing keys.
14713
14714 @param[in] j JSON object to read values from
14715
14716 @throw type_error.312 if called on JSON values other than objects; example:
14717 `"cannot use update() with string"`
14718
14719 @complexity O(N*log(size() + N)), where N is the number of elements to
14720 insert.
14721
14722 @liveexample{The example shows how `update()` is used.,update}
14723
14724 @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
14725
14726 @since version 3.0.0
14727 */
update(const_reference j)14728 void update(const_reference j)
14729 {
14730 // implicitly convert null value to an empty object
14731 if (is_null())
14732 {
14733 m_type = value_t::object;
14734 m_value.object = create<object_t>();
14735 assert_invariant();
14736 }
14737
14738 if (JSON_UNLIKELY(not is_object()))
14739 {
14740 JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
14741 }
14742 if (JSON_UNLIKELY(not j.is_object()))
14743 {
14744 JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
14745 }
14746
14747 for (auto it = j.cbegin(); it != j.cend(); ++it)
14748 {
14749 m_value.object->operator[](it.key()) = it.value();
14750 }
14751 }
14752
14753 /*!
14754 @brief updates a JSON object from another object, overwriting existing keys
14755
14756 Inserts all values from from range `[first, last)` and overwrites existing
14757 keys.
14758
14759 @param[in] first begin of the range of elements to insert
14760 @param[in] last end of the range of elements to insert
14761
14762 @throw type_error.312 if called on JSON values other than objects; example:
14763 `"cannot use update() with string"`
14764 @throw invalid_iterator.202 if iterator @a first or @a last does does not
14765 point to an object; example: `"iterators first and last must point to
14766 objects"`
14767 @throw invalid_iterator.210 if @a first and @a last do not belong to the
14768 same JSON value; example: `"iterators do not fit"`
14769
14770 @complexity O(N*log(size() + N)), where N is the number of elements to
14771 insert.
14772
14773 @liveexample{The example shows how `update()` is used__range.,update}
14774
14775 @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
14776
14777 @since version 3.0.0
14778 */
update(const_iterator first,const_iterator last)14779 void update(const_iterator first, const_iterator last)
14780 {
14781 // implicitly convert null value to an empty object
14782 if (is_null())
14783 {
14784 m_type = value_t::object;
14785 m_value.object = create<object_t>();
14786 assert_invariant();
14787 }
14788
14789 if (JSON_UNLIKELY(not is_object()))
14790 {
14791 JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
14792 }
14793
14794 // check if range iterators belong to the same JSON object
14795 if (JSON_UNLIKELY(first.m_object != last.m_object))
14796 {
14797 JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
14798 }
14799
14800 // passed iterators must belong to objects
14801 if (JSON_UNLIKELY(not first.m_object->is_object()
14802 or not first.m_object->is_object()))
14803 {
14804 JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
14805 }
14806
14807 for (auto it = first; it != last; ++it)
14808 {
14809 m_value.object->operator[](it.key()) = it.value();
14810 }
14811 }
14812
14813 /*!
14814 @brief exchanges the values
14815
14816 Exchanges the contents of the JSON value with those of @a other. Does not
14817 invoke any move, copy, or swap operations on individual elements. All
14818 iterators and references remain valid. The past-the-end iterator is
14819 invalidated.
14820
14821 @param[in,out] other JSON value to exchange the contents with
14822
14823 @complexity Constant.
14824
14825 @liveexample{The example below shows how JSON values can be swapped with
14826 `swap()`.,swap__reference}
14827
14828 @since version 1.0.0
14829 */
swap(reference other)14830 void swap(reference other) noexcept (
14831 std::is_nothrow_move_constructible<value_t>::value and
14832 std::is_nothrow_move_assignable<value_t>::value and
14833 std::is_nothrow_move_constructible<json_value>::value and
14834 std::is_nothrow_move_assignable<json_value>::value
14835 )
14836 {
14837 std::swap(m_type, other.m_type);
14838 std::swap(m_value, other.m_value);
14839 assert_invariant();
14840 }
14841
14842 /*!
14843 @brief exchanges the values
14844
14845 Exchanges the contents of a JSON array with those of @a other. Does not
14846 invoke any move, copy, or swap operations on individual elements. All
14847 iterators and references remain valid. The past-the-end iterator is
14848 invalidated.
14849
14850 @param[in,out] other array to exchange the contents with
14851
14852 @throw type_error.310 when JSON value is not an array; example: `"cannot
14853 use swap() with string"`
14854
14855 @complexity Constant.
14856
14857 @liveexample{The example below shows how arrays can be swapped with
14858 `swap()`.,swap__array_t}
14859
14860 @since version 1.0.0
14861 */
swap(array_t & other)14862 void swap(array_t& other)
14863 {
14864 // swap only works for arrays
14865 if (JSON_LIKELY(is_array()))
14866 {
14867 std::swap(*(m_value.array), other);
14868 }
14869 else
14870 {
14871 JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
14872 }
14873 }
14874
14875 /*!
14876 @brief exchanges the values
14877
14878 Exchanges the contents of a JSON object with those of @a other. Does not
14879 invoke any move, copy, or swap operations on individual elements. All
14880 iterators and references remain valid. The past-the-end iterator is
14881 invalidated.
14882
14883 @param[in,out] other object to exchange the contents with
14884
14885 @throw type_error.310 when JSON value is not an object; example:
14886 `"cannot use swap() with string"`
14887
14888 @complexity Constant.
14889
14890 @liveexample{The example below shows how objects can be swapped with
14891 `swap()`.,swap__object_t}
14892
14893 @since version 1.0.0
14894 */
swap(object_t & other)14895 void swap(object_t& other)
14896 {
14897 // swap only works for objects
14898 if (JSON_LIKELY(is_object()))
14899 {
14900 std::swap(*(m_value.object), other);
14901 }
14902 else
14903 {
14904 JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
14905 }
14906 }
14907
14908 /*!
14909 @brief exchanges the values
14910
14911 Exchanges the contents of a JSON string with those of @a other. Does not
14912 invoke any move, copy, or swap operations on individual elements. All
14913 iterators and references remain valid. The past-the-end iterator is
14914 invalidated.
14915
14916 @param[in,out] other string to exchange the contents with
14917
14918 @throw type_error.310 when JSON value is not a string; example: `"cannot
14919 use swap() with boolean"`
14920
14921 @complexity Constant.
14922
14923 @liveexample{The example below shows how strings can be swapped with
14924 `swap()`.,swap__string_t}
14925
14926 @since version 1.0.0
14927 */
swap(string_t & other)14928 void swap(string_t& other)
14929 {
14930 // swap only works for strings
14931 if (JSON_LIKELY(is_string()))
14932 {
14933 std::swap(*(m_value.string), other);
14934 }
14935 else
14936 {
14937 JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
14938 }
14939 }
14940
14941 /// @}
14942
14943 public:
14944 //////////////////////////////////////////
14945 // lexicographical comparison operators //
14946 //////////////////////////////////////////
14947
14948 /// @name lexicographical comparison operators
14949 /// @{
14950
14951 /*!
14952 @brief comparison: equal
14953
14954 Compares two JSON values for equality according to the following rules:
14955 - Two JSON values are equal if (1) they are from the same type and (2)
14956 their stored values are the same according to their respective
14957 `operator==`.
14958 - Integer and floating-point numbers are automatically converted before
14959 comparison. Note than two NaN values are always treated as unequal.
14960 - Two JSON null values are equal.
14961
14962 @note Floating-point inside JSON values numbers are compared with
14963 `json::number_float_t::operator==` which is `double::operator==` by
14964 default. To compare floating-point while respecting an epsilon, an alternative
14965 [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
14966 could be used, for instance
14967 @code {.cpp}
14968 template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
14969 inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
14970 {
14971 return std::abs(a - b) <= epsilon;
14972 }
14973 @endcode
14974
14975 @note NaN values never compare equal to themselves or to other NaN values.
14976
14977 @param[in] lhs first JSON value to consider
14978 @param[in] rhs second JSON value to consider
14979 @return whether the values @a lhs and @a rhs are equal
14980
14981 @exceptionsafety No-throw guarantee: this function never throws exceptions.
14982
14983 @complexity Linear.
14984
14985 @liveexample{The example demonstrates comparing several JSON
14986 types.,operator__equal}
14987
14988 @since version 1.0.0
14989 */
operator ==(const_reference lhs,const_reference rhs)14990 friend bool operator==(const_reference lhs, const_reference rhs) noexcept
14991 {
14992 const auto lhs_type = lhs.type();
14993 const auto rhs_type = rhs.type();
14994
14995 if (lhs_type == rhs_type)
14996 {
14997 switch (lhs_type)
14998 {
14999 case value_t::array:
15000 return (*lhs.m_value.array == *rhs.m_value.array);
15001
15002 case value_t::object:
15003 return (*lhs.m_value.object == *rhs.m_value.object);
15004
15005 case value_t::null:
15006 return true;
15007
15008 case value_t::string:
15009 return (*lhs.m_value.string == *rhs.m_value.string);
15010
15011 case value_t::boolean:
15012 return (lhs.m_value.boolean == rhs.m_value.boolean);
15013
15014 case value_t::number_integer:
15015 return (lhs.m_value.number_integer == rhs.m_value.number_integer);
15016
15017 case value_t::number_unsigned:
15018 return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned);
15019
15020 case value_t::number_float:
15021 return (lhs.m_value.number_float == rhs.m_value.number_float);
15022
15023 default:
15024 return false;
15025 }
15026 }
15027 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
15028 {
15029 return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float);
15030 }
15031 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
15032 {
15033 return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer));
15034 }
15035 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
15036 {
15037 return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float);
15038 }
15039 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
15040 {
15041 return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned));
15042 }
15043 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
15044 {
15045 return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer);
15046 }
15047 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
15048 {
15049 return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned));
15050 }
15051
15052 return false;
15053 }
15054
15055 /*!
15056 @brief comparison: equal
15057 @copydoc operator==(const_reference, const_reference)
15058 */
15059 template<typename ScalarType, typename std::enable_if<
15060 std::is_scalar<ScalarType>::value, int>::type = 0>
operator ==(const_reference lhs,const ScalarType rhs)15061 friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
15062 {
15063 return (lhs == basic_json(rhs));
15064 }
15065
15066 /*!
15067 @brief comparison: equal
15068 @copydoc operator==(const_reference, const_reference)
15069 */
15070 template<typename ScalarType, typename std::enable_if<
15071 std::is_scalar<ScalarType>::value, int>::type = 0>
operator ==(const ScalarType lhs,const_reference rhs)15072 friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
15073 {
15074 return (basic_json(lhs) == rhs);
15075 }
15076
15077 /*!
15078 @brief comparison: not equal
15079
15080 Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
15081
15082 @param[in] lhs first JSON value to consider
15083 @param[in] rhs second JSON value to consider
15084 @return whether the values @a lhs and @a rhs are not equal
15085
15086 @complexity Linear.
15087
15088 @exceptionsafety No-throw guarantee: this function never throws exceptions.
15089
15090 @liveexample{The example demonstrates comparing several JSON
15091 types.,operator__notequal}
15092
15093 @since version 1.0.0
15094 */
operator !=(const_reference lhs,const_reference rhs)15095 friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
15096 {
15097 return not (lhs == rhs);
15098 }
15099
15100 /*!
15101 @brief comparison: not equal
15102 @copydoc operator!=(const_reference, const_reference)
15103 */
15104 template<typename ScalarType, typename std::enable_if<
15105 std::is_scalar<ScalarType>::value, int>::type = 0>
operator !=(const_reference lhs,const ScalarType rhs)15106 friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
15107 {
15108 return (lhs != basic_json(rhs));
15109 }
15110
15111 /*!
15112 @brief comparison: not equal
15113 @copydoc operator!=(const_reference, const_reference)
15114 */
15115 template<typename ScalarType, typename std::enable_if<
15116 std::is_scalar<ScalarType>::value, int>::type = 0>
operator !=(const ScalarType lhs,const_reference rhs)15117 friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
15118 {
15119 return (basic_json(lhs) != rhs);
15120 }
15121
15122 /*!
15123 @brief comparison: less than
15124
15125 Compares whether one JSON value @a lhs is less than another JSON value @a
15126 rhs according to the following rules:
15127 - If @a lhs and @a rhs have the same type, the values are compared using
15128 the default `<` operator.
15129 - Integer and floating-point numbers are automatically converted before
15130 comparison
15131 - In case @a lhs and @a rhs have different types, the values are ignored
15132 and the order of the types is considered, see
15133 @ref operator<(const value_t, const value_t).
15134
15135 @param[in] lhs first JSON value to consider
15136 @param[in] rhs second JSON value to consider
15137 @return whether @a lhs is less than @a rhs
15138
15139 @complexity Linear.
15140
15141 @exceptionsafety No-throw guarantee: this function never throws exceptions.
15142
15143 @liveexample{The example demonstrates comparing several JSON
15144 types.,operator__less}
15145
15146 @since version 1.0.0
15147 */
operator <(const_reference lhs,const_reference rhs)15148 friend bool operator<(const_reference lhs, const_reference rhs) noexcept
15149 {
15150 const auto lhs_type = lhs.type();
15151 const auto rhs_type = rhs.type();
15152
15153 if (lhs_type == rhs_type)
15154 {
15155 switch (lhs_type)
15156 {
15157 case value_t::array:
15158 return (*lhs.m_value.array) < (*rhs.m_value.array);
15159
15160 case value_t::object:
15161 return *lhs.m_value.object < *rhs.m_value.object;
15162
15163 case value_t::null:
15164 return false;
15165
15166 case value_t::string:
15167 return *lhs.m_value.string < *rhs.m_value.string;
15168
15169 case value_t::boolean:
15170 return lhs.m_value.boolean < rhs.m_value.boolean;
15171
15172 case value_t::number_integer:
15173 return lhs.m_value.number_integer < rhs.m_value.number_integer;
15174
15175 case value_t::number_unsigned:
15176 return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
15177
15178 case value_t::number_float:
15179 return lhs.m_value.number_float < rhs.m_value.number_float;
15180
15181 default:
15182 return false;
15183 }
15184 }
15185 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
15186 {
15187 return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
15188 }
15189 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
15190 {
15191 return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
15192 }
15193 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
15194 {
15195 return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
15196 }
15197 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
15198 {
15199 return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
15200 }
15201 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
15202 {
15203 return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
15204 }
15205 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
15206 {
15207 return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
15208 }
15209
15210 // We only reach this line if we cannot compare values. In that case,
15211 // we compare types. Note we have to call the operator explicitly,
15212 // because MSVC has problems otherwise.
15213 return operator<(lhs_type, rhs_type);
15214 }
15215
15216 /*!
15217 @brief comparison: less than
15218 @copydoc operator<(const_reference, const_reference)
15219 */
15220 template<typename ScalarType, typename std::enable_if<
15221 std::is_scalar<ScalarType>::value, int>::type = 0>
operator <(const_reference lhs,const ScalarType rhs)15222 friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
15223 {
15224 return (lhs < basic_json(rhs));
15225 }
15226
15227 /*!
15228 @brief comparison: less than
15229 @copydoc operator<(const_reference, const_reference)
15230 */
15231 template<typename ScalarType, typename std::enable_if<
15232 std::is_scalar<ScalarType>::value, int>::type = 0>
operator <(const ScalarType lhs,const_reference rhs)15233 friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
15234 {
15235 return (basic_json(lhs) < rhs);
15236 }
15237
15238 /*!
15239 @brief comparison: less than or equal
15240
15241 Compares whether one JSON value @a lhs is less than or equal to another
15242 JSON value by calculating `not (rhs < lhs)`.
15243
15244 @param[in] lhs first JSON value to consider
15245 @param[in] rhs second JSON value to consider
15246 @return whether @a lhs is less than or equal to @a rhs
15247
15248 @complexity Linear.
15249
15250 @exceptionsafety No-throw guarantee: this function never throws exceptions.
15251
15252 @liveexample{The example demonstrates comparing several JSON
15253 types.,operator__greater}
15254
15255 @since version 1.0.0
15256 */
operator <=(const_reference lhs,const_reference rhs)15257 friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
15258 {
15259 return not (rhs < lhs);
15260 }
15261
15262 /*!
15263 @brief comparison: less than or equal
15264 @copydoc operator<=(const_reference, const_reference)
15265 */
15266 template<typename ScalarType, typename std::enable_if<
15267 std::is_scalar<ScalarType>::value, int>::type = 0>
operator <=(const_reference lhs,const ScalarType rhs)15268 friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
15269 {
15270 return (lhs <= basic_json(rhs));
15271 }
15272
15273 /*!
15274 @brief comparison: less than or equal
15275 @copydoc operator<=(const_reference, const_reference)
15276 */
15277 template<typename ScalarType, typename std::enable_if<
15278 std::is_scalar<ScalarType>::value, int>::type = 0>
operator <=(const ScalarType lhs,const_reference rhs)15279 friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
15280 {
15281 return (basic_json(lhs) <= rhs);
15282 }
15283
15284 /*!
15285 @brief comparison: greater than
15286
15287 Compares whether one JSON value @a lhs is greater than another
15288 JSON value by calculating `not (lhs <= rhs)`.
15289
15290 @param[in] lhs first JSON value to consider
15291 @param[in] rhs second JSON value to consider
15292 @return whether @a lhs is greater than to @a rhs
15293
15294 @complexity Linear.
15295
15296 @exceptionsafety No-throw guarantee: this function never throws exceptions.
15297
15298 @liveexample{The example demonstrates comparing several JSON
15299 types.,operator__lessequal}
15300
15301 @since version 1.0.0
15302 */
operator >(const_reference lhs,const_reference rhs)15303 friend bool operator>(const_reference lhs, const_reference rhs) noexcept
15304 {
15305 return not (lhs <= rhs);
15306 }
15307
15308 /*!
15309 @brief comparison: greater than
15310 @copydoc operator>(const_reference, const_reference)
15311 */
15312 template<typename ScalarType, typename std::enable_if<
15313 std::is_scalar<ScalarType>::value, int>::type = 0>
operator >(const_reference lhs,const ScalarType rhs)15314 friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
15315 {
15316 return (lhs > basic_json(rhs));
15317 }
15318
15319 /*!
15320 @brief comparison: greater than
15321 @copydoc operator>(const_reference, const_reference)
15322 */
15323 template<typename ScalarType, typename std::enable_if<
15324 std::is_scalar<ScalarType>::value, int>::type = 0>
operator >(const ScalarType lhs,const_reference rhs)15325 friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
15326 {
15327 return (basic_json(lhs) > rhs);
15328 }
15329
15330 /*!
15331 @brief comparison: greater than or equal
15332
15333 Compares whether one JSON value @a lhs is greater than or equal to another
15334 JSON value by calculating `not (lhs < rhs)`.
15335
15336 @param[in] lhs first JSON value to consider
15337 @param[in] rhs second JSON value to consider
15338 @return whether @a lhs is greater than or equal to @a rhs
15339
15340 @complexity Linear.
15341
15342 @exceptionsafety No-throw guarantee: this function never throws exceptions.
15343
15344 @liveexample{The example demonstrates comparing several JSON
15345 types.,operator__greaterequal}
15346
15347 @since version 1.0.0
15348 */
operator >=(const_reference lhs,const_reference rhs)15349 friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
15350 {
15351 return not (lhs < rhs);
15352 }
15353
15354 /*!
15355 @brief comparison: greater than or equal
15356 @copydoc operator>=(const_reference, const_reference)
15357 */
15358 template<typename ScalarType, typename std::enable_if<
15359 std::is_scalar<ScalarType>::value, int>::type = 0>
operator >=(const_reference lhs,const ScalarType rhs)15360 friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
15361 {
15362 return (lhs >= basic_json(rhs));
15363 }
15364
15365 /*!
15366 @brief comparison: greater than or equal
15367 @copydoc operator>=(const_reference, const_reference)
15368 */
15369 template<typename ScalarType, typename std::enable_if<
15370 std::is_scalar<ScalarType>::value, int>::type = 0>
operator >=(const ScalarType lhs,const_reference rhs)15371 friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
15372 {
15373 return (basic_json(lhs) >= rhs);
15374 }
15375
15376 /// @}
15377
15378 ///////////////////
15379 // serialization //
15380 ///////////////////
15381
15382 /// @name serialization
15383 /// @{
15384
15385 /*!
15386 @brief serialize to stream
15387
15388 Serialize the given JSON value @a j to the output stream @a o. The JSON
15389 value will be serialized using the @ref dump member function.
15390
15391 - The indentation of the output can be controlled with the member variable
15392 `width` of the output stream @a o. For instance, using the manipulator
15393 `std::setw(4)` on @a o sets the indentation level to `4` and the
15394 serialization result is the same as calling `dump(4)`.
15395
15396 - The indentation character can be controlled with the member variable
15397 `fill` of the output stream @a o. For instance, the manipulator
15398 `std::setfill('\\t')` sets indentation to use a tab character rather than
15399 the default space character.
15400
15401 @param[in,out] o stream to serialize to
15402 @param[in] j JSON value to serialize
15403
15404 @return the stream @a o
15405
15406 @throw type_error.316 if a string stored inside the JSON value is not
15407 UTF-8 encoded
15408
15409 @complexity Linear.
15410
15411 @liveexample{The example below shows the serialization with different
15412 parameters to `width` to adjust the indentation level.,operator_serialize}
15413
15414 @since version 1.0.0; indentation character added in version 3.0.0
15415 */
operator <<(std::ostream & o,const basic_json & j)15416 friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
15417 {
15418 // read width member and use it as indentation parameter if nonzero
15419 const bool pretty_print = (o.width() > 0);
15420 const auto indentation = (pretty_print ? o.width() : 0);
15421
15422 // reset width to 0 for subsequent calls to this stream
15423 o.width(0);
15424
15425 // do the actual serialization
15426 serializer s(detail::output_adapter<char>(o), o.fill());
15427 s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
15428 return o;
15429 }
15430
15431 /*!
15432 @brief serialize to stream
15433 @deprecated This stream operator is deprecated and will be removed in
15434 future 4.0.0 of the library. Please use
15435 @ref operator<<(std::ostream&, const basic_json&)
15436 instead; that is, replace calls like `j >> o;` with `o << j;`.
15437 @since version 1.0.0; deprecated since version 3.0.0
15438 */
15439 JSON_DEPRECATED
operator >>(const basic_json & j,std::ostream & o)15440 friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
15441 {
15442 return o << j;
15443 }
15444
15445 /// @}
15446
15447
15448 /////////////////////
15449 // deserialization //
15450 /////////////////////
15451
15452 /// @name deserialization
15453 /// @{
15454
15455 /*!
15456 @brief deserialize from a compatible input
15457
15458 This function reads from a compatible input. Examples are:
15459 - an array of 1-byte values
15460 - strings with character/literal type with size of 1 byte
15461 - input streams
15462 - container with contiguous storage of 1-byte values. Compatible container
15463 types include `std::vector`, `std::string`, `std::array`,
15464 `std::valarray`, and `std::initializer_list`. Furthermore, C-style
15465 arrays can be used with `std::begin()`/`std::end()`. User-defined
15466 containers can be used as long as they implement random-access iterators
15467 and a contiguous storage.
15468
15469 @pre Each element of the container has a size of 1 byte. Violating this
15470 precondition yields undefined behavior. **This precondition is enforced
15471 with a static assertion.**
15472
15473 @pre The container storage is contiguous. Violating this precondition
15474 yields undefined behavior. **This precondition is enforced with an
15475 assertion.**
15476 @pre Each element of the container has a size of 1 byte. Violating this
15477 precondition yields undefined behavior. **This precondition is enforced
15478 with a static assertion.**
15479
15480 @warning There is no way to enforce all preconditions at compile-time. If
15481 the function is called with a noncompliant container and with
15482 assertions switched off, the behavior is undefined and will most
15483 likely yield segmentation violation.
15484
15485 @param[in] i input to read from
15486 @param[in] cb a parser callback function of type @ref parser_callback_t
15487 which is used to control the deserialization by filtering unwanted values
15488 (optional)
15489
15490 @return result of the deserialization
15491
15492 @throw parse_error.101 if a parse error occurs; example: `""unexpected end
15493 of input; expected string literal""`
15494 @throw parse_error.102 if to_unicode fails or surrogate error
15495 @throw parse_error.103 if to_unicode fails
15496
15497 @complexity Linear in the length of the input. The parser is a predictive
15498 LL(1) parser. The complexity can be higher if the parser callback function
15499 @a cb has a super-linear complexity.
15500
15501 @note A UTF-8 byte order mark is silently ignored.
15502
15503 @liveexample{The example below demonstrates the `parse()` function reading
15504 from an array.,parse__array__parser_callback_t}
15505
15506 @liveexample{The example below demonstrates the `parse()` function with
15507 and without callback function.,parse__string__parser_callback_t}
15508
15509 @liveexample{The example below demonstrates the `parse()` function with
15510 and without callback function.,parse__istream__parser_callback_t}
15511
15512 @liveexample{The example below demonstrates the `parse()` function reading
15513 from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
15514
15515 @since version 2.0.3 (contiguous containers)
15516 */
parse(detail::input_adapter i,const parser_callback_t cb=nullptr,const bool allow_exceptions=true)15517 static basic_json parse(detail::input_adapter i,
15518 const parser_callback_t cb = nullptr,
15519 const bool allow_exceptions = true)
15520 {
15521 basic_json result;
15522 parser(i, cb, allow_exceptions).parse(true, result);
15523 return result;
15524 }
15525
15526 /*!
15527 @copydoc basic_json parse(detail::input_adapter, const parser_callback_t)
15528 */
parse(detail::input_adapter & i,const parser_callback_t cb=nullptr,const bool allow_exceptions=true)15529 static basic_json parse(detail::input_adapter& i,
15530 const parser_callback_t cb = nullptr,
15531 const bool allow_exceptions = true)
15532 {
15533 basic_json result;
15534 parser(i, cb, allow_exceptions).parse(true, result);
15535 return result;
15536 }
15537
accept(detail::input_adapter i)15538 static bool accept(detail::input_adapter i)
15539 {
15540 return parser(i).accept(true);
15541 }
15542
accept(detail::input_adapter & i)15543 static bool accept(detail::input_adapter& i)
15544 {
15545 return parser(i).accept(true);
15546 }
15547
15548 /*!
15549 @brief deserialize from an iterator range with contiguous storage
15550
15551 This function reads from an iterator range of a container with contiguous
15552 storage of 1-byte values. Compatible container types include
15553 `std::vector`, `std::string`, `std::array`, `std::valarray`, and
15554 `std::initializer_list`. Furthermore, C-style arrays can be used with
15555 `std::begin()`/`std::end()`. User-defined containers can be used as long
15556 as they implement random-access iterators and a contiguous storage.
15557
15558 @pre The iterator range is contiguous. Violating this precondition yields
15559 undefined behavior. **This precondition is enforced with an assertion.**
15560 @pre Each element in the range has a size of 1 byte. Violating this
15561 precondition yields undefined behavior. **This precondition is enforced
15562 with a static assertion.**
15563
15564 @warning There is no way to enforce all preconditions at compile-time. If
15565 the function is called with noncompliant iterators and with
15566 assertions switched off, the behavior is undefined and will most
15567 likely yield segmentation violation.
15568
15569 @tparam IteratorType iterator of container with contiguous storage
15570 @param[in] first begin of the range to parse (included)
15571 @param[in] last end of the range to parse (excluded)
15572 @param[in] cb a parser callback function of type @ref parser_callback_t
15573 which is used to control the deserialization by filtering unwanted values
15574 (optional)
15575 @param[in] allow_exceptions whether to throw exceptions in case of a
15576 parse error (optional, true by default)
15577
15578 @return result of the deserialization
15579
15580 @throw parse_error.101 in case of an unexpected token
15581 @throw parse_error.102 if to_unicode fails or surrogate error
15582 @throw parse_error.103 if to_unicode fails
15583
15584 @complexity Linear in the length of the input. The parser is a predictive
15585 LL(1) parser. The complexity can be higher if the parser callback function
15586 @a cb has a super-linear complexity.
15587
15588 @note A UTF-8 byte order mark is silently ignored.
15589
15590 @liveexample{The example below demonstrates the `parse()` function reading
15591 from an iterator range.,parse__iteratortype__parser_callback_t}
15592
15593 @since version 2.0.3
15594 */
15595 template<class IteratorType, typename std::enable_if<
15596 std::is_base_of<
15597 std::random_access_iterator_tag,
15598 typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
parse(IteratorType first,IteratorType last,const parser_callback_t cb=nullptr,const bool allow_exceptions=true)15599 static basic_json parse(IteratorType first, IteratorType last,
15600 const parser_callback_t cb = nullptr,
15601 const bool allow_exceptions = true)
15602 {
15603 basic_json result;
15604 parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
15605 return result;
15606 }
15607
15608 template<class IteratorType, typename std::enable_if<
15609 std::is_base_of<
15610 std::random_access_iterator_tag,
15611 typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
accept(IteratorType first,IteratorType last)15612 static bool accept(IteratorType first, IteratorType last)
15613 {
15614 return parser(detail::input_adapter(first, last)).accept(true);
15615 }
15616
15617 /*!
15618 @brief deserialize from stream
15619 @deprecated This stream operator is deprecated and will be removed in
15620 version 4.0.0 of the library. Please use
15621 @ref operator>>(std::istream&, basic_json&)
15622 instead; that is, replace calls like `j << i;` with `i >> j;`.
15623 @since version 1.0.0; deprecated since version 3.0.0
15624 */
15625 JSON_DEPRECATED
operator <<(basic_json & j,std::istream & i)15626 friend std::istream& operator<<(basic_json& j, std::istream& i)
15627 {
15628 return operator>>(i, j);
15629 }
15630
15631 /*!
15632 @brief deserialize from stream
15633
15634 Deserializes an input stream to a JSON value.
15635
15636 @param[in,out] i input stream to read a serialized JSON value from
15637 @param[in,out] j JSON value to write the deserialized input to
15638
15639 @throw parse_error.101 in case of an unexpected token
15640 @throw parse_error.102 if to_unicode fails or surrogate error
15641 @throw parse_error.103 if to_unicode fails
15642
15643 @complexity Linear in the length of the input. The parser is a predictive
15644 LL(1) parser.
15645
15646 @note A UTF-8 byte order mark is silently ignored.
15647
15648 @liveexample{The example below shows how a JSON value is constructed by
15649 reading a serialization from a stream.,operator_deserialize}
15650
15651 @sa parse(std::istream&, const parser_callback_t) for a variant with a
15652 parser callback function to filter values while parsing
15653
15654 @since version 1.0.0
15655 */
operator >>(std::istream & i,basic_json & j)15656 friend std::istream& operator>>(std::istream& i, basic_json& j)
15657 {
15658 parser(detail::input_adapter(i)).parse(false, j);
15659 return i;
15660 }
15661
15662 /// @}
15663
15664 ///////////////////////////
15665 // convenience functions //
15666 ///////////////////////////
15667
15668 /*!
15669 @brief return the type as string
15670
15671 Returns the type name as string to be used in error messages - usually to
15672 indicate that a function was called on a wrong JSON type.
15673
15674 @return a string representation of a the @a m_type member:
15675 Value type | return value
15676 ----------- | -------------
15677 null | `"null"`
15678 boolean | `"boolean"`
15679 string | `"string"`
15680 number | `"number"` (for all number types)
15681 object | `"object"`
15682 array | `"array"`
15683 discarded | `"discarded"`
15684
15685 @exceptionsafety No-throw guarantee: this function never throws exceptions.
15686
15687 @complexity Constant.
15688
15689 @liveexample{The following code exemplifies `type_name()` for all JSON
15690 types.,type_name}
15691
15692 @sa @ref type() -- return the type of the JSON value
15693 @sa @ref operator value_t() -- return the type of the JSON value (implicit)
15694
15695 @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
15696 since 3.0.0
15697 */
type_name() const15698 const char* type_name() const noexcept
15699 {
15700 {
15701 switch (m_type)
15702 {
15703 case value_t::null:
15704 return "null";
15705 case value_t::object:
15706 return "object";
15707 case value_t::array:
15708 return "array";
15709 case value_t::string:
15710 return "string";
15711 case value_t::boolean:
15712 return "boolean";
15713 case value_t::discarded:
15714 return "discarded";
15715 default:
15716 return "number";
15717 }
15718 }
15719 }
15720
15721
15722 private:
15723 //////////////////////
15724 // member variables //
15725 //////////////////////
15726
15727 /// the type of the current element
15728 value_t m_type = value_t::null;
15729
15730 /// the value of the current element
15731 json_value m_value = {};
15732
15733 //////////////////////////////////////////
15734 // binary serialization/deserialization //
15735 //////////////////////////////////////////
15736
15737 /// @name binary serialization/deserialization support
15738 /// @{
15739
15740 public:
15741 /*!
15742 @brief create a CBOR serialization of a given JSON value
15743
15744 Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
15745 Binary Object Representation) serialization format. CBOR is a binary
15746 serialization format which aims to be more compact than JSON itself, yet
15747 more efficient to parse.
15748
15749 The library uses the following mapping from JSON values types to
15750 CBOR types according to the CBOR specification (RFC 7049):
15751
15752 JSON value type | value/range | CBOR type | first byte
15753 --------------- | ------------------------------------------ | ---------------------------------- | ---------------
15754 null | `null` | Null | 0xF6
15755 boolean | `true` | True | 0xF5
15756 boolean | `false` | False | 0xF4
15757 number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
15758 number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
15759 number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
15760 number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
15761 number_integer | -24..-1 | Negative integer | 0x20..0x37
15762 number_integer | 0..23 | Integer | 0x00..0x17
15763 number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
15764 number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
15765 number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
15766 number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
15767 number_unsigned | 0..23 | Integer | 0x00..0x17
15768 number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
15769 number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
15770 number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
15771 number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
15772 number_float | *any value* | Double-Precision Float | 0xFB
15773 string | *length*: 0..23 | UTF-8 string | 0x60..0x77
15774 string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
15775 string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
15776 string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
15777 string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
15778 array | *size*: 0..23 | array | 0x80..0x97
15779 array | *size*: 23..255 | array (1 byte follow) | 0x98
15780 array | *size*: 256..65535 | array (2 bytes follow) | 0x99
15781 array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
15782 array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
15783 object | *size*: 0..23 | map | 0xA0..0xB7
15784 object | *size*: 23..255 | map (1 byte follow) | 0xB8
15785 object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
15786 object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
15787 object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
15788
15789 @note The mapping is **complete** in the sense that any JSON value type
15790 can be converted to a CBOR value.
15791
15792 @note If NaN or Infinity are stored inside a JSON number, they are
15793 serialized properly. This behavior differs from the @ref dump()
15794 function which serializes NaN or Infinity to `null`.
15795
15796 @note The following CBOR types are not used in the conversion:
15797 - byte strings (0x40..0x5F)
15798 - UTF-8 strings terminated by "break" (0x7F)
15799 - arrays terminated by "break" (0x9F)
15800 - maps terminated by "break" (0xBF)
15801 - date/time (0xC0..0xC1)
15802 - bignum (0xC2..0xC3)
15803 - decimal fraction (0xC4)
15804 - bigfloat (0xC5)
15805 - tagged items (0xC6..0xD4, 0xD8..0xDB)
15806 - expected conversions (0xD5..0xD7)
15807 - simple values (0xE0..0xF3, 0xF8)
15808 - undefined (0xF7)
15809 - half and single-precision floats (0xF9-0xFA)
15810 - break (0xFF)
15811
15812 @param[in] j JSON value to serialize
15813 @return MessagePack serialization as byte vector
15814
15815 @complexity Linear in the size of the JSON value @a j.
15816
15817 @liveexample{The example shows the serialization of a JSON value to a byte
15818 vector in CBOR format.,to_cbor}
15819
15820 @sa http://cbor.io
15821 @sa @ref from_cbor(detail::input_adapter, const bool strict) for the
15822 analogous deserialization
15823 @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
15824 @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
15825 related UBJSON format
15826
15827 @since version 2.0.9
15828 */
to_cbor(const basic_json & j)15829 static std::vector<uint8_t> to_cbor(const basic_json& j)
15830 {
15831 std::vector<uint8_t> result;
15832 to_cbor(j, result);
15833 return result;
15834 }
15835
to_cbor(const basic_json & j,detail::output_adapter<uint8_t> o)15836 static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
15837 {
15838 binary_writer<uint8_t>(o).write_cbor(j);
15839 }
15840
to_cbor(const basic_json & j,detail::output_adapter<char> o)15841 static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
15842 {
15843 binary_writer<char>(o).write_cbor(j);
15844 }
15845
15846 /*!
15847 @brief create a MessagePack serialization of a given JSON value
15848
15849 Serializes a given JSON value @a j to a byte vector using the MessagePack
15850 serialization format. MessagePack is a binary serialization format which
15851 aims to be more compact than JSON itself, yet more efficient to parse.
15852
15853 The library uses the following mapping from JSON values types to
15854 MessagePack types according to the MessagePack specification:
15855
15856 JSON value type | value/range | MessagePack type | first byte
15857 --------------- | --------------------------------- | ---------------- | ----------
15858 null | `null` | nil | 0xC0
15859 boolean | `true` | true | 0xC3
15860 boolean | `false` | false | 0xC2
15861 number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
15862 number_integer | -2147483648..-32769 | int32 | 0xD2
15863 number_integer | -32768..-129 | int16 | 0xD1
15864 number_integer | -128..-33 | int8 | 0xD0
15865 number_integer | -32..-1 | negative fixint | 0xE0..0xFF
15866 number_integer | 0..127 | positive fixint | 0x00..0x7F
15867 number_integer | 128..255 | uint 8 | 0xCC
15868 number_integer | 256..65535 | uint 16 | 0xCD
15869 number_integer | 65536..4294967295 | uint 32 | 0xCE
15870 number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
15871 number_unsigned | 0..127 | positive fixint | 0x00..0x7F
15872 number_unsigned | 128..255 | uint 8 | 0xCC
15873 number_unsigned | 256..65535 | uint 16 | 0xCD
15874 number_unsigned | 65536..4294967295 | uint 32 | 0xCE
15875 number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
15876 number_float | *any value* | float 64 | 0xCB
15877 string | *length*: 0..31 | fixstr | 0xA0..0xBF
15878 string | *length*: 32..255 | str 8 | 0xD9
15879 string | *length*: 256..65535 | str 16 | 0xDA
15880 string | *length*: 65536..4294967295 | str 32 | 0xDB
15881 array | *size*: 0..15 | fixarray | 0x90..0x9F
15882 array | *size*: 16..65535 | array 16 | 0xDC
15883 array | *size*: 65536..4294967295 | array 32 | 0xDD
15884 object | *size*: 0..15 | fix map | 0x80..0x8F
15885 object | *size*: 16..65535 | map 16 | 0xDE
15886 object | *size*: 65536..4294967295 | map 32 | 0xDF
15887
15888 @note The mapping is **complete** in the sense that any JSON value type
15889 can be converted to a MessagePack value.
15890
15891 @note The following values can **not** be converted to a MessagePack value:
15892 - strings with more than 4294967295 bytes
15893 - arrays with more than 4294967295 elements
15894 - objects with more than 4294967295 elements
15895
15896 @note The following MessagePack types are not used in the conversion:
15897 - bin 8 - bin 32 (0xC4..0xC6)
15898 - ext 8 - ext 32 (0xC7..0xC9)
15899 - float 32 (0xCA)
15900 - fixext 1 - fixext 16 (0xD4..0xD8)
15901
15902 @note Any MessagePack output created @ref to_msgpack can be successfully
15903 parsed by @ref from_msgpack.
15904
15905 @note If NaN or Infinity are stored inside a JSON number, they are
15906 serialized properly. This behavior differs from the @ref dump()
15907 function which serializes NaN or Infinity to `null`.
15908
15909 @param[in] j JSON value to serialize
15910 @return MessagePack serialization as byte vector
15911
15912 @complexity Linear in the size of the JSON value @a j.
15913
15914 @liveexample{The example shows the serialization of a JSON value to a byte
15915 vector in MessagePack format.,to_msgpack}
15916
15917 @sa http://msgpack.org
15918 @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
15919 analogous deserialization
15920 @sa @ref to_cbor(const basic_json& for the related CBOR format
15921 @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
15922 related UBJSON format
15923
15924 @since version 2.0.9
15925 */
to_msgpack(const basic_json & j)15926 static std::vector<uint8_t> to_msgpack(const basic_json& j)
15927 {
15928 std::vector<uint8_t> result;
15929 to_msgpack(j, result);
15930 return result;
15931 }
15932
to_msgpack(const basic_json & j,detail::output_adapter<uint8_t> o)15933 static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
15934 {
15935 binary_writer<uint8_t>(o).write_msgpack(j);
15936 }
15937
to_msgpack(const basic_json & j,detail::output_adapter<char> o)15938 static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
15939 {
15940 binary_writer<char>(o).write_msgpack(j);
15941 }
15942
15943 /*!
15944 @brief create a UBJSON serialization of a given JSON value
15945
15946 Serializes a given JSON value @a j to a byte vector using the UBJSON
15947 (Universal Binary JSON) serialization format. UBJSON aims to be more compact
15948 than JSON itself, yet more efficient to parse.
15949
15950 The library uses the following mapping from JSON values types to
15951 UBJSON types according to the UBJSON specification:
15952
15953 JSON value type | value/range | UBJSON type | marker
15954 --------------- | --------------------------------- | ----------- | ------
15955 null | `null` | null | `Z`
15956 boolean | `true` | true | `T`
15957 boolean | `false` | false | `F`
15958 number_integer | -9223372036854775808..-2147483649 | int64 | `L`
15959 number_integer | -2147483648..-32769 | int32 | `l`
15960 number_integer | -32768..-129 | int16 | `I`
15961 number_integer | -128..127 | int8 | `i`
15962 number_integer | 128..255 | uint8 | `U`
15963 number_integer | 256..32767 | int16 | `I`
15964 number_integer | 32768..2147483647 | int32 | `l`
15965 number_integer | 2147483648..9223372036854775807 | int64 | `L`
15966 number_unsigned | 0..127 | int8 | `i`
15967 number_unsigned | 128..255 | uint8 | `U`
15968 number_unsigned | 256..32767 | int16 | `I`
15969 number_unsigned | 32768..2147483647 | int32 | `l`
15970 number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
15971 number_float | *any value* | float64 | `D`
15972 string | *with shortest length indicator* | string | `S`
15973 array | *see notes on optimized format* | array | `[`
15974 object | *see notes on optimized format* | map | `{`
15975
15976 @note The mapping is **complete** in the sense that any JSON value type
15977 can be converted to a UBJSON value.
15978
15979 @note The following values can **not** be converted to a UBJSON value:
15980 - strings with more than 9223372036854775807 bytes (theoretical)
15981 - unsigned integer numbers above 9223372036854775807
15982
15983 @note The following markers are not used in the conversion:
15984 - `Z`: no-op values are not created.
15985 - `C`: single-byte strings are serialized with `S` markers.
15986
15987 @note Any UBJSON output created @ref to_ubjson can be successfully parsed
15988 by @ref from_ubjson.
15989
15990 @note If NaN or Infinity are stored inside a JSON number, they are
15991 serialized properly. This behavior differs from the @ref dump()
15992 function which serializes NaN or Infinity to `null`.
15993
15994 @note The optimized formats for containers are supported: Parameter
15995 @a use_size adds size information to the beginning of a container and
15996 removes the closing marker. Parameter @a use_type further checks
15997 whether all elements of a container have the same type and adds the
15998 type marker to the beginning of the container. The @a use_type
15999 parameter must only be used together with @a use_size = true. Note
16000 that @a use_size = true alone may result in larger representations -
16001 the benefit of this parameter is that the receiving side is
16002 immediately informed on the number of elements of the container.
16003
16004 @param[in] j JSON value to serialize
16005 @param[in] use_size whether to add size annotations to container types
16006 @param[in] use_type whether to add type annotations to container types
16007 (must be combined with @a use_size = true)
16008 @return UBJSON serialization as byte vector
16009
16010 @complexity Linear in the size of the JSON value @a j.
16011
16012 @liveexample{The example shows the serialization of a JSON value to a byte
16013 vector in UBJSON format.,to_ubjson}
16014
16015 @sa http://ubjson.org
16016 @sa @ref from_ubjson(detail::input_adapter, const bool strict) for the
16017 analogous deserialization
16018 @sa @ref to_cbor(const basic_json& for the related CBOR format
16019 @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
16020
16021 @since version 3.1.0
16022 */
to_ubjson(const basic_json & j,const bool use_size=false,const bool use_type=false)16023 static std::vector<uint8_t> to_ubjson(const basic_json& j,
16024 const bool use_size = false,
16025 const bool use_type = false)
16026 {
16027 std::vector<uint8_t> result;
16028 to_ubjson(j, result, use_size, use_type);
16029 return result;
16030 }
16031
to_ubjson(const basic_json & j,detail::output_adapter<uint8_t> o,const bool use_size=false,const bool use_type=false)16032 static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
16033 const bool use_size = false, const bool use_type = false)
16034 {
16035 binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
16036 }
16037
to_ubjson(const basic_json & j,detail::output_adapter<char> o,const bool use_size=false,const bool use_type=false)16038 static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
16039 const bool use_size = false, const bool use_type = false)
16040 {
16041 binary_writer<char>(o).write_ubjson(j, use_size, use_type);
16042 }
16043
16044 /*!
16045 @brief create a JSON value from an input in CBOR format
16046
16047 Deserializes a given input @a i to a JSON value using the CBOR (Concise
16048 Binary Object Representation) serialization format.
16049
16050 The library maps CBOR types to JSON value types as follows:
16051
16052 CBOR type | JSON value type | first byte
16053 ---------------------- | --------------- | ----------
16054 Integer | number_unsigned | 0x00..0x17
16055 Unsigned integer | number_unsigned | 0x18
16056 Unsigned integer | number_unsigned | 0x19
16057 Unsigned integer | number_unsigned | 0x1A
16058 Unsigned integer | number_unsigned | 0x1B
16059 Negative integer | number_integer | 0x20..0x37
16060 Negative integer | number_integer | 0x38
16061 Negative integer | number_integer | 0x39
16062 Negative integer | number_integer | 0x3A
16063 Negative integer | number_integer | 0x3B
16064 Negative integer | number_integer | 0x40..0x57
16065 UTF-8 string | string | 0x60..0x77
16066 UTF-8 string | string | 0x78
16067 UTF-8 string | string | 0x79
16068 UTF-8 string | string | 0x7A
16069 UTF-8 string | string | 0x7B
16070 UTF-8 string | string | 0x7F
16071 array | array | 0x80..0x97
16072 array | array | 0x98
16073 array | array | 0x99
16074 array | array | 0x9A
16075 array | array | 0x9B
16076 array | array | 0x9F
16077 map | object | 0xA0..0xB7
16078 map | object | 0xB8
16079 map | object | 0xB9
16080 map | object | 0xBA
16081 map | object | 0xBB
16082 map | object | 0xBF
16083 False | `false` | 0xF4
16084 True | `true` | 0xF5
16085 Nill | `null` | 0xF6
16086 Half-Precision Float | number_float | 0xF9
16087 Single-Precision Float | number_float | 0xFA
16088 Double-Precision Float | number_float | 0xFB
16089
16090 @warning The mapping is **incomplete** in the sense that not all CBOR
16091 types can be converted to a JSON value. The following CBOR types
16092 are not supported and will yield parse errors (parse_error.112):
16093 - byte strings (0x40..0x5F)
16094 - date/time (0xC0..0xC1)
16095 - bignum (0xC2..0xC3)
16096 - decimal fraction (0xC4)
16097 - bigfloat (0xC5)
16098 - tagged items (0xC6..0xD4, 0xD8..0xDB)
16099 - expected conversions (0xD5..0xD7)
16100 - simple values (0xE0..0xF3, 0xF8)
16101 - undefined (0xF7)
16102
16103 @warning CBOR allows map keys of any type, whereas JSON only allows
16104 strings as keys in object values. Therefore, CBOR maps with keys
16105 other than UTF-8 strings are rejected (parse_error.113).
16106
16107 @note Any CBOR output created @ref to_cbor can be successfully parsed by
16108 @ref from_cbor.
16109
16110 @param[in] i an input in CBOR format convertible to an input adapter
16111 @param[in] strict whether to expect the input to be consumed until EOF
16112 (true by default)
16113 @return deserialized JSON value
16114
16115 @throw parse_error.110 if the given input ends prematurely or the end of
16116 file was not reached when @a strict was set to true
16117 @throw parse_error.112 if unsupported features from CBOR were
16118 used in the given input @a v or if the input is not valid CBOR
16119 @throw parse_error.113 if a string was expected as map key, but not found
16120
16121 @complexity Linear in the size of the input @a i.
16122
16123 @liveexample{The example shows the deserialization of a byte vector in CBOR
16124 format to a JSON value.,from_cbor}
16125
16126 @sa http://cbor.io
16127 @sa @ref to_cbor(const basic_json&) for the analogous serialization
16128 @sa @ref from_msgpack(detail::input_adapter, const bool) for the
16129 related MessagePack format
16130 @sa @ref from_ubjson(detail::input_adapter, const bool) for the related
16131 UBJSON format
16132
16133 @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
16134 consume input adapters, removed start_index parameter, and added
16135 @a strict parameter since 3.0.0
16136 */
from_cbor(detail::input_adapter i,const bool strict=true)16137 static basic_json from_cbor(detail::input_adapter i,
16138 const bool strict = true)
16139 {
16140 return binary_reader(i).parse_cbor(strict);
16141 }
16142
16143 /*!
16144 @copydoc from_cbor(detail::input_adapter, const bool)
16145 */
16146 template<typename A1, typename A2,
16147 detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
from_cbor(A1 && a1,A2 && a2,const bool strict=true)16148 static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true)
16149 {
16150 return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_cbor(strict);
16151 }
16152
16153 /*!
16154 @brief create a JSON value from an input in MessagePack format
16155
16156 Deserializes a given input @a i to a JSON value using the MessagePack
16157 serialization format.
16158
16159 The library maps MessagePack types to JSON value types as follows:
16160
16161 MessagePack type | JSON value type | first byte
16162 ---------------- | --------------- | ----------
16163 positive fixint | number_unsigned | 0x00..0x7F
16164 fixmap | object | 0x80..0x8F
16165 fixarray | array | 0x90..0x9F
16166 fixstr | string | 0xA0..0xBF
16167 nil | `null` | 0xC0
16168 false | `false` | 0xC2
16169 true | `true` | 0xC3
16170 float 32 | number_float | 0xCA
16171 float 64 | number_float | 0xCB
16172 uint 8 | number_unsigned | 0xCC
16173 uint 16 | number_unsigned | 0xCD
16174 uint 32 | number_unsigned | 0xCE
16175 uint 64 | number_unsigned | 0xCF
16176 int 8 | number_integer | 0xD0
16177 int 16 | number_integer | 0xD1
16178 int 32 | number_integer | 0xD2
16179 int 64 | number_integer | 0xD3
16180 str 8 | string | 0xD9
16181 str 16 | string | 0xDA
16182 str 32 | string | 0xDB
16183 array 16 | array | 0xDC
16184 array 32 | array | 0xDD
16185 map 16 | object | 0xDE
16186 map 32 | object | 0xDF
16187 negative fixint | number_integer | 0xE0-0xFF
16188
16189 @warning The mapping is **incomplete** in the sense that not all
16190 MessagePack types can be converted to a JSON value. The following
16191 MessagePack types are not supported and will yield parse errors:
16192 - bin 8 - bin 32 (0xC4..0xC6)
16193 - ext 8 - ext 32 (0xC7..0xC9)
16194 - fixext 1 - fixext 16 (0xD4..0xD8)
16195
16196 @note Any MessagePack output created @ref to_msgpack can be successfully
16197 parsed by @ref from_msgpack.
16198
16199 @param[in] i an input in MessagePack format convertible to an input
16200 adapter
16201 @param[in] strict whether to expect the input to be consumed until EOF
16202 (true by default)
16203
16204 @throw parse_error.110 if the given input ends prematurely or the end of
16205 file was not reached when @a strict was set to true
16206 @throw parse_error.112 if unsupported features from MessagePack were
16207 used in the given input @a i or if the input is not valid MessagePack
16208 @throw parse_error.113 if a string was expected as map key, but not found
16209
16210 @complexity Linear in the size of the input @a i.
16211
16212 @liveexample{The example shows the deserialization of a byte vector in
16213 MessagePack format to a JSON value.,from_msgpack}
16214
16215 @sa http://msgpack.org
16216 @sa @ref to_msgpack(const basic_json&) for the analogous serialization
16217 @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR
16218 format
16219 @sa @ref from_ubjson(detail::input_adapter, const bool) for the related
16220 UBJSON format
16221
16222 @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
16223 consume input adapters, removed start_index parameter, and added
16224 @a strict parameter since 3.0.0
16225 */
from_msgpack(detail::input_adapter i,const bool strict=true)16226 static basic_json from_msgpack(detail::input_adapter i,
16227 const bool strict = true)
16228 {
16229 return binary_reader(i).parse_msgpack(strict);
16230 }
16231
16232 /*!
16233 @copydoc from_msgpack(detail::input_adapter, const bool)
16234 */
16235 template<typename A1, typename A2,
16236 detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
from_msgpack(A1 && a1,A2 && a2,const bool strict=true)16237 static basic_json from_msgpack(A1 && a1, A2 && a2, const bool strict = true)
16238 {
16239 return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_msgpack(strict);
16240 }
16241
16242 /*!
16243 @brief create a JSON value from an input in UBJSON format
16244
16245 Deserializes a given input @a i to a JSON value using the UBJSON (Universal
16246 Binary JSON) serialization format.
16247
16248 The library maps UBJSON types to JSON value types as follows:
16249
16250 UBJSON type | JSON value type | marker
16251 ----------- | --------------------------------------- | ------
16252 no-op | *no value, next value is read* | `N`
16253 null | `null` | `Z`
16254 false | `false` | `F`
16255 true | `true` | `T`
16256 float32 | number_float | `d`
16257 float64 | number_float | `D`
16258 uint8 | number_unsigned | `U`
16259 int8 | number_integer | `i`
16260 int16 | number_integer | `I`
16261 int32 | number_integer | `l`
16262 int64 | number_integer | `L`
16263 string | string | `S`
16264 char | string | `C`
16265 array | array (optimized values are supported) | `[`
16266 object | object (optimized values are supported) | `{`
16267
16268 @note The mapping is **complete** in the sense that any UBJSON value can
16269 be converted to a JSON value.
16270
16271 @param[in] i an input in UBJSON format convertible to an input adapter
16272 @param[in] strict whether to expect the input to be consumed until EOF
16273 (true by default)
16274
16275 @throw parse_error.110 if the given input ends prematurely or the end of
16276 file was not reached when @a strict was set to true
16277 @throw parse_error.112 if a parse error occurs
16278 @throw parse_error.113 if a string could not be parsed successfully
16279
16280 @complexity Linear in the size of the input @a i.
16281
16282 @liveexample{The example shows the deserialization of a byte vector in
16283 UBJSON format to a JSON value.,from_ubjson}
16284
16285 @sa http://ubjson.org
16286 @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
16287 analogous serialization
16288 @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR
16289 format
16290 @sa @ref from_msgpack(detail::input_adapter, const bool) for the related
16291 MessagePack format
16292
16293 @since version 3.1.0
16294 */
from_ubjson(detail::input_adapter i,const bool strict=true)16295 static basic_json from_ubjson(detail::input_adapter i,
16296 const bool strict = true)
16297 {
16298 return binary_reader(i).parse_ubjson(strict);
16299 }
16300
16301 template<typename A1, typename A2,
16302 detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
from_ubjson(A1 && a1,A2 && a2,const bool strict=true)16303 static basic_json from_ubjson(A1 && a1, A2 && a2, const bool strict = true)
16304 {
16305 return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_ubjson(strict);
16306 }
16307
16308 /// @}
16309
16310 //////////////////////////
16311 // JSON Pointer support //
16312 //////////////////////////
16313
16314 /// @name JSON Pointer functions
16315 /// @{
16316
16317 /*!
16318 @brief access specified element via JSON Pointer
16319
16320 Uses a JSON pointer to retrieve a reference to the respective JSON value.
16321 No bound checking is performed. Similar to @ref operator[](const typename
16322 object_t::key_type&), `null` values are created in arrays and objects if
16323 necessary.
16324
16325 In particular:
16326 - If the JSON pointer points to an object key that does not exist, it
16327 is created an filled with a `null` value before a reference to it
16328 is returned.
16329 - If the JSON pointer points to an array index that does not exist, it
16330 is created an filled with a `null` value before a reference to it
16331 is returned. All indices between the current maximum and the given
16332 index are also filled with `null`.
16333 - The special value `-` is treated as a synonym for the index past the
16334 end.
16335
16336 @param[in] ptr a JSON pointer
16337
16338 @return reference to the element pointed to by @a ptr
16339
16340 @complexity Constant.
16341
16342 @throw parse_error.106 if an array index begins with '0'
16343 @throw parse_error.109 if an array index was not a number
16344 @throw out_of_range.404 if the JSON pointer can not be resolved
16345
16346 @liveexample{The behavior is shown in the example.,operatorjson_pointer}
16347
16348 @since version 2.0.0
16349 */
operator [](const json_pointer & ptr)16350 reference operator[](const json_pointer& ptr)
16351 {
16352 return ptr.get_unchecked(this);
16353 }
16354
16355 /*!
16356 @brief access specified element via JSON Pointer
16357
16358 Uses a JSON pointer to retrieve a reference to the respective JSON value.
16359 No bound checking is performed. The function does not change the JSON
16360 value; no `null` values are created. In particular, the the special value
16361 `-` yields an exception.
16362
16363 @param[in] ptr JSON pointer to the desired element
16364
16365 @return const reference to the element pointed to by @a ptr
16366
16367 @complexity Constant.
16368
16369 @throw parse_error.106 if an array index begins with '0'
16370 @throw parse_error.109 if an array index was not a number
16371 @throw out_of_range.402 if the array index '-' is used
16372 @throw out_of_range.404 if the JSON pointer can not be resolved
16373
16374 @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
16375
16376 @since version 2.0.0
16377 */
operator [](const json_pointer & ptr) const16378 const_reference operator[](const json_pointer& ptr) const
16379 {
16380 return ptr.get_unchecked(this);
16381 }
16382
16383 /*!
16384 @brief access specified element via JSON Pointer
16385
16386 Returns a reference to the element at with specified JSON pointer @a ptr,
16387 with bounds checking.
16388
16389 @param[in] ptr JSON pointer to the desired element
16390
16391 @return reference to the element pointed to by @a ptr
16392
16393 @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
16394 begins with '0'. See example below.
16395
16396 @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
16397 is not a number. See example below.
16398
16399 @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
16400 is out of range. See example below.
16401
16402 @throw out_of_range.402 if the array index '-' is used in the passed JSON
16403 pointer @a ptr. As `at` provides checked access (and no elements are
16404 implicitly inserted), the index '-' is always invalid. See example below.
16405
16406 @throw out_of_range.403 if the JSON pointer describes a key of an object
16407 which cannot be found. See example below.
16408
16409 @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
16410 See example below.
16411
16412 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
16413 changes in the JSON value.
16414
16415 @complexity Constant.
16416
16417 @since version 2.0.0
16418
16419 @liveexample{The behavior is shown in the example.,at_json_pointer}
16420 */
at(const json_pointer & ptr)16421 reference at(const json_pointer& ptr)
16422 {
16423 return ptr.get_checked(this);
16424 }
16425
16426 /*!
16427 @brief access specified element via JSON Pointer
16428
16429 Returns a const reference to the element at with specified JSON pointer @a
16430 ptr, with bounds checking.
16431
16432 @param[in] ptr JSON pointer to the desired element
16433
16434 @return reference to the element pointed to by @a ptr
16435
16436 @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
16437 begins with '0'. See example below.
16438
16439 @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
16440 is not a number. See example below.
16441
16442 @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
16443 is out of range. See example below.
16444
16445 @throw out_of_range.402 if the array index '-' is used in the passed JSON
16446 pointer @a ptr. As `at` provides checked access (and no elements are
16447 implicitly inserted), the index '-' is always invalid. See example below.
16448
16449 @throw out_of_range.403 if the JSON pointer describes a key of an object
16450 which cannot be found. See example below.
16451
16452 @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
16453 See example below.
16454
16455 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
16456 changes in the JSON value.
16457
16458 @complexity Constant.
16459
16460 @since version 2.0.0
16461
16462 @liveexample{The behavior is shown in the example.,at_json_pointer_const}
16463 */
at(const json_pointer & ptr) const16464 const_reference at(const json_pointer& ptr) const
16465 {
16466 return ptr.get_checked(this);
16467 }
16468
16469 /*!
16470 @brief return flattened JSON value
16471
16472 The function creates a JSON object whose keys are JSON pointers (see [RFC
16473 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
16474 primitive. The original JSON value can be restored using the @ref
16475 unflatten() function.
16476
16477 @return an object that maps JSON pointers to primitive values
16478
16479 @note Empty objects and arrays are flattened to `null` and will not be
16480 reconstructed correctly by the @ref unflatten() function.
16481
16482 @complexity Linear in the size the JSON value.
16483
16484 @liveexample{The following code shows how a JSON object is flattened to an
16485 object whose keys consist of JSON pointers.,flatten}
16486
16487 @sa @ref unflatten() for the reverse function
16488
16489 @since version 2.0.0
16490 */
flatten() const16491 basic_json flatten() const
16492 {
16493 basic_json result(value_t::object);
16494 json_pointer::flatten("", *this, result);
16495 return result;
16496 }
16497
16498 /*!
16499 @brief unflatten a previously flattened JSON value
16500
16501 The function restores the arbitrary nesting of a JSON value that has been
16502 flattened before using the @ref flatten() function. The JSON value must
16503 meet certain constraints:
16504 1. The value must be an object.
16505 2. The keys must be JSON pointers (see
16506 [RFC 6901](https://tools.ietf.org/html/rfc6901))
16507 3. The mapped values must be primitive JSON types.
16508
16509 @return the original JSON from a flattened version
16510
16511 @note Empty objects and arrays are flattened by @ref flatten() to `null`
16512 values and can not unflattened to their original type. Apart from
16513 this example, for a JSON value `j`, the following is always true:
16514 `j == j.flatten().unflatten()`.
16515
16516 @complexity Linear in the size the JSON value.
16517
16518 @throw type_error.314 if value is not an object
16519 @throw type_error.315 if object values are not primitive
16520
16521 @liveexample{The following code shows how a flattened JSON object is
16522 unflattened into the original nested JSON object.,unflatten}
16523
16524 @sa @ref flatten() for the reverse function
16525
16526 @since version 2.0.0
16527 */
unflatten() const16528 basic_json unflatten() const
16529 {
16530 return json_pointer::unflatten(*this);
16531 }
16532
16533 /// @}
16534
16535 //////////////////////////
16536 // JSON Patch functions //
16537 //////////////////////////
16538
16539 /// @name JSON Patch functions
16540 /// @{
16541
16542 /*!
16543 @brief applies a JSON patch
16544
16545 [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
16546 expressing a sequence of operations to apply to a JSON) document. With
16547 this function, a JSON Patch is applied to the current JSON value by
16548 executing all operations from the patch.
16549
16550 @param[in] json_patch JSON patch document
16551 @return patched document
16552
16553 @note The application of a patch is atomic: Either all operations succeed
16554 and the patched document is returned or an exception is thrown. In
16555 any case, the original value is not changed: the patch is applied
16556 to a copy of the value.
16557
16558 @throw parse_error.104 if the JSON patch does not consist of an array of
16559 objects
16560
16561 @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
16562 attributes are missing); example: `"operation add must have member path"`
16563
16564 @throw out_of_range.401 if an array index is out of range.
16565
16566 @throw out_of_range.403 if a JSON pointer inside the patch could not be
16567 resolved successfully in the current JSON value; example: `"key baz not
16568 found"`
16569
16570 @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
16571 "move")
16572
16573 @throw other_error.501 if "test" operation was unsuccessful
16574
16575 @complexity Linear in the size of the JSON value and the length of the
16576 JSON patch. As usually only a fraction of the JSON value is affected by
16577 the patch, the complexity can usually be neglected.
16578
16579 @liveexample{The following code shows how a JSON patch is applied to a
16580 value.,patch}
16581
16582 @sa @ref diff -- create a JSON patch by comparing two JSON values
16583
16584 @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
16585 @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
16586
16587 @since version 2.0.0
16588 */
patch(const basic_json & json_patch) const16589 basic_json patch(const basic_json& json_patch) const
16590 {
16591 // make a working copy to apply the patch to
16592 basic_json result = *this;
16593
16594 // the valid JSON Patch operations
16595 enum class patch_operations {add, remove, replace, move, copy, test, invalid};
16596
16597 const auto get_op = [](const std::string & op)
16598 {
16599 if (op == "add")
16600 {
16601 return patch_operations::add;
16602 }
16603 if (op == "remove")
16604 {
16605 return patch_operations::remove;
16606 }
16607 if (op == "replace")
16608 {
16609 return patch_operations::replace;
16610 }
16611 if (op == "move")
16612 {
16613 return patch_operations::move;
16614 }
16615 if (op == "copy")
16616 {
16617 return patch_operations::copy;
16618 }
16619 if (op == "test")
16620 {
16621 return patch_operations::test;
16622 }
16623
16624 return patch_operations::invalid;
16625 };
16626
16627 // wrapper for "add" operation; add value at ptr
16628 const auto operation_add = [&result](json_pointer & ptr, basic_json val)
16629 {
16630 // adding to the root of the target document means replacing it
16631 if (ptr.is_root())
16632 {
16633 result = val;
16634 }
16635 else
16636 {
16637 // make sure the top element of the pointer exists
16638 json_pointer top_pointer = ptr.top();
16639 if (top_pointer != ptr)
16640 {
16641 result.at(top_pointer);
16642 }
16643
16644 // get reference to parent of JSON pointer ptr
16645 const auto last_path = ptr.pop_back();
16646 basic_json& parent = result[ptr];
16647
16648 switch (parent.m_type)
16649 {
16650 case value_t::null:
16651 case value_t::object:
16652 {
16653 // use operator[] to add value
16654 parent[last_path] = val;
16655 break;
16656 }
16657
16658 case value_t::array:
16659 {
16660 if (last_path == "-")
16661 {
16662 // special case: append to back
16663 parent.push_back(val);
16664 }
16665 else
16666 {
16667 const auto idx = json_pointer::array_index(last_path);
16668 if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
16669 {
16670 // avoid undefined behavior
16671 JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
16672 }
16673 else
16674 {
16675 // default case: insert add offset
16676 parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
16677 }
16678 }
16679 break;
16680 }
16681
16682 default:
16683 {
16684 // if there exists a parent it cannot be primitive
16685 assert(false); // LCOV_EXCL_LINE
16686 }
16687 }
16688 }
16689 };
16690
16691 // wrapper for "remove" operation; remove value at ptr
16692 const auto operation_remove = [&result](json_pointer & ptr)
16693 {
16694 // get reference to parent of JSON pointer ptr
16695 const auto last_path = ptr.pop_back();
16696 basic_json& parent = result.at(ptr);
16697
16698 // remove child
16699 if (parent.is_object())
16700 {
16701 // perform range check
16702 auto it = parent.find(last_path);
16703 if (JSON_LIKELY(it != parent.end()))
16704 {
16705 parent.erase(it);
16706 }
16707 else
16708 {
16709 JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
16710 }
16711 }
16712 else if (parent.is_array())
16713 {
16714 // note erase performs range check
16715 parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
16716 }
16717 };
16718
16719 // type check: top level value must be an array
16720 if (JSON_UNLIKELY(not json_patch.is_array()))
16721 {
16722 JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
16723 }
16724
16725 // iterate and apply the operations
16726 for (const auto& val : json_patch)
16727 {
16728 // wrapper to get a value for an operation
16729 const auto get_value = [&val](const std::string & op,
16730 const std::string & member,
16731 bool string_type) -> basic_json &
16732 {
16733 // find value
16734 auto it = val.m_value.object->find(member);
16735
16736 // context-sensitive error message
16737 const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
16738
16739 // check if desired value is present
16740 if (JSON_UNLIKELY(it == val.m_value.object->end()))
16741 {
16742 JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
16743 }
16744
16745 // check if result is of type string
16746 if (JSON_UNLIKELY(string_type and not it->second.is_string()))
16747 {
16748 JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
16749 }
16750
16751 // no error: return value
16752 return it->second;
16753 };
16754
16755 // type check: every element of the array must be an object
16756 if (JSON_UNLIKELY(not val.is_object()))
16757 {
16758 JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
16759 }
16760
16761 // collect mandatory members
16762 const std::string op = get_value("op", "op", true);
16763 const std::string path = get_value(op, "path", true);
16764 json_pointer ptr(path);
16765
16766 switch (get_op(op))
16767 {
16768 case patch_operations::add:
16769 {
16770 operation_add(ptr, get_value("add", "value", false));
16771 break;
16772 }
16773
16774 case patch_operations::remove:
16775 {
16776 operation_remove(ptr);
16777 break;
16778 }
16779
16780 case patch_operations::replace:
16781 {
16782 // the "path" location must exist - use at()
16783 result.at(ptr) = get_value("replace", "value", false);
16784 break;
16785 }
16786
16787 case patch_operations::move:
16788 {
16789 const std::string from_path = get_value("move", "from", true);
16790 json_pointer from_ptr(from_path);
16791
16792 // the "from" location must exist - use at()
16793 basic_json v = result.at(from_ptr);
16794
16795 // The move operation is functionally identical to a
16796 // "remove" operation on the "from" location, followed
16797 // immediately by an "add" operation at the target
16798 // location with the value that was just removed.
16799 operation_remove(from_ptr);
16800 operation_add(ptr, v);
16801 break;
16802 }
16803
16804 case patch_operations::copy:
16805 {
16806 const std::string from_path = get_value("copy", "from", true);
16807 const json_pointer from_ptr(from_path);
16808
16809 // the "from" location must exist - use at()
16810 basic_json v = result.at(from_ptr);
16811
16812 // The copy is functionally identical to an "add"
16813 // operation at the target location using the value
16814 // specified in the "from" member.
16815 operation_add(ptr, v);
16816 break;
16817 }
16818
16819 case patch_operations::test:
16820 {
16821 bool success = false;
16822 JSON_TRY
16823 {
16824 // check if "value" matches the one at "path"
16825 // the "path" location must exist - use at()
16826 success = (result.at(ptr) == get_value("test", "value", false));
16827 }
16828 JSON_CATCH (out_of_range&)
16829 {
16830 // ignore out of range errors: success remains false
16831 }
16832
16833 // throw an exception if test fails
16834 if (JSON_UNLIKELY(not success))
16835 {
16836 JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
16837 }
16838
16839 break;
16840 }
16841
16842 case patch_operations::invalid:
16843 {
16844 // op must be "add", "remove", "replace", "move", "copy", or
16845 // "test"
16846 JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
16847 }
16848 }
16849 }
16850
16851 return result;
16852 }
16853
16854 /*!
16855 @brief creates a diff as a JSON patch
16856
16857 Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
16858 be changed into the value @a target by calling @ref patch function.
16859
16860 @invariant For two JSON values @a source and @a target, the following code
16861 yields always `true`:
16862 @code {.cpp}
16863 source.patch(diff(source, target)) == target;
16864 @endcode
16865
16866 @note Currently, only `remove`, `add`, and `replace` operations are
16867 generated.
16868
16869 @param[in] source JSON value to compare from
16870 @param[in] target JSON value to compare against
16871 @param[in] path helper value to create JSON pointers
16872
16873 @return a JSON patch to convert the @a source to @a target
16874
16875 @complexity Linear in the lengths of @a source and @a target.
16876
16877 @liveexample{The following code shows how a JSON patch is created as a
16878 diff for two JSON values.,diff}
16879
16880 @sa @ref patch -- apply a JSON patch
16881 @sa @ref merge_patch -- apply a JSON Merge Patch
16882
16883 @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
16884
16885 @since version 2.0.0
16886 */
diff(const basic_json & source,const basic_json & target,const std::string & path="")16887 static basic_json diff(const basic_json& source, const basic_json& target,
16888 const std::string& path = "")
16889 {
16890 // the patch
16891 basic_json result(value_t::array);
16892
16893 // if the values are the same, return empty patch
16894 if (source == target)
16895 {
16896 return result;
16897 }
16898
16899 if (source.type() != target.type())
16900 {
16901 // different types: replace value
16902 result.push_back(
16903 {
16904 {"op", "replace"}, {"path", path}, {"value", target}
16905 });
16906 }
16907 else
16908 {
16909 switch (source.type())
16910 {
16911 case value_t::array:
16912 {
16913 // first pass: traverse common elements
16914 std::size_t i = 0;
16915 while (i < source.size() and i < target.size())
16916 {
16917 // recursive call to compare array values at index i
16918 auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
16919 result.insert(result.end(), temp_diff.begin(), temp_diff.end());
16920 ++i;
16921 }
16922
16923 // i now reached the end of at least one array
16924 // in a second pass, traverse the remaining elements
16925
16926 // remove my remaining elements
16927 const auto end_index = static_cast<difference_type>(result.size());
16928 while (i < source.size())
16929 {
16930 // add operations in reverse order to avoid invalid
16931 // indices
16932 result.insert(result.begin() + end_index, object(
16933 {
16934 {"op", "remove"},
16935 {"path", path + "/" + std::to_string(i)}
16936 }));
16937 ++i;
16938 }
16939
16940 // add other remaining elements
16941 while (i < target.size())
16942 {
16943 result.push_back(
16944 {
16945 {"op", "add"},
16946 {"path", path + "/" + std::to_string(i)},
16947 {"value", target[i]}
16948 });
16949 ++i;
16950 }
16951
16952 break;
16953 }
16954
16955 case value_t::object:
16956 {
16957 // first pass: traverse this object's elements
16958 for (auto it = source.cbegin(); it != source.cend(); ++it)
16959 {
16960 // escape the key name to be used in a JSON patch
16961 const auto key = json_pointer::escape(it.key());
16962
16963 if (target.find(it.key()) != target.end())
16964 {
16965 // recursive call to compare object values at key it
16966 auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
16967 result.insert(result.end(), temp_diff.begin(), temp_diff.end());
16968 }
16969 else
16970 {
16971 // found a key that is not in o -> remove it
16972 result.push_back(object(
16973 {
16974 {"op", "remove"}, {"path", path + "/" + key}
16975 }));
16976 }
16977 }
16978
16979 // second pass: traverse other object's elements
16980 for (auto it = target.cbegin(); it != target.cend(); ++it)
16981 {
16982 if (source.find(it.key()) == source.end())
16983 {
16984 // found a key that is not in this -> add it
16985 const auto key = json_pointer::escape(it.key());
16986 result.push_back(
16987 {
16988 {"op", "add"}, {"path", path + "/" + key},
16989 {"value", it.value()}
16990 });
16991 }
16992 }
16993
16994 break;
16995 }
16996
16997 default:
16998 {
16999 // both primitive type: replace value
17000 result.push_back(
17001 {
17002 {"op", "replace"}, {"path", path}, {"value", target}
17003 });
17004 break;
17005 }
17006 }
17007 }
17008
17009 return result;
17010 }
17011
17012 /// @}
17013
17014 ////////////////////////////////
17015 // JSON Merge Patch functions //
17016 ////////////////////////////////
17017
17018 /// @name JSON Merge Patch functions
17019 /// @{
17020
17021 /*!
17022 @brief applies a JSON Merge Patch
17023
17024 The merge patch format is primarily intended for use with the HTTP PATCH
17025 method as a means of describing a set of modifications to a target
17026 resource's content. This function applies a merge patch to the current
17027 JSON value.
17028
17029 The function implements the following algorithm from Section 2 of
17030 [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
17031
17032 ```
17033 define MergePatch(Target, Patch):
17034 if Patch is an Object:
17035 if Target is not an Object:
17036 Target = {} // Ignore the contents and set it to an empty Object
17037 for each Name/Value pair in Patch:
17038 if Value is null:
17039 if Name exists in Target:
17040 remove the Name/Value pair from Target
17041 else:
17042 Target[Name] = MergePatch(Target[Name], Value)
17043 return Target
17044 else:
17045 return Patch
17046 ```
17047
17048 Thereby, `Target` is the current object; that is, the patch is applied to
17049 the current value.
17050
17051 @param[in] patch the patch to apply
17052
17053 @complexity Linear in the lengths of @a patch.
17054
17055 @liveexample{The following code shows how a JSON Merge Patch is applied to
17056 a JSON document.,merge_patch}
17057
17058 @sa @ref patch -- apply a JSON patch
17059 @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
17060
17061 @since version 3.0.0
17062 */
merge_patch(const basic_json & patch)17063 void merge_patch(const basic_json& patch)
17064 {
17065 if (patch.is_object())
17066 {
17067 if (not is_object())
17068 {
17069 *this = object();
17070 }
17071 for (auto it = patch.begin(); it != patch.end(); ++it)
17072 {
17073 if (it.value().is_null())
17074 {
17075 erase(it.key());
17076 }
17077 else
17078 {
17079 operator[](it.key()).merge_patch(it.value());
17080 }
17081 }
17082 }
17083 else
17084 {
17085 *this = patch;
17086 }
17087 }
17088
17089 /// @}
17090 };
17091 } // namespace nlohmann
17092
17093 ///////////////////////
17094 // nonmember support //
17095 ///////////////////////
17096
17097 // specialization of std::swap, and std::hash
17098 namespace std
17099 {
17100 /*!
17101 @brief exchanges the values of two JSON objects
17102
17103 @since version 1.0.0
17104 */
17105 template<>
swap(nlohmann::json & j1,nlohmann::json & j2)17106 inline void swap(nlohmann::json& j1,
17107 nlohmann::json& j2) noexcept(
17108 is_nothrow_move_constructible<nlohmann::json>::value and
17109 is_nothrow_move_assignable<nlohmann::json>::value
17110 )
17111 {
17112 j1.swap(j2);
17113 }
17114
17115 /// hash value for JSON objects
17116 template<>
17117 struct hash<nlohmann::json>
17118 {
17119 /*!
17120 @brief return a hash value for a JSON object
17121
17122 @since version 1.0.0
17123 */
operator ()std::hash17124 std::size_t operator()(const nlohmann::json& j) const
17125 {
17126 // a naive hashing via the string representation
17127 const auto& h = hash<nlohmann::json::string_t>();
17128 return h(j.dump());
17129 }
17130 };
17131
17132 /// specialization for std::less<value_t>
17133 /// @note: do not remove the space after '<',
17134 /// see https://github.com/nlohmann/json/pull/679
17135 template<>
17136 struct less< ::nlohmann::detail::value_t>
17137 {
17138 /*!
17139 @brief compare two value_t enum values
17140 @since version 3.0.0
17141 */
operator ()std::less17142 bool operator()(nlohmann::detail::value_t lhs,
17143 nlohmann::detail::value_t rhs) const noexcept
17144 {
17145 return nlohmann::detail::operator<(lhs, rhs);
17146 }
17147 };
17148
17149 } // namespace std
17150
17151 /*!
17152 @brief user-defined string literal for JSON values
17153
17154 This operator implements a user-defined string literal for JSON objects. It
17155 can be used by adding `"_json"` to a string literal and returns a JSON object
17156 if no parse error occurred.
17157
17158 @param[in] s a string representation of a JSON object
17159 @param[in] n the length of string @a s
17160 @return a JSON object
17161
17162 @since version 1.0.0
17163 */
operator ""_json(const char * s,std::size_t n)17164 inline nlohmann::json operator "" _json(const char* s, std::size_t n)
17165 {
17166 return nlohmann::json::parse(s, s + n);
17167 }
17168
17169 /*!
17170 @brief user-defined string literal for JSON pointer
17171
17172 This operator implements a user-defined string literal for JSON Pointers. It
17173 can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
17174 object if no parse error occurred.
17175
17176 @param[in] s a string representation of a JSON Pointer
17177 @param[in] n the length of string @a s
17178 @return a JSON pointer object
17179
17180 @since version 2.0.0
17181 */
operator ""_json_pointer(const char * s,std::size_t n)17182 inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
17183 {
17184 return nlohmann::json::json_pointer(std::string(s, n));
17185 }
17186
17187 // #include <nlohmann/detail/macro_unscope.hpp>
17188
17189
17190 // restore GCC/clang diagnostic settings
17191 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
17192 #pragma GCC diagnostic pop
17193 #endif
17194 #if defined(__clang__)
17195 #pragma GCC diagnostic pop
17196 #endif
17197
17198 // clean up
17199 #undef JSON_CATCH
17200 #undef JSON_THROW
17201 #undef JSON_TRY
17202 #undef JSON_LIKELY
17203 #undef JSON_UNLIKELY
17204 #undef JSON_DEPRECATED
17205 #undef JSON_HAS_CPP_14
17206 #undef JSON_HAS_CPP_17
17207 #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
17208 #undef NLOHMANN_BASIC_JSON_TPL
17209 #undef NLOHMANN_JSON_HAS_HELPER
17210
17211
17212 #endif
17213