• R/O
  • SSH

Commit

Tags
No Tags

Frequently used words (click to add to your profile)

javac++androidlinuxc#objective-cqt誰得cocoawindowspythonrubyphpgameguibathyscaphec翻訳omegat計画中(planning stage)frameworktwittertestdombtronvb.netdirectxarduinopreviewerゲームエンジン

This is a fork of Zandronum for TSPG.


Commit MetaInfo

Revisión65db5d52630caa1aae583df27e121ce6ba071527 (tree)
Tiempo2018-10-23 06:08:18
AutorSean Baggaley <sean@csnx...>
CommiterSean Baggaley

Log Message

Add support for automated proxy detection

Cambiar Resumen

Diferencia incremental

diff -r 17e5ed239033 -r 65db5d52630c src/CMakeLists.txt
--- a/src/CMakeLists.txt Sat Mar 17 10:26:52 2018 +0000
+++ b/src/CMakeLists.txt Mon Oct 22 22:08:18 2018 +0100
@@ -1426,6 +1426,9 @@
14261426 r_data/r_interpolate.cpp
14271427 r_data/r_translate.cpp
14281428 zzautozend.cpp
1429+
1430+ # [TSPG]
1431+ tspg_dnsbl.cpp
14291432 )
14301433
14311434 # [BB] To keep the delta to ZDoom small, we keep the target name 'zdoom', but
diff -r 17e5ed239033 -r 65db5d52630c src/json.hpp
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/json.hpp Mon Oct 22 22:08:18 2018 +0100
@@ -0,0 +1,18912 @@
1+/*
2+ __ _____ _____ _____
3+ __| | __| | | | JSON for Modern C++
4+| | |__ | | | | | | version 3.2.0
5+|_____|_____|_____|_|___| https://github.com/nlohmann/json
6+
7+Licensed under the MIT License <http://opensource.org/licenses/MIT>.
8+SPDX-License-Identifier: MIT
9+Copyright (c) 2013-2018 Niels Lohmann <http://nlohmann.me>.
10+
11+Permission is hereby granted, free of charge, to any person obtaining a copy
12+of this software and associated documentation files (the "Software"), to deal
13+in the Software without restriction, including without limitation the rights
14+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15+copies of the Software, and to permit persons to whom the Software is
16+furnished to do so, subject to the following conditions:
17+
18+The above copyright notice and this permission notice shall be included in all
19+copies or substantial portions of the Software.
20+
21+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27+SOFTWARE.
28+*/
29+
30+#ifndef NLOHMANN_JSON_HPP
31+#define NLOHMANN_JSON_HPP
32+
33+#define NLOHMANN_JSON_VERSION_MAJOR 3
34+#define NLOHMANN_JSON_VERSION_MINOR 2
35+#define NLOHMANN_JSON_VERSION_PATCH 0
36+
37+#include <algorithm> // all_of, find, for_each
38+#include <cassert> // assert
39+#include <ciso646> // and, not, or
40+#include <cstddef> // nullptr_t, ptrdiff_t, size_t
41+#include <functional> // hash, less
42+#include <initializer_list> // initializer_list
43+#include <iosfwd> // istream, ostream
44+#include <iterator> // iterator_traits, random_access_iterator_tag
45+#include <numeric> // accumulate
46+#include <string> // string, stoi, to_string
47+#include <utility> // declval, forward, move, pair, swap
48+
49+// #include <nlohmann/json_fwd.hpp>
50+#ifndef NLOHMANN_JSON_FWD_HPP
51+#define NLOHMANN_JSON_FWD_HPP
52+
53+#include <cstdint> // int64_t, uint64_t
54+#include <map> // map
55+#include <memory> // allocator
56+#include <string> // string
57+#include <vector> // vector
58+
59+/*!
60+@brief namespace for Niels Lohmann
61+@see https://github.com/nlohmann
62+@since version 1.0.0
63+*/
64+namespace nlohmann
65+{
66+/*!
67+@brief default JSONSerializer template argument
68+
69+This serializer ignores the template arguments and uses ADL
70+([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
71+for serialization.
72+*/
73+template<typename T = void, typename SFINAE = void>
74+struct adl_serializer;
75+
76+template<template<typename U, typename V, typename... Args> class ObjectType =
77+ std::map,
78+ template<typename U, typename... Args> class ArrayType = std::vector,
79+ class StringType = std::string, class BooleanType = bool,
80+ class NumberIntegerType = std::int64_t,
81+ class NumberUnsignedType = std::uint64_t,
82+ class NumberFloatType = double,
83+ template<typename U> class AllocatorType = std::allocator,
84+ template<typename T, typename SFINAE = void> class JSONSerializer =
85+ adl_serializer>
86+class basic_json;
87+
88+/*!
89+@brief JSON Pointer
90+
91+A JSON pointer defines a string syntax for identifying a specific value
92+within a JSON document. It can be used with functions `at` and
93+`operator[]`. Furthermore, JSON pointers are the base for JSON patches.
94+
95+@sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
96+
97+@since version 2.0.0
98+*/
99+template<typename BasicJsonType>
100+class json_pointer;
101+
102+/*!
103+@brief default JSON class
104+
105+This type is the default specialization of the @ref basic_json class which
106+uses the standard template types.
107+
108+@since version 1.0.0
109+*/
110+using json = basic_json<>;
111+}
112+
113+#endif
114+
115+// #include <nlohmann/detail/macro_scope.hpp>
116+
117+
118+// This file contains all internal macro definitions
119+// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
120+
121+// exclude unsupported compilers
122+#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
123+ #if defined(__clang__)
124+ #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
125+ #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
126+ #endif
127+ #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
128+ #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900
129+ #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
130+ #endif
131+ #endif
132+#endif
133+
134+// disable float-equal warnings on GCC/clang
135+#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
136+ #pragma GCC diagnostic push
137+ #pragma GCC diagnostic ignored "-Wfloat-equal"
138+#endif
139+
140+// disable documentation warnings on clang
141+#if defined(__clang__)
142+ #pragma GCC diagnostic push
143+ #pragma GCC diagnostic ignored "-Wdocumentation"
144+#endif
145+
146+// allow for portable deprecation warnings
147+#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
148+ #define JSON_DEPRECATED __attribute__((deprecated))
149+#elif defined(_MSC_VER)
150+ #define JSON_DEPRECATED __declspec(deprecated)
151+#else
152+ #define JSON_DEPRECATED
153+#endif
154+
155+// allow to disable exceptions
156+#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
157+ #define JSON_THROW(exception) throw exception
158+ #define JSON_TRY try
159+ #define JSON_CATCH(exception) catch(exception)
160+ #define JSON_INTERNAL_CATCH(exception) catch(exception)
161+#else
162+ #define JSON_THROW(exception) std::abort()
163+ #define JSON_TRY if(true)
164+ #define JSON_CATCH(exception) if(false)
165+ #define JSON_INTERNAL_CATCH(exception) if(false)
166+#endif
167+
168+// override exception macros
169+#if defined(JSON_THROW_USER)
170+ #undef JSON_THROW
171+ #define JSON_THROW JSON_THROW_USER
172+#endif
173+#if defined(JSON_TRY_USER)
174+ #undef JSON_TRY
175+ #define JSON_TRY JSON_TRY_USER
176+#endif
177+#if defined(JSON_CATCH_USER)
178+ #undef JSON_CATCH
179+ #define JSON_CATCH JSON_CATCH_USER
180+ #define JSON_INTERNAL_CATCH JSON_CATCH_USER
181+#endif
182+#if defined(JSON_INTERNAL_CATCH_USER)
183+ #undef JSON_INTERNAL_CATCH
184+ #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
185+#endif
186+
187+// manual branch prediction
188+#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
189+ #define JSON_LIKELY(x) __builtin_expect(!!(x), 1)
190+ #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
191+#else
192+ #define JSON_LIKELY(x) x
193+ #define JSON_UNLIKELY(x) x
194+#endif
195+
196+// C++ language standard detection
197+#if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
198+ #define JSON_HAS_CPP_17
199+ #define JSON_HAS_CPP_14
200+#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
201+ #define JSON_HAS_CPP_14
202+#endif
203+
204+// Ugly macros to avoid uglier copy-paste when specializing basic_json. They
205+// may be removed in the future once the class is split.
206+
207+#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
208+ template<template<typename, typename, typename...> class ObjectType, \
209+ template<typename, typename...> class ArrayType, \
210+ class StringType, class BooleanType, class NumberIntegerType, \
211+ class NumberUnsignedType, class NumberFloatType, \
212+ template<typename> class AllocatorType, \
213+ template<typename, typename = void> class JSONSerializer>
214+
215+#define NLOHMANN_BASIC_JSON_TPL \
216+ basic_json<ObjectType, ArrayType, StringType, BooleanType, \
217+ NumberIntegerType, NumberUnsignedType, NumberFloatType, \
218+ AllocatorType, JSONSerializer>
219+
220+/*!
221+@brief Helper to determine whether there's a key_type for T.
222+
223+This helper is used to tell associative containers apart from other containers
224+such as sequence containers. For instance, `std::map` passes the test as it
225+contains a `mapped_type`, whereas `std::vector` fails the test.
226+
227+@sa http://stackoverflow.com/a/7728728/266378
228+@since version 1.0.0, overworked in version 2.0.6
229+*/
230+#define NLOHMANN_JSON_HAS_HELPER(type) \
231+ template<typename T> struct has_##type { \
232+ private: \
233+ template<typename U, typename = typename U::type> \
234+ static int detect(U &&); \
235+ static void detect(...); \
236+ public: \
237+ static constexpr bool value = \
238+ std::is_integral<decltype(detect(std::declval<T>()))>::value; \
239+ }
240+
241+// #include <nlohmann/detail/meta/cpp_future.hpp>
242+
243+
244+#include <ciso646> // not
245+#include <cstddef> // size_t
246+#include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
247+
248+namespace nlohmann
249+{
250+namespace detail
251+{
252+// alias templates to reduce boilerplate
253+template<bool B, typename T = void>
254+using enable_if_t = typename std::enable_if<B, T>::type;
255+
256+template<typename T>
257+using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
258+
259+// implementation of C++14 index_sequence and affiliates
260+// source: https://stackoverflow.com/a/32223343
261+template<std::size_t... Ints>
262+struct index_sequence
263+{
264+ using type = index_sequence;
265+ using value_type = std::size_t;
266+ static constexpr std::size_t size() noexcept
267+ {
268+ return sizeof...(Ints);
269+ }
270+};
271+
272+template<class Sequence1, class Sequence2>
273+struct merge_and_renumber;
274+
275+template<std::size_t... I1, std::size_t... I2>
276+struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
277+ : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
278+
279+template<std::size_t N>
280+struct make_index_sequence
281+ : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
282+ typename make_index_sequence < N - N / 2 >::type > {};
283+
284+template<> struct make_index_sequence<0> : index_sequence<> {};
285+template<> struct make_index_sequence<1> : index_sequence<0> {};
286+
287+template<typename... Ts>
288+using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
289+
290+/*
291+Implementation of two C++17 constructs: conjunction, negation. This is needed
292+to avoid evaluating all the traits in a condition
293+
294+For example: not std::is_same<void, T>::value and has_value_type<T>::value
295+will not compile when T = void (on MSVC at least). Whereas
296+conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
297+stop evaluating if negation<...>::value == false
298+
299+Please note that those constructs must be used with caution, since symbols can
300+become very long quickly (which can slow down compilation and cause MSVC
301+internal compiler errors). Only use it when you have to (see example ahead).
302+*/
303+template<class...> struct conjunction : std::true_type {};
304+template<class B1> struct conjunction<B1> : B1 {};
305+template<class B1, class... Bn>
306+struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
307+
308+template<class B> struct negation : std::integral_constant<bool, not B::value> {};
309+
310+// dispatch utility (taken from ranges-v3)
311+template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
312+template<> struct priority_tag<0> {};
313+
314+// taken from ranges-v3
315+template<typename T>
316+struct static_const
317+{
318+ static constexpr T value{};
319+};
320+
321+template<typename T>
322+constexpr T static_const<T>::value;
323+}
324+}
325+
326+// #include <nlohmann/detail/meta/type_traits.hpp>
327+
328+
329+#include <ciso646> // not
330+#include <limits> // numeric_limits
331+#include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
332+#include <utility> // declval
333+
334+// #include <nlohmann/json_fwd.hpp>
335+
336+// #include <nlohmann/detail/meta/cpp_future.hpp>
337+
338+// #include <nlohmann/detail/macro_scope.hpp>
339+
340+
341+namespace nlohmann
342+{
343+/*!
344+@brief detail namespace with internal helper functions
345+
346+This namespace collects functions that should not be exposed,
347+implementations of some @ref basic_json methods, and meta-programming helpers.
348+
349+@since version 2.1.0
350+*/
351+namespace detail
352+{
353+/////////////
354+// helpers //
355+/////////////
356+
357+template<typename> struct is_basic_json : std::false_type {};
358+
359+NLOHMANN_BASIC_JSON_TPL_DECLARATION
360+struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
361+
362+////////////////////////
363+// has_/is_ functions //
364+////////////////////////
365+
366+// source: https://stackoverflow.com/a/37193089/4116453
367+
368+template <typename T, typename = void>
369+struct is_complete_type : std::false_type {};
370+
371+template <typename T>
372+struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
373+
374+NLOHMANN_JSON_HAS_HELPER(mapped_type);
375+NLOHMANN_JSON_HAS_HELPER(key_type);
376+NLOHMANN_JSON_HAS_HELPER(value_type);
377+NLOHMANN_JSON_HAS_HELPER(iterator);
378+
379+template<bool B, class RealType, class CompatibleObjectType>
380+struct is_compatible_object_type_impl : std::false_type {};
381+
382+template<class RealType, class CompatibleObjectType>
383+struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
384+{
385+ static constexpr auto value =
386+ std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and
387+ std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value;
388+};
389+
390+template<bool B, class RealType, class CompatibleStringType>
391+struct is_compatible_string_type_impl : std::false_type {};
392+
393+template<class RealType, class CompatibleStringType>
394+struct is_compatible_string_type_impl<true, RealType, CompatibleStringType>
395+{
396+ static constexpr auto value =
397+ std::is_same<typename RealType::value_type, typename CompatibleStringType::value_type>::value and
398+ std::is_constructible<RealType, CompatibleStringType>::value;
399+};
400+
401+template<class BasicJsonType, class CompatibleObjectType>
402+struct is_compatible_object_type
403+{
404+ static auto constexpr value = is_compatible_object_type_impl <
405+ conjunction<negation<std::is_same<void, CompatibleObjectType>>,
406+ has_mapped_type<CompatibleObjectType>,
407+ has_key_type<CompatibleObjectType>>::value,
408+ typename BasicJsonType::object_t, CompatibleObjectType >::value;
409+};
410+
411+template<class BasicJsonType, class CompatibleStringType>
412+struct is_compatible_string_type
413+{
414+ static auto constexpr value = is_compatible_string_type_impl <
415+ conjunction<negation<std::is_same<void, CompatibleStringType>>,
416+ has_value_type<CompatibleStringType>>::value,
417+ typename BasicJsonType::string_t, CompatibleStringType >::value;
418+};
419+
420+template<typename BasicJsonType, typename T>
421+struct is_basic_json_nested_type
422+{
423+ static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
424+ std::is_same<T, typename BasicJsonType::const_iterator>::value or
425+ std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
426+ std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value;
427+};
428+
429+template<class BasicJsonType, class CompatibleArrayType>
430+struct is_compatible_array_type
431+{
432+ static auto constexpr value =
433+ conjunction<negation<std::is_same<void, CompatibleArrayType>>,
434+ negation<is_compatible_object_type<
435+ BasicJsonType, CompatibleArrayType>>,
436+ negation<std::is_constructible<typename BasicJsonType::string_t,
437+ CompatibleArrayType>>,
438+ negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
439+ has_value_type<CompatibleArrayType>,
440+ has_iterator<CompatibleArrayType>>::value;
441+};
442+
443+template<bool, typename, typename>
444+struct is_compatible_integer_type_impl : std::false_type {};
445+
446+template<typename RealIntegerType, typename CompatibleNumberIntegerType>
447+struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
448+{
449+ // is there an assert somewhere on overflows?
450+ using RealLimits = std::numeric_limits<RealIntegerType>;
451+ using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
452+
453+ static constexpr auto value =
454+ std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and
455+ CompatibleLimits::is_integer and
456+ RealLimits::is_signed == CompatibleLimits::is_signed;
457+};
458+
459+template<typename RealIntegerType, typename CompatibleNumberIntegerType>
460+struct is_compatible_integer_type
461+{
462+ static constexpr auto value =
463+ is_compatible_integer_type_impl <
464+ std::is_integral<CompatibleNumberIntegerType>::value and
465+ not std::is_same<bool, CompatibleNumberIntegerType>::value,
466+ RealIntegerType, CompatibleNumberIntegerType > ::value;
467+};
468+
469+// trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
470+template<typename BasicJsonType, typename T>
471+struct has_from_json
472+{
473+ private:
474+ // also check the return type of from_json
475+ template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
476+ std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
477+ static int detect(U&&);
478+ static void detect(...);
479+
480+ public:
481+ static constexpr bool value = std::is_integral<decltype(
482+ detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
483+};
484+
485+// This trait checks if JSONSerializer<T>::from_json(json const&) exists
486+// this overload is used for non-default-constructible user-defined-types
487+template<typename BasicJsonType, typename T>
488+struct has_non_default_from_json
489+{
490+ private:
491+ template <
492+ typename U,
493+ typename = enable_if_t<std::is_same<
494+ T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value >>
495+ static int detect(U&&);
496+ static void detect(...);
497+
498+ public:
499+ static constexpr bool value = std::is_integral<decltype(detect(
500+ std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
501+};
502+
503+// This trait checks if BasicJsonType::json_serializer<T>::to_json exists
504+template<typename BasicJsonType, typename T>
505+struct has_to_json
506+{
507+ private:
508+ template<typename U, typename = decltype(uncvref_t<U>::to_json(
509+ std::declval<BasicJsonType&>(), std::declval<T>()))>
510+ static int detect(U&&);
511+ static void detect(...);
512+
513+ public:
514+ static constexpr bool value = std::is_integral<decltype(detect(
515+ std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
516+};
517+
518+template <typename BasicJsonType, typename CompatibleCompleteType>
519+struct is_compatible_complete_type
520+{
521+ static constexpr bool value =
522+ not std::is_base_of<std::istream, CompatibleCompleteType>::value and
523+ not is_basic_json<CompatibleCompleteType>::value and
524+ not is_basic_json_nested_type<BasicJsonType, CompatibleCompleteType>::value and
525+ has_to_json<BasicJsonType, CompatibleCompleteType>::value;
526+};
527+
528+template <typename BasicJsonType, typename CompatibleType>
529+struct is_compatible_type
530+ : conjunction<is_complete_type<CompatibleType>,
531+ is_compatible_complete_type<BasicJsonType, CompatibleType>>
532+{
533+};
534+}
535+}
536+
537+// #include <nlohmann/detail/exceptions.hpp>
538+
539+
540+#include <exception> // exception
541+#include <stdexcept> // runtime_error
542+#include <string> // to_string
543+
544+namespace nlohmann
545+{
546+namespace detail
547+{
548+////////////////
549+// exceptions //
550+////////////////
551+
552+/*!
553+@brief general exception of the @ref basic_json class
554+
555+This class is an extension of `std::exception` objects with a member @a id for
556+exception ids. It is used as the base class for all exceptions thrown by the
557+@ref basic_json class. This class can hence be used as "wildcard" to catch
558+exceptions.
559+
560+Subclasses:
561+- @ref parse_error for exceptions indicating a parse error
562+- @ref invalid_iterator for exceptions indicating errors with iterators
563+- @ref type_error for exceptions indicating executing a member function with
564+ a wrong type
565+- @ref out_of_range for exceptions indicating access out of the defined range
566+- @ref other_error for exceptions indicating other library errors
567+
568+@internal
569+@note To have nothrow-copy-constructible exceptions, we internally use
570+ `std::runtime_error` which can cope with arbitrary-length error messages.
571+ Intermediate strings are built with static functions and then passed to
572+ the actual constructor.
573+@endinternal
574+
575+@liveexample{The following code shows how arbitrary library exceptions can be
576+caught.,exception}
577+
578+@since version 3.0.0
579+*/
580+class exception : public std::exception
581+{
582+ public:
583+ /// returns the explanatory string
584+ const char* what() const noexcept override
585+ {
586+ return m.what();
587+ }
588+
589+ /// the id of the exception
590+ const int id;
591+
592+ protected:
593+ exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
594+
595+ static std::string name(const std::string& ename, int id_)
596+ {
597+ return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
598+ }
599+
600+ private:
601+ /// an exception object as storage for error messages
602+ std::runtime_error m;
603+};
604+
605+/*!
606+@brief exception indicating a parse error
607+
608+This exception is thrown by the library when a parse error occurs. Parse errors
609+can occur during the deserialization of JSON text, CBOR, MessagePack, as well
610+as when using JSON Patch.
611+
612+Member @a byte holds the byte index of the last read character in the input
613+file.
614+
615+Exceptions have ids 1xx.
616+
617+name / id | example message | description
618+------------------------------ | --------------- | -------------------------
619+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.
620+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.
621+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.
622+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.
623+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.
624+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`.
625+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.
626+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.
627+json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
628+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.
629+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.
630+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.
631+
632+@note For an input with n bytes, 1 is the index of the first character and n+1
633+ is the index of the terminating null byte or the end of file. This also
634+ holds true when reading a byte vector (CBOR or MessagePack).
635+
636+@liveexample{The following code shows how a `parse_error` exception can be
637+caught.,parse_error}
638+
639+@sa @ref exception for the base class of the library exceptions
640+@sa @ref invalid_iterator for exceptions indicating errors with iterators
641+@sa @ref type_error for exceptions indicating executing a member function with
642+ a wrong type
643+@sa @ref out_of_range for exceptions indicating access out of the defined range
644+@sa @ref other_error for exceptions indicating other library errors
645+
646+@since version 3.0.0
647+*/
648+class parse_error : public exception
649+{
650+ public:
651+ /*!
652+ @brief create a parse error exception
653+ @param[in] id_ the id of the exception
654+ @param[in] byte_ the byte index where the error occurred (or 0 if the
655+ position cannot be determined)
656+ @param[in] what_arg the explanatory string
657+ @return parse_error object
658+ */
659+ static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
660+ {
661+ std::string w = exception::name("parse_error", id_) + "parse error" +
662+ (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") +
663+ ": " + what_arg;
664+ return parse_error(id_, byte_, w.c_str());
665+ }
666+
667+ /*!
668+ @brief byte index of the parse error
669+
670+ The byte index of the last read character in the input file.
671+
672+ @note For an input with n bytes, 1 is the index of the first character and
673+ n+1 is the index of the terminating null byte or the end of file.
674+ This also holds true when reading a byte vector (CBOR or MessagePack).
675+ */
676+ const std::size_t byte;
677+
678+ private:
679+ parse_error(int id_, std::size_t byte_, const char* what_arg)
680+ : exception(id_, what_arg), byte(byte_) {}
681+};
682+
683+/*!
684+@brief exception indicating errors with iterators
685+
686+This exception is thrown if iterators passed to a library function do not match
687+the expected semantics.
688+
689+Exceptions have ids 2xx.
690+
691+name / id | example message | description
692+----------------------------------- | --------------- | -------------------------
693+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.
694+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.
695+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.
696+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.
697+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.
698+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.
699+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.
700+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.
701+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.
702+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.
703+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.
704+json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
705+json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
706+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().
707+
708+@liveexample{The following code shows how an `invalid_iterator` exception can be
709+caught.,invalid_iterator}
710+
711+@sa @ref exception for the base class of the library exceptions
712+@sa @ref parse_error for exceptions indicating a parse error
713+@sa @ref type_error for exceptions indicating executing a member function with
714+ a wrong type
715+@sa @ref out_of_range for exceptions indicating access out of the defined range
716+@sa @ref other_error for exceptions indicating other library errors
717+
718+@since version 3.0.0
719+*/
720+class invalid_iterator : public exception
721+{
722+ public:
723+ static invalid_iterator create(int id_, const std::string& what_arg)
724+ {
725+ std::string w = exception::name("invalid_iterator", id_) + what_arg;
726+ return invalid_iterator(id_, w.c_str());
727+ }
728+
729+ private:
730+ invalid_iterator(int id_, const char* what_arg)
731+ : exception(id_, what_arg) {}
732+};
733+
734+/*!
735+@brief exception indicating executing a member function with a wrong type
736+
737+This exception is thrown in case of a type error; that is, a library function is
738+executed on a JSON value whose type does not match the expected semantics.
739+
740+Exceptions have ids 3xx.
741+
742+name / id | example message | description
743+----------------------------- | --------------- | -------------------------
744+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.
745+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.
746+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&.
747+json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
748+json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
749+json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
750+json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
751+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.
752+json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
753+json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
754+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.
755+json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
756+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.
757+json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
758+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.
759+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. |
760+
761+@liveexample{The following code shows how a `type_error` exception can be
762+caught.,type_error}
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 out_of_range for exceptions indicating access out of the defined range
768+@sa @ref other_error for exceptions indicating other library errors
769+
770+@since version 3.0.0
771+*/
772+class type_error : public exception
773+{
774+ public:
775+ static type_error create(int id_, const std::string& what_arg)
776+ {
777+ std::string w = exception::name("type_error", id_) + what_arg;
778+ return type_error(id_, w.c_str());
779+ }
780+
781+ private:
782+ type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
783+};
784+
785+/*!
786+@brief exception indicating access out of the defined range
787+
788+This exception is thrown in case a library function is called on an input
789+parameter that exceeds the expected range, for instance in case of array
790+indices or nonexisting object keys.
791+
792+Exceptions have ids 4xx.
793+
794+name / id | example message | description
795+------------------------------- | --------------- | -------------------------
796+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.
797+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.
798+json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
799+json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
800+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.
801+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.
802+json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON only supports integers numbers up to 9223372036854775807. |
803+json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
804+
805+@liveexample{The following code shows how an `out_of_range` exception can be
806+caught.,out_of_range}
807+
808+@sa @ref exception for the base class of the library exceptions
809+@sa @ref parse_error for exceptions indicating a parse error
810+@sa @ref invalid_iterator for exceptions indicating errors with iterators
811+@sa @ref type_error for exceptions indicating executing a member function with
812+ a wrong type
813+@sa @ref other_error for exceptions indicating other library errors
814+
815+@since version 3.0.0
816+*/
817+class out_of_range : public exception
818+{
819+ public:
820+ static out_of_range create(int id_, const std::string& what_arg)
821+ {
822+ std::string w = exception::name("out_of_range", id_) + what_arg;
823+ return out_of_range(id_, w.c_str());
824+ }
825+
826+ private:
827+ out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
828+};
829+
830+/*!
831+@brief exception indicating other library errors
832+
833+This exception is thrown in case of errors that cannot be classified with the
834+other exception types.
835+
836+Exceptions have ids 5xx.
837+
838+name / id | example message | description
839+------------------------------ | --------------- | -------------------------
840+json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
841+
842+@sa @ref exception for the base class of the library exceptions
843+@sa @ref parse_error for exceptions indicating a parse error
844+@sa @ref invalid_iterator for exceptions indicating errors with iterators
845+@sa @ref type_error for exceptions indicating executing a member function with
846+ a wrong type
847+@sa @ref out_of_range for exceptions indicating access out of the defined range
848+
849+@liveexample{The following code shows how an `other_error` exception can be
850+caught.,other_error}
851+
852+@since version 3.0.0
853+*/
854+class other_error : public exception
855+{
856+ public:
857+ static other_error create(int id_, const std::string& what_arg)
858+ {
859+ std::string w = exception::name("other_error", id_) + what_arg;
860+ return other_error(id_, w.c_str());
861+ }
862+
863+ private:
864+ other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
865+};
866+}
867+}
868+
869+// #include <nlohmann/detail/value_t.hpp>
870+
871+
872+#include <array> // array
873+#include <ciso646> // and
874+#include <cstddef> // size_t
875+#include <cstdint> // uint8_t
876+
877+namespace nlohmann
878+{
879+namespace detail
880+{
881+///////////////////////////
882+// JSON type enumeration //
883+///////////////////////////
884+
885+/*!
886+@brief the JSON type enumeration
887+
888+This enumeration collects the different JSON types. It is internally used to
889+distinguish the stored values, and the functions @ref basic_json::is_null(),
890+@ref basic_json::is_object(), @ref basic_json::is_array(),
891+@ref basic_json::is_string(), @ref basic_json::is_boolean(),
892+@ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
893+@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
894+@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
895+@ref basic_json::is_structured() rely on it.
896+
897+@note There are three enumeration entries (number_integer, number_unsigned, and
898+number_float), because the library distinguishes these three types for numbers:
899+@ref basic_json::number_unsigned_t is used for unsigned integers,
900+@ref basic_json::number_integer_t is used for signed integers, and
901+@ref basic_json::number_float_t is used for floating-point numbers or to
902+approximate integers which do not fit in the limits of their respective type.
903+
904+@sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
905+value with the default value for a given type
906+
907+@since version 1.0.0
908+*/
909+enum class value_t : std::uint8_t
910+{
911+ null, ///< null value
912+ object, ///< object (unordered set of name/value pairs)
913+ array, ///< array (ordered collection of values)
914+ string, ///< string value
915+ boolean, ///< boolean value
916+ number_integer, ///< number value (signed integer)
917+ number_unsigned, ///< number value (unsigned integer)
918+ number_float, ///< number value (floating-point)
919+ discarded ///< discarded by the the parser callback function
920+};
921+
922+/*!
923+@brief comparison operator for JSON types
924+
925+Returns an ordering that is similar to Python:
926+- order: null < boolean < number < object < array < string
927+- furthermore, each type is not smaller than itself
928+- discarded values are not comparable
929+
930+@since version 1.0.0
931+*/
932+inline bool operator<(const value_t lhs, const value_t rhs) noexcept
933+{
934+ static constexpr std::array<std::uint8_t, 8> order = {{
935+ 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
936+ 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
937+ }
938+ };
939+
940+ const auto l_index = static_cast<std::size_t>(lhs);
941+ const auto r_index = static_cast<std::size_t>(rhs);
942+ return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
943+}
944+}
945+}
946+
947+// #include <nlohmann/detail/conversions/from_json.hpp>
948+
949+
950+#include <algorithm> // transform
951+#include <array> // array
952+#include <ciso646> // and, not
953+#include <forward_list> // forward_list
954+#include <iterator> // inserter, front_inserter, end
955+#include <map> // map
956+#include <string> // string
957+#include <tuple> // tuple, make_tuple
958+#include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
959+#include <unordered_map> // unordered_map
960+#include <utility> // pair, declval
961+#include <valarray> // valarray
962+
963+// #include <nlohmann/detail/exceptions.hpp>
964+
965+// #include <nlohmann/detail/macro_scope.hpp>
966+
967+// #include <nlohmann/detail/meta/cpp_future.hpp>
968+
969+// #include <nlohmann/detail/meta/type_traits.hpp>
970+
971+// #include <nlohmann/detail/value_t.hpp>
972+
973+
974+namespace nlohmann
975+{
976+namespace detail
977+{
978+template<typename BasicJsonType>
979+void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
980+{
981+ if (JSON_UNLIKELY(not j.is_null()))
982+ {
983+ JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
984+ }
985+ n = nullptr;
986+}
987+
988+// overloads for basic_json template parameters
989+template<typename BasicJsonType, typename ArithmeticType,
990+ enable_if_t<std::is_arithmetic<ArithmeticType>::value and
991+ not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
992+ int> = 0>
993+void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
994+{
995+ switch (static_cast<value_t>(j))
996+ {
997+ case value_t::number_unsigned:
998+ {
999+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
1000+ break;
1001+ }
1002+ case value_t::number_integer:
1003+ {
1004+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
1005+ break;
1006+ }
1007+ case value_t::number_float:
1008+ {
1009+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
1010+ break;
1011+ }
1012+
1013+ default:
1014+ JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
1015+ }
1016+}
1017+
1018+template<typename BasicJsonType>
1019+void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
1020+{
1021+ if (JSON_UNLIKELY(not j.is_boolean()))
1022+ {
1023+ JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
1024+ }
1025+ b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
1026+}
1027+
1028+template<typename BasicJsonType>
1029+void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
1030+{
1031+ if (JSON_UNLIKELY(not j.is_string()))
1032+ {
1033+ JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
1034+ }
1035+ s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
1036+}
1037+
1038+template <
1039+ typename BasicJsonType, typename CompatibleStringType,
1040+ enable_if_t <
1041+ is_compatible_string_type<BasicJsonType, CompatibleStringType>::value and
1042+ not std::is_same<typename BasicJsonType::string_t,
1043+ CompatibleStringType>::value,
1044+ int > = 0 >
1045+void from_json(const BasicJsonType& j, CompatibleStringType& s)
1046+{
1047+ if (JSON_UNLIKELY(not j.is_string()))
1048+ {
1049+ JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
1050+ }
1051+
1052+ s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
1053+}
1054+
1055+template<typename BasicJsonType>
1056+void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
1057+{
1058+ get_arithmetic_value(j, val);
1059+}
1060+
1061+template<typename BasicJsonType>
1062+void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
1063+{
1064+ get_arithmetic_value(j, val);
1065+}
1066+
1067+template<typename BasicJsonType>
1068+void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
1069+{
1070+ get_arithmetic_value(j, val);
1071+}
1072+
1073+template<typename BasicJsonType, typename EnumType,
1074+ enable_if_t<std::is_enum<EnumType>::value, int> = 0>
1075+void from_json(const BasicJsonType& j, EnumType& e)
1076+{
1077+ typename std::underlying_type<EnumType>::type val;
1078+ get_arithmetic_value(j, val);
1079+ e = static_cast<EnumType>(val);
1080+}
1081+
1082+template<typename BasicJsonType>
1083+void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
1084+{
1085+ if (JSON_UNLIKELY(not j.is_array()))
1086+ {
1087+ JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1088+ }
1089+ arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
1090+}
1091+
1092+// forward_list doesn't have an insert method
1093+template<typename BasicJsonType, typename T, typename Allocator,
1094+ enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
1095+void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
1096+{
1097+ if (JSON_UNLIKELY(not j.is_array()))
1098+ {
1099+ JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1100+ }
1101+ std::transform(j.rbegin(), j.rend(),
1102+ std::front_inserter(l), [](const BasicJsonType & i)
1103+ {
1104+ return i.template get<T>();
1105+ });
1106+}
1107+
1108+// valarray doesn't have an insert method
1109+template<typename BasicJsonType, typename T,
1110+ enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
1111+void from_json(const BasicJsonType& j, std::valarray<T>& l)
1112+{
1113+ if (JSON_UNLIKELY(not j.is_array()))
1114+ {
1115+ JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1116+ }
1117+ l.resize(j.size());
1118+ std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
1119+}
1120+
1121+template<typename BasicJsonType, typename CompatibleArrayType>
1122+void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/)
1123+{
1124+ using std::end;
1125+
1126+ std::transform(j.begin(), j.end(),
1127+ std::inserter(arr, end(arr)), [](const BasicJsonType & i)
1128+ {
1129+ // get<BasicJsonType>() returns *this, this won't call a from_json
1130+ // method when value_type is BasicJsonType
1131+ return i.template get<typename CompatibleArrayType::value_type>();
1132+ });
1133+}
1134+
1135+template<typename BasicJsonType, typename CompatibleArrayType>
1136+auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/)
1137+-> decltype(
1138+ arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
1139+ void())
1140+{
1141+ using std::end;
1142+
1143+ arr.reserve(j.size());
1144+ std::transform(j.begin(), j.end(),
1145+ std::inserter(arr, end(arr)), [](const BasicJsonType & i)
1146+ {
1147+ // get<BasicJsonType>() returns *this, this won't call a from_json
1148+ // method when value_type is BasicJsonType
1149+ return i.template get<typename CompatibleArrayType::value_type>();
1150+ });
1151+}
1152+
1153+template<typename BasicJsonType, typename T, std::size_t N>
1154+void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/)
1155+{
1156+ for (std::size_t i = 0; i < N; ++i)
1157+ {
1158+ arr[i] = j.at(i).template get<T>();
1159+ }
1160+}
1161+
1162+template <
1163+ typename BasicJsonType, typename CompatibleArrayType,
1164+ enable_if_t <
1165+ is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
1166+ not std::is_same<typename BasicJsonType::array_t,
1167+ CompatibleArrayType>::value and
1168+ std::is_constructible <
1169+ BasicJsonType, typename CompatibleArrayType::value_type >::value,
1170+ int > = 0 >
1171+void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
1172+{
1173+ if (JSON_UNLIKELY(not j.is_array()))
1174+ {
1175+ JSON_THROW(type_error::create(302, "type must be array, but is " +
1176+ std::string(j.type_name())));
1177+ }
1178+
1179+ from_json_array_impl(j, arr, priority_tag<2> {});
1180+}
1181+
1182+template<typename BasicJsonType, typename CompatibleObjectType,
1183+ enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
1184+void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
1185+{
1186+ if (JSON_UNLIKELY(not j.is_object()))
1187+ {
1188+ JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
1189+ }
1190+
1191+ auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
1192+ using value_type = typename CompatibleObjectType::value_type;
1193+ std::transform(
1194+ inner_object->begin(), inner_object->end(),
1195+ std::inserter(obj, obj.begin()),
1196+ [](typename BasicJsonType::object_t::value_type const & p)
1197+ {
1198+ return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>());
1199+ });
1200+}
1201+
1202+// overload for arithmetic types, not chosen for basic_json template arguments
1203+// (BooleanType, etc..); note: Is it really necessary to provide explicit
1204+// overloads for boolean_t etc. in case of a custom BooleanType which is not
1205+// an arithmetic type?
1206+template<typename BasicJsonType, typename ArithmeticType,
1207+ enable_if_t <
1208+ std::is_arithmetic<ArithmeticType>::value and
1209+ not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
1210+ not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
1211+ not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
1212+ not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
1213+ int> = 0>
1214+void from_json(const BasicJsonType& j, ArithmeticType& val)
1215+{
1216+ switch (static_cast<value_t>(j))
1217+ {
1218+ case value_t::number_unsigned:
1219+ {
1220+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
1221+ break;
1222+ }
1223+ case value_t::number_integer:
1224+ {
1225+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
1226+ break;
1227+ }
1228+ case value_t::number_float:
1229+ {
1230+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
1231+ break;
1232+ }
1233+ case value_t::boolean:
1234+ {
1235+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
1236+ break;
1237+ }
1238+
1239+ default:
1240+ JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
1241+ }
1242+}
1243+
1244+template<typename BasicJsonType, typename A1, typename A2>
1245+void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
1246+{
1247+ p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
1248+}
1249+
1250+template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
1251+void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>)
1252+{
1253+ t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
1254+}
1255+
1256+template<typename BasicJsonType, typename... Args>
1257+void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
1258+{
1259+ from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
1260+}
1261+
1262+template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
1263+ typename = enable_if_t<not std::is_constructible<
1264+ typename BasicJsonType::string_t, Key>::value>>
1265+void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
1266+{
1267+ if (JSON_UNLIKELY(not j.is_array()))
1268+ {
1269+ JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1270+ }
1271+ for (const auto& p : j)
1272+ {
1273+ if (JSON_UNLIKELY(not p.is_array()))
1274+ {
1275+ JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
1276+ }
1277+ m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
1278+ }
1279+}
1280+
1281+template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
1282+ typename = enable_if_t<not std::is_constructible<
1283+ typename BasicJsonType::string_t, Key>::value>>
1284+void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
1285+{
1286+ if (JSON_UNLIKELY(not j.is_array()))
1287+ {
1288+ JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1289+ }
1290+ for (const auto& p : j)
1291+ {
1292+ if (JSON_UNLIKELY(not p.is_array()))
1293+ {
1294+ JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
1295+ }
1296+ m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
1297+ }
1298+}
1299+
1300+struct from_json_fn
1301+{
1302+ private:
1303+ template<typename BasicJsonType, typename T>
1304+ auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const
1305+ noexcept(noexcept(from_json(j, val)))
1306+ -> decltype(from_json(j, val), void())
1307+ {
1308+ return from_json(j, val);
1309+ }
1310+
1311+ template<typename BasicJsonType, typename T>
1312+ void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept
1313+ {
1314+ static_assert(sizeof(BasicJsonType) == 0,
1315+ "could not find from_json() method in T's namespace");
1316+#ifdef _MSC_VER
1317+ // MSVC does not show a stacktrace for the above assert
1318+ using decayed = uncvref_t<T>;
1319+ static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
1320+ "forcing MSVC stacktrace to show which T we're talking about.");
1321+#endif
1322+ }
1323+
1324+ public:
1325+ template<typename BasicJsonType, typename T>
1326+ void operator()(const BasicJsonType& j, T& val) const
1327+ noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
1328+ {
1329+ return call(j, val, priority_tag<1> {});
1330+ }
1331+};
1332+}
1333+
1334+/// namespace to hold default `from_json` function
1335+/// to see why this is required:
1336+/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
1337+namespace
1338+{
1339+constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
1340+}
1341+}
1342+
1343+// #include <nlohmann/detail/conversions/to_json.hpp>
1344+
1345+
1346+#include <ciso646> // or, and, not
1347+#include <iterator> // begin, end
1348+#include <tuple> // tuple, get
1349+#include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
1350+#include <utility> // move, forward, declval, pair
1351+#include <valarray> // valarray
1352+#include <vector> // vector
1353+
1354+// #include <nlohmann/detail/meta/cpp_future.hpp>
1355+
1356+// #include <nlohmann/detail/meta/type_traits.hpp>
1357+
1358+// #include <nlohmann/detail/value_t.hpp>
1359+
1360+// #include <nlohmann/detail/iterators/iteration_proxy.hpp>
1361+
1362+
1363+#include <cstddef> // size_t
1364+#include <string> // string, to_string
1365+#include <iterator> // input_iterator_tag
1366+
1367+// #include <nlohmann/detail/value_t.hpp>
1368+
1369+
1370+namespace nlohmann
1371+{
1372+namespace detail
1373+{
1374+/// proxy class for the items() function
1375+template<typename IteratorType> class iteration_proxy
1376+{
1377+ private:
1378+ /// helper class for iteration
1379+ class iteration_proxy_internal
1380+ {
1381+ public:
1382+ using difference_type = std::ptrdiff_t;
1383+ using value_type = iteration_proxy_internal;
1384+ using pointer = iteration_proxy_internal*;
1385+ using reference = iteration_proxy_internal&;
1386+ using iterator_category = std::input_iterator_tag;
1387+
1388+ private:
1389+ /// the iterator
1390+ IteratorType anchor;
1391+ /// an index for arrays (used to create key names)
1392+ std::size_t array_index = 0;
1393+ /// last stringified array index
1394+ mutable std::size_t array_index_last = 0;
1395+ /// a string representation of the array index
1396+ mutable std::string array_index_str = "0";
1397+ /// an empty string (to return a reference for primitive values)
1398+ const std::string empty_str = "";
1399+
1400+ public:
1401+ explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {}
1402+
1403+ iteration_proxy_internal(const iteration_proxy_internal&) = default;
1404+ iteration_proxy_internal& operator=(const iteration_proxy_internal&) = default;
1405+
1406+ /// dereference operator (needed for range-based for)
1407+ iteration_proxy_internal& operator*()
1408+ {
1409+ return *this;
1410+ }
1411+
1412+ /// increment operator (needed for range-based for)
1413+ iteration_proxy_internal& operator++()
1414+ {
1415+ ++anchor;
1416+ ++array_index;
1417+
1418+ return *this;
1419+ }
1420+
1421+ /// equality operator (needed for InputIterator)
1422+ bool operator==(const iteration_proxy_internal& o) const noexcept
1423+ {
1424+ return anchor == o.anchor;
1425+ }
1426+
1427+ /// inequality operator (needed for range-based for)
1428+ bool operator!=(const iteration_proxy_internal& o) const noexcept
1429+ {
1430+ return anchor != o.anchor;
1431+ }
1432+
1433+ /// return key of the iterator
1434+ const std::string& key() const
1435+ {
1436+ assert(anchor.m_object != nullptr);
1437+
1438+ switch (anchor.m_object->type())
1439+ {
1440+ // use integer array index as key
1441+ case value_t::array:
1442+ {
1443+ if (array_index != array_index_last)
1444+ {
1445+ array_index_str = std::to_string(array_index);
1446+ array_index_last = array_index;
1447+ }
1448+ return array_index_str;
1449+ }
1450+
1451+ // use key from the object
1452+ case value_t::object:
1453+ return anchor.key();
1454+
1455+ // use an empty key for all primitive types
1456+ default:
1457+ return empty_str;
1458+ }
1459+ }
1460+
1461+ /// return value of the iterator
1462+ typename IteratorType::reference value() const
1463+ {
1464+ return anchor.value();
1465+ }
1466+ };
1467+
1468+ /// the container to iterate
1469+ typename IteratorType::reference container;
1470+
1471+ public:
1472+ /// construct iteration proxy from a container
1473+ explicit iteration_proxy(typename IteratorType::reference cont) noexcept
1474+ : container(cont) {}
1475+
1476+ /// return iterator begin (needed for range-based for)
1477+ iteration_proxy_internal begin() noexcept
1478+ {
1479+ return iteration_proxy_internal(container.begin());
1480+ }
1481+
1482+ /// return iterator end (needed for range-based for)
1483+ iteration_proxy_internal end() noexcept
1484+ {
1485+ return iteration_proxy_internal(container.end());
1486+ }
1487+};
1488+}
1489+}
1490+
1491+
1492+namespace nlohmann
1493+{
1494+namespace detail
1495+{
1496+//////////////////
1497+// constructors //
1498+//////////////////
1499+
1500+template<value_t> struct external_constructor;
1501+
1502+template<>
1503+struct external_constructor<value_t::boolean>
1504+{
1505+ template<typename BasicJsonType>
1506+ static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
1507+ {
1508+ j.m_type = value_t::boolean;
1509+ j.m_value = b;
1510+ j.assert_invariant();
1511+ }
1512+};
1513+
1514+template<>
1515+struct external_constructor<value_t::string>
1516+{
1517+ template<typename BasicJsonType>
1518+ static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
1519+ {
1520+ j.m_type = value_t::string;
1521+ j.m_value = s;
1522+ j.assert_invariant();
1523+ }
1524+
1525+ template<typename BasicJsonType>
1526+ static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
1527+ {
1528+ j.m_type = value_t::string;
1529+ j.m_value = std::move(s);
1530+ j.assert_invariant();
1531+ }
1532+
1533+ template<typename BasicJsonType, typename CompatibleStringType,
1534+ enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
1535+ int> = 0>
1536+ static void construct(BasicJsonType& j, const CompatibleStringType& str)
1537+ {
1538+ j.m_type = value_t::string;
1539+ j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
1540+ j.assert_invariant();
1541+ }
1542+};
1543+
1544+template<>
1545+struct external_constructor<value_t::number_float>
1546+{
1547+ template<typename BasicJsonType>
1548+ static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
1549+ {
1550+ j.m_type = value_t::number_float;
1551+ j.m_value = val;
1552+ j.assert_invariant();
1553+ }
1554+};
1555+
1556+template<>
1557+struct external_constructor<value_t::number_unsigned>
1558+{
1559+ template<typename BasicJsonType>
1560+ static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
1561+ {
1562+ j.m_type = value_t::number_unsigned;
1563+ j.m_value = val;
1564+ j.assert_invariant();
1565+ }
1566+};
1567+
1568+template<>
1569+struct external_constructor<value_t::number_integer>
1570+{
1571+ template<typename BasicJsonType>
1572+ static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
1573+ {
1574+ j.m_type = value_t::number_integer;
1575+ j.m_value = val;
1576+ j.assert_invariant();
1577+ }
1578+};
1579+
1580+template<>
1581+struct external_constructor<value_t::array>
1582+{
1583+ template<typename BasicJsonType>
1584+ static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
1585+ {
1586+ j.m_type = value_t::array;
1587+ j.m_value = arr;
1588+ j.assert_invariant();
1589+ }
1590+
1591+ template<typename BasicJsonType>
1592+ static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
1593+ {
1594+ j.m_type = value_t::array;
1595+ j.m_value = std::move(arr);
1596+ j.assert_invariant();
1597+ }
1598+
1599+ template<typename BasicJsonType, typename CompatibleArrayType,
1600+ enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
1601+ int> = 0>
1602+ static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
1603+ {
1604+ using std::begin;
1605+ using std::end;
1606+ j.m_type = value_t::array;
1607+ j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
1608+ j.assert_invariant();
1609+ }
1610+
1611+ template<typename BasicJsonType>
1612+ static void construct(BasicJsonType& j, const std::vector<bool>& arr)
1613+ {
1614+ j.m_type = value_t::array;
1615+ j.m_value = value_t::array;
1616+ j.m_value.array->reserve(arr.size());
1617+ for (const bool x : arr)
1618+ {
1619+ j.m_value.array->push_back(x);
1620+ }
1621+ j.assert_invariant();
1622+ }
1623+
1624+ template<typename BasicJsonType, typename T,
1625+ enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
1626+ static void construct(BasicJsonType& j, const std::valarray<T>& arr)
1627+ {
1628+ j.m_type = value_t::array;
1629+ j.m_value = value_t::array;
1630+ j.m_value.array->resize(arr.size());
1631+ std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
1632+ j.assert_invariant();
1633+ }
1634+};
1635+
1636+template<>
1637+struct external_constructor<value_t::object>
1638+{
1639+ template<typename BasicJsonType>
1640+ static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
1641+ {
1642+ j.m_type = value_t::object;
1643+ j.m_value = obj;
1644+ j.assert_invariant();
1645+ }
1646+
1647+ template<typename BasicJsonType>
1648+ static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
1649+ {
1650+ j.m_type = value_t::object;
1651+ j.m_value = std::move(obj);
1652+ j.assert_invariant();
1653+ }
1654+
1655+ template<typename BasicJsonType, typename CompatibleObjectType,
1656+ enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
1657+ static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
1658+ {
1659+ using std::begin;
1660+ using std::end;
1661+
1662+ j.m_type = value_t::object;
1663+ j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
1664+ j.assert_invariant();
1665+ }
1666+};
1667+
1668+/////////////
1669+// to_json //
1670+/////////////
1671+
1672+template<typename BasicJsonType, typename T,
1673+ enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
1674+void to_json(BasicJsonType& j, T b) noexcept
1675+{
1676+ external_constructor<value_t::boolean>::construct(j, b);
1677+}
1678+
1679+template<typename BasicJsonType, typename CompatibleString,
1680+ enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
1681+void to_json(BasicJsonType& j, const CompatibleString& s)
1682+{
1683+ external_constructor<value_t::string>::construct(j, s);
1684+}
1685+
1686+template<typename BasicJsonType>
1687+void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
1688+{
1689+ external_constructor<value_t::string>::construct(j, std::move(s));
1690+}
1691+
1692+template<typename BasicJsonType, typename FloatType,
1693+ enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
1694+void to_json(BasicJsonType& j, FloatType val) noexcept
1695+{
1696+ external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
1697+}
1698+
1699+template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
1700+ enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
1701+void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
1702+{
1703+ external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
1704+}
1705+
1706+template<typename BasicJsonType, typename CompatibleNumberIntegerType,
1707+ enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
1708+void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
1709+{
1710+ external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
1711+}
1712+
1713+template<typename BasicJsonType, typename EnumType,
1714+ enable_if_t<std::is_enum<EnumType>::value, int> = 0>
1715+void to_json(BasicJsonType& j, EnumType e) noexcept
1716+{
1717+ using underlying_type = typename std::underlying_type<EnumType>::type;
1718+ external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
1719+}
1720+
1721+template<typename BasicJsonType>
1722+void to_json(BasicJsonType& j, const std::vector<bool>& e)
1723+{
1724+ external_constructor<value_t::array>::construct(j, e);
1725+}
1726+
1727+template<typename BasicJsonType, typename CompatibleArrayType,
1728+ enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
1729+ std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
1730+ int> = 0>
1731+void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
1732+{
1733+ external_constructor<value_t::array>::construct(j, arr);
1734+}
1735+
1736+template<typename BasicJsonType, typename T,
1737+ enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
1738+void to_json(BasicJsonType& j, const std::valarray<T>& arr)
1739+{
1740+ external_constructor<value_t::array>::construct(j, std::move(arr));
1741+}
1742+
1743+template<typename BasicJsonType>
1744+void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
1745+{
1746+ external_constructor<value_t::array>::construct(j, std::move(arr));
1747+}
1748+
1749+template<typename BasicJsonType, typename CompatibleObjectType,
1750+ enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
1751+void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
1752+{
1753+ external_constructor<value_t::object>::construct(j, obj);
1754+}
1755+
1756+template<typename BasicJsonType>
1757+void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
1758+{
1759+ external_constructor<value_t::object>::construct(j, std::move(obj));
1760+}
1761+
1762+template<typename BasicJsonType, typename T, std::size_t N,
1763+ enable_if_t<not std::is_constructible<typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0>
1764+void to_json(BasicJsonType& j, T (&arr)[N])
1765+{
1766+ external_constructor<value_t::array>::construct(j, arr);
1767+}
1768+
1769+template<typename BasicJsonType, typename... Args>
1770+void to_json(BasicJsonType& j, const std::pair<Args...>& p)
1771+{
1772+ j = {p.first, p.second};
1773+}
1774+
1775+// for https://github.com/nlohmann/json/pull/1134
1776+template<typename BasicJsonType, typename T,
1777+ enable_if_t<std::is_same<T, typename iteration_proxy<typename BasicJsonType::iterator>::iteration_proxy_internal>::value, int> = 0>
1778+void to_json(BasicJsonType& j, T b) noexcept
1779+{
1780+ j = {{b.key(), b.value()}};
1781+}
1782+
1783+template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
1784+void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>)
1785+{
1786+ j = {std::get<Idx>(t)...};
1787+}
1788+
1789+template<typename BasicJsonType, typename... Args>
1790+void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
1791+{
1792+ to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
1793+}
1794+
1795+struct to_json_fn
1796+{
1797+ private:
1798+ template<typename BasicJsonType, typename T>
1799+ auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
1800+ -> decltype(to_json(j, std::forward<T>(val)), void())
1801+ {
1802+ return to_json(j, std::forward<T>(val));
1803+ }
1804+
1805+ template<typename BasicJsonType, typename T>
1806+ void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept
1807+ {
1808+ static_assert(sizeof(BasicJsonType) == 0,
1809+ "could not find to_json() method in T's namespace");
1810+
1811+#ifdef _MSC_VER
1812+ // MSVC does not show a stacktrace for the above assert
1813+ using decayed = uncvref_t<T>;
1814+ static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
1815+ "forcing MSVC stacktrace to show which T we're talking about.");
1816+#endif
1817+ }
1818+
1819+ public:
1820+ template<typename BasicJsonType, typename T>
1821+ void operator()(BasicJsonType& j, T&& val) const
1822+ noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
1823+ {
1824+ return call(j, std::forward<T>(val), priority_tag<1> {});
1825+ }
1826+};
1827+}
1828+
1829+/// namespace to hold default `to_json` function
1830+namespace
1831+{
1832+constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
1833+}
1834+}
1835+
1836+// #include <nlohmann/detail/input/input_adapters.hpp>
1837+
1838+
1839+#include <cassert> // assert
1840+#include <cstddef> // size_t
1841+#include <cstring> // strlen
1842+#include <istream> // istream
1843+#include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
1844+#include <memory> // shared_ptr, make_shared, addressof
1845+#include <numeric> // accumulate
1846+#include <string> // string, char_traits
1847+#include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
1848+#include <utility> // pair, declval
1849+
1850+// #include <nlohmann/detail/macro_scope.hpp>
1851+
1852+
1853+namespace nlohmann
1854+{
1855+namespace detail
1856+{
1857+/// the supported input formats
1858+enum class input_format_t { json, cbor, msgpack, ubjson };
1859+
1860+////////////////////
1861+// input adapters //
1862+////////////////////
1863+
1864+/*!
1865+@brief abstract input adapter interface
1866+
1867+Produces a stream of std::char_traits<char>::int_type characters from a
1868+std::istream, a buffer, or some other input type. Accepts the return of
1869+exactly one non-EOF character for future input. The int_type characters
1870+returned consist of all valid char values as positive values (typically
1871+unsigned char), plus an EOF value outside that range, specified by the value
1872+of the function std::char_traits<char>::eof(). This value is typically -1, but
1873+could be any arbitrary value which is not a valid char value.
1874+*/
1875+struct input_adapter_protocol
1876+{
1877+ /// get a character [0,255] or std::char_traits<char>::eof().
1878+ virtual std::char_traits<char>::int_type get_character() = 0;
1879+ virtual ~input_adapter_protocol() = default;
1880+};
1881+
1882+/// a type to simplify interfaces
1883+using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
1884+
1885+/*!
1886+Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
1887+beginning of input. Does not support changing the underlying std::streambuf
1888+in mid-input. Maintains underlying std::istream and std::streambuf to support
1889+subsequent use of standard std::istream operations to process any input
1890+characters following those used in parsing the JSON input. Clears the
1891+std::istream flags; any input errors (e.g., EOF) will be detected by the first
1892+subsequent call for input from the std::istream.
1893+*/
1894+class input_stream_adapter : public input_adapter_protocol
1895+{
1896+ public:
1897+ ~input_stream_adapter() override
1898+ {
1899+ // clear stream flags; we use underlying streambuf I/O, do not
1900+ // maintain ifstream flags
1901+ is.clear();
1902+ }
1903+
1904+ explicit input_stream_adapter(std::istream& i)
1905+ : is(i), sb(*i.rdbuf())
1906+ {}
1907+
1908+ // delete because of pointer members
1909+ input_stream_adapter(const input_stream_adapter&) = delete;
1910+ input_stream_adapter& operator=(input_stream_adapter&) = delete;
1911+
1912+ // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
1913+ // ensure that std::char_traits<char>::eof() and the character 0xFF do not
1914+ // end up as the same value, eg. 0xFFFFFFFF.
1915+ std::char_traits<char>::int_type get_character() override
1916+ {
1917+ return sb.sbumpc();
1918+ }
1919+
1920+ private:
1921+ /// the associated input stream
1922+ std::istream& is;
1923+ std::streambuf& sb;
1924+};
1925+
1926+/// input adapter for buffer input
1927+class input_buffer_adapter : public input_adapter_protocol
1928+{
1929+ public:
1930+ input_buffer_adapter(const char* b, const std::size_t l)
1931+ : cursor(b), limit(b + l)
1932+ {}
1933+
1934+ // delete because of pointer members
1935+ input_buffer_adapter(const input_buffer_adapter&) = delete;
1936+ input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
1937+
1938+ std::char_traits<char>::int_type get_character() noexcept override
1939+ {
1940+ if (JSON_LIKELY(cursor < limit))
1941+ {
1942+ return std::char_traits<char>::to_int_type(*(cursor++));
1943+ }
1944+
1945+ return std::char_traits<char>::eof();
1946+ }
1947+
1948+ private:
1949+ /// pointer to the current character
1950+ const char* cursor;
1951+ /// pointer past the last character
1952+ const char* const limit;
1953+};
1954+
1955+template<typename WideStringType>
1956+class wide_string_input_adapter : public input_adapter_protocol
1957+{
1958+ public:
1959+ explicit wide_string_input_adapter(const WideStringType& w) : str(w) {}
1960+
1961+ std::char_traits<char>::int_type get_character() noexcept override
1962+ {
1963+ // check if buffer needs to be filled
1964+ if (utf8_bytes_index == utf8_bytes_filled)
1965+ {
1966+ if (sizeof(typename WideStringType::value_type) == 2)
1967+ {
1968+ fill_buffer_utf16();
1969+ }
1970+ else
1971+ {
1972+ fill_buffer_utf32();
1973+ }
1974+
1975+ assert(utf8_bytes_filled > 0);
1976+ assert(utf8_bytes_index == 0);
1977+ }
1978+
1979+ // use buffer
1980+ assert(utf8_bytes_filled > 0);
1981+ assert(utf8_bytes_index < utf8_bytes_filled);
1982+ return utf8_bytes[utf8_bytes_index++];
1983+ }
1984+
1985+ private:
1986+ void fill_buffer_utf16()
1987+ {
1988+ utf8_bytes_index = 0;
1989+
1990+ if (current_wchar == str.size())
1991+ {
1992+ utf8_bytes[0] = std::char_traits<char>::eof();
1993+ utf8_bytes_filled = 1;
1994+ }
1995+ else
1996+ {
1997+ // get the current character
1998+ const int wc = static_cast<int>(str[current_wchar++]);
1999+
2000+ // UTF-16 to UTF-8 encoding
2001+ if (wc < 0x80)
2002+ {
2003+ utf8_bytes[0] = wc;
2004+ utf8_bytes_filled = 1;
2005+ }
2006+ else if (wc <= 0x7FF)
2007+ {
2008+ utf8_bytes[0] = 0xC0 | ((wc >> 6));
2009+ utf8_bytes[1] = 0x80 | (wc & 0x3F);
2010+ utf8_bytes_filled = 2;
2011+ }
2012+ else if (0xD800 > wc or wc >= 0xE000)
2013+ {
2014+ utf8_bytes[0] = 0xE0 | ((wc >> 12));
2015+ utf8_bytes[1] = 0x80 | ((wc >> 6) & 0x3F);
2016+ utf8_bytes[2] = 0x80 | (wc & 0x3F);
2017+ utf8_bytes_filled = 3;
2018+ }
2019+ else
2020+ {
2021+ if (current_wchar < str.size())
2022+ {
2023+ const int wc2 = static_cast<int>(str[current_wchar++]);
2024+ const int charcode = 0x10000 + (((wc & 0x3FF) << 10) | (wc2 & 0x3FF));
2025+ utf8_bytes[0] = 0xf0 | (charcode >> 18);
2026+ utf8_bytes[1] = 0x80 | ((charcode >> 12) & 0x3F);
2027+ utf8_bytes[2] = 0x80 | ((charcode >> 6) & 0x3F);
2028+ utf8_bytes[3] = 0x80 | (charcode & 0x3F);
2029+ utf8_bytes_filled = 4;
2030+ }
2031+ else
2032+ {
2033+ // unknown character
2034+ ++current_wchar;
2035+ utf8_bytes[0] = wc;
2036+ utf8_bytes_filled = 1;
2037+ }
2038+ }
2039+ }
2040+ }
2041+
2042+ void fill_buffer_utf32()
2043+ {
2044+ utf8_bytes_index = 0;
2045+
2046+ if (current_wchar == str.size())
2047+ {
2048+ utf8_bytes[0] = std::char_traits<char>::eof();
2049+ utf8_bytes_filled = 1;
2050+ }
2051+ else
2052+ {
2053+ // get the current character
2054+ const int wc = static_cast<int>(str[current_wchar++]);
2055+
2056+ // UTF-32 to UTF-8 encoding
2057+ if (wc < 0x80)
2058+ {
2059+ utf8_bytes[0] = wc;
2060+ utf8_bytes_filled = 1;
2061+ }
2062+ else if (wc <= 0x7FF)
2063+ {
2064+ utf8_bytes[0] = 0xC0 | ((wc >> 6) & 0x1F);
2065+ utf8_bytes[1] = 0x80 | (wc & 0x3F);
2066+ utf8_bytes_filled = 2;
2067+ }
2068+ else if (wc <= 0xFFFF)
2069+ {
2070+ utf8_bytes[0] = 0xE0 | ((wc >> 12) & 0x0F);
2071+ utf8_bytes[1] = 0x80 | ((wc >> 6) & 0x3F);
2072+ utf8_bytes[2] = 0x80 | (wc & 0x3F);
2073+ utf8_bytes_filled = 3;
2074+ }
2075+ else if (wc <= 0x10FFFF)
2076+ {
2077+ utf8_bytes[0] = 0xF0 | ((wc >> 18 ) & 0x07);
2078+ utf8_bytes[1] = 0x80 | ((wc >> 12) & 0x3F);
2079+ utf8_bytes[2] = 0x80 | ((wc >> 6) & 0x3F);
2080+ utf8_bytes[3] = 0x80 | (wc & 0x3F);
2081+ utf8_bytes_filled = 4;
2082+ }
2083+ else
2084+ {
2085+ // unknown character
2086+ utf8_bytes[0] = wc;
2087+ utf8_bytes_filled = 1;
2088+ }
2089+ }
2090+ }
2091+
2092+ private:
2093+ /// the wstring to process
2094+ const WideStringType& str;
2095+
2096+ /// index of the current wchar in str
2097+ std::size_t current_wchar = 0;
2098+
2099+ /// a buffer for UTF-8 bytes
2100+ std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
2101+
2102+ /// index to the utf8_codes array for the next valid byte
2103+ std::size_t utf8_bytes_index = 0;
2104+ /// number of valid bytes in the utf8_codes array
2105+ std::size_t utf8_bytes_filled = 0;
2106+};
2107+
2108+class input_adapter
2109+{
2110+ public:
2111+ // native support
2112+
2113+ /// input adapter for input stream
2114+ input_adapter(std::istream& i)
2115+ : ia(std::make_shared<input_stream_adapter>(i)) {}
2116+
2117+ /// input adapter for input stream
2118+ input_adapter(std::istream&& i)
2119+ : ia(std::make_shared<input_stream_adapter>(i)) {}
2120+
2121+ input_adapter(const std::wstring& ws)
2122+ : ia(std::make_shared<wide_string_input_adapter<std::wstring>>(ws)) {}
2123+
2124+ input_adapter(const std::u16string& ws)
2125+ : ia(std::make_shared<wide_string_input_adapter<std::u16string>>(ws)) {}
2126+
2127+ input_adapter(const std::u32string& ws)
2128+ : ia(std::make_shared<wide_string_input_adapter<std::u32string>>(ws)) {}
2129+
2130+ /// input adapter for buffer
2131+ template<typename CharT,
2132+ typename std::enable_if<
2133+ std::is_pointer<CharT>::value and
2134+ std::is_integral<typename std::remove_pointer<CharT>::type>::value and
2135+ sizeof(typename std::remove_pointer<CharT>::type) == 1,
2136+ int>::type = 0>
2137+ input_adapter(CharT b, std::size_t l)
2138+ : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
2139+
2140+ // derived support
2141+
2142+ /// input adapter for string literal
2143+ template<typename CharT,
2144+ typename std::enable_if<
2145+ std::is_pointer<CharT>::value and
2146+ std::is_integral<typename std::remove_pointer<CharT>::type>::value and
2147+ sizeof(typename std::remove_pointer<CharT>::type) == 1,
2148+ int>::type = 0>
2149+ input_adapter(CharT b)
2150+ : input_adapter(reinterpret_cast<const char*>(b),
2151+ std::strlen(reinterpret_cast<const char*>(b))) {}
2152+
2153+ /// input adapter for iterator range with contiguous storage
2154+ template<class IteratorType,
2155+ typename std::enable_if<
2156+ std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
2157+ int>::type = 0>
2158+ input_adapter(IteratorType first, IteratorType last)
2159+ {
2160+ // assertion to check that the iterator range is indeed contiguous,
2161+ // see http://stackoverflow.com/a/35008842/266378 for more discussion
2162+ assert(std::accumulate(
2163+ first, last, std::pair<bool, int>(true, 0),
2164+ [&first](std::pair<bool, int> res, decltype(*first) val)
2165+ {
2166+ res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
2167+ return res;
2168+ }).first);
2169+
2170+ // assertion to check that each element is 1 byte long
2171+ static_assert(
2172+ sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
2173+ "each element in the iterator range must have the size of 1 byte");
2174+
2175+ const auto len = static_cast<size_t>(std::distance(first, last));
2176+ if (JSON_LIKELY(len > 0))
2177+ {
2178+ // there is at least one element: use the address of first
2179+ ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
2180+ }
2181+ else
2182+ {
2183+ // the address of first cannot be used: use nullptr
2184+ ia = std::make_shared<input_buffer_adapter>(nullptr, len);
2185+ }
2186+ }
2187+
2188+ /// input adapter for array
2189+ template<class T, std::size_t N>
2190+ input_adapter(T (&array)[N])
2191+ : input_adapter(std::begin(array), std::end(array)) {}
2192+
2193+ /// input adapter for contiguous container
2194+ template<class ContiguousContainer, typename
2195+ std::enable_if<not std::is_pointer<ContiguousContainer>::value and
2196+ std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
2197+ int>::type = 0>
2198+ input_adapter(const ContiguousContainer& c)
2199+ : input_adapter(std::begin(c), std::end(c)) {}
2200+
2201+ operator input_adapter_t()
2202+ {
2203+ return ia;
2204+ }
2205+
2206+ private:
2207+ /// the actual adapter
2208+ input_adapter_t ia = nullptr;
2209+};
2210+}
2211+}
2212+
2213+// #include <nlohmann/detail/input/lexer.hpp>
2214+
2215+
2216+#include <clocale> // localeconv
2217+#include <cstddef> // size_t
2218+#include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
2219+#include <cstdio> // snprintf
2220+#include <initializer_list> // initializer_list
2221+#include <string> // char_traits, string
2222+#include <vector> // vector
2223+
2224+// #include <nlohmann/detail/macro_scope.hpp>
2225+
2226+// #include <nlohmann/detail/input/input_adapters.hpp>
2227+
2228+
2229+namespace nlohmann
2230+{
2231+namespace detail
2232+{
2233+///////////
2234+// lexer //
2235+///////////
2236+
2237+/*!
2238+@brief lexical analysis
2239+
2240+This class organizes the lexical analysis during JSON deserialization.
2241+*/
2242+template<typename BasicJsonType>
2243+class lexer
2244+{
2245+ using number_integer_t = typename BasicJsonType::number_integer_t;
2246+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
2247+ using number_float_t = typename BasicJsonType::number_float_t;
2248+ using string_t = typename BasicJsonType::string_t;
2249+
2250+ public:
2251+ /// token types for the parser
2252+ enum class token_type
2253+ {
2254+ uninitialized, ///< indicating the scanner is uninitialized
2255+ literal_true, ///< the `true` literal
2256+ literal_false, ///< the `false` literal
2257+ literal_null, ///< the `null` literal
2258+ value_string, ///< a string -- use get_string() for actual value
2259+ value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
2260+ value_integer, ///< a signed integer -- use get_number_integer() for actual value
2261+ value_float, ///< an floating point number -- use get_number_float() for actual value
2262+ begin_array, ///< the character for array begin `[`
2263+ begin_object, ///< the character for object begin `{`
2264+ end_array, ///< the character for array end `]`
2265+ end_object, ///< the character for object end `}`
2266+ name_separator, ///< the name separator `:`
2267+ value_separator, ///< the value separator `,`
2268+ parse_error, ///< indicating a parse error
2269+ end_of_input, ///< indicating the end of the input buffer
2270+ literal_or_value ///< a literal or the begin of a value (only for diagnostics)
2271+ };
2272+
2273+ /// return name of values of type token_type (only used for errors)
2274+ static const char* token_type_name(const token_type t) noexcept
2275+ {
2276+ switch (t)
2277+ {
2278+ case token_type::uninitialized:
2279+ return "<uninitialized>";
2280+ case token_type::literal_true:
2281+ return "true literal";
2282+ case token_type::literal_false:
2283+ return "false literal";
2284+ case token_type::literal_null:
2285+ return "null literal";
2286+ case token_type::value_string:
2287+ return "string literal";
2288+ case lexer::token_type::value_unsigned:
2289+ case lexer::token_type::value_integer:
2290+ case lexer::token_type::value_float:
2291+ return "number literal";
2292+ case token_type::begin_array:
2293+ return "'['";
2294+ case token_type::begin_object:
2295+ return "'{'";
2296+ case token_type::end_array:
2297+ return "']'";
2298+ case token_type::end_object:
2299+ return "'}'";
2300+ case token_type::name_separator:
2301+ return "':'";
2302+ case token_type::value_separator:
2303+ return "','";
2304+ case token_type::parse_error:
2305+ return "<parse error>";
2306+ case token_type::end_of_input:
2307+ return "end of input";
2308+ case token_type::literal_or_value:
2309+ return "'[', '{', or a literal";
2310+ // LCOV_EXCL_START
2311+ default: // catch non-enum values
2312+ return "unknown token";
2313+ // LCOV_EXCL_STOP
2314+ }
2315+ }
2316+
2317+ explicit lexer(detail::input_adapter_t&& adapter)
2318+ : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
2319+
2320+ // delete because of pointer members
2321+ lexer(const lexer&) = delete;
2322+ lexer& operator=(lexer&) = delete;
2323+
2324+ private:
2325+ /////////////////////
2326+ // locales
2327+ /////////////////////
2328+
2329+ /// return the locale-dependent decimal point
2330+ static char get_decimal_point() noexcept
2331+ {
2332+ const auto loc = localeconv();
2333+ assert(loc != nullptr);
2334+ return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
2335+ }
2336+
2337+ /////////////////////
2338+ // scan functions
2339+ /////////////////////
2340+
2341+ /*!
2342+ @brief get codepoint from 4 hex characters following `\u`
2343+
2344+ For input "\u c1 c2 c3 c4" the codepoint is:
2345+ (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
2346+ = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
2347+
2348+ Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
2349+ must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
2350+ conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
2351+ between the ASCII value of the character and the desired integer value.
2352+
2353+ @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
2354+ non-hex character)
2355+ */
2356+ int get_codepoint()
2357+ {
2358+ // this function only makes sense after reading `\u`
2359+ assert(current == 'u');
2360+ int codepoint = 0;
2361+
2362+ const auto factors = { 12, 8, 4, 0 };
2363+ for (const auto factor : factors)
2364+ {
2365+ get();
2366+
2367+ if (current >= '0' and current <= '9')
2368+ {
2369+ codepoint += ((current - 0x30) << factor);
2370+ }
2371+ else if (current >= 'A' and current <= 'F')
2372+ {
2373+ codepoint += ((current - 0x37) << factor);
2374+ }
2375+ else if (current >= 'a' and current <= 'f')
2376+ {
2377+ codepoint += ((current - 0x57) << factor);
2378+ }
2379+ else
2380+ {
2381+ return -1;
2382+ }
2383+ }
2384+
2385+ assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
2386+ return codepoint;
2387+ }
2388+
2389+ /*!
2390+ @brief check if the next byte(s) are inside a given range
2391+
2392+ Adds the current byte and, for each passed range, reads a new byte and
2393+ checks if it is inside the range. If a violation was detected, set up an
2394+ error message and return false. Otherwise, return true.
2395+
2396+ @param[in] ranges list of integers; interpreted as list of pairs of
2397+ inclusive lower and upper bound, respectively
2398+
2399+ @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
2400+ 1, 2, or 3 pairs. This precondition is enforced by an assertion.
2401+
2402+ @return true if and only if no range violation was detected
2403+ */
2404+ bool next_byte_in_range(std::initializer_list<int> ranges)
2405+ {
2406+ assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
2407+ add(current);
2408+
2409+ for (auto range = ranges.begin(); range != ranges.end(); ++range)
2410+ {
2411+ get();
2412+ if (JSON_LIKELY(*range <= current and current <= *(++range)))
2413+ {
2414+ add(current);
2415+ }
2416+ else
2417+ {
2418+ error_message = "invalid string: ill-formed UTF-8 byte";
2419+ return false;
2420+ }
2421+ }
2422+
2423+ return true;
2424+ }
2425+
2426+ /*!
2427+ @brief scan a string literal
2428+
2429+ This function scans a string according to Sect. 7 of RFC 7159. While
2430+ scanning, bytes are escaped and copied into buffer token_buffer. Then the
2431+ function returns successfully, token_buffer is *not* null-terminated (as it
2432+ may contain \0 bytes), and token_buffer.size() is the number of bytes in the
2433+ string.
2434+
2435+ @return token_type::value_string if string could be successfully scanned,
2436+ token_type::parse_error otherwise
2437+
2438+ @note In case of errors, variable error_message contains a textual
2439+ description.
2440+ */
2441+ token_type scan_string()
2442+ {
2443+ // reset token_buffer (ignore opening quote)
2444+ reset();
2445+
2446+ // we entered the function by reading an open quote
2447+ assert(current == '\"');
2448+
2449+ while (true)
2450+ {
2451+ // get next character
2452+ switch (get())
2453+ {
2454+ // end of file while parsing string
2455+ case std::char_traits<char>::eof():
2456+ {
2457+ error_message = "invalid string: missing closing quote";
2458+ return token_type::parse_error;
2459+ }
2460+
2461+ // closing quote
2462+ case '\"':
2463+ {
2464+ return token_type::value_string;
2465+ }
2466+
2467+ // escapes
2468+ case '\\':
2469+ {
2470+ switch (get())
2471+ {
2472+ // quotation mark
2473+ case '\"':
2474+ add('\"');
2475+ break;
2476+ // reverse solidus
2477+ case '\\':
2478+ add('\\');
2479+ break;
2480+ // solidus
2481+ case '/':
2482+ add('/');
2483+ break;
2484+ // backspace
2485+ case 'b':
2486+ add('\b');
2487+ break;
2488+ // form feed
2489+ case 'f':
2490+ add('\f');
2491+ break;
2492+ // line feed
2493+ case 'n':
2494+ add('\n');
2495+ break;
2496+ // carriage return
2497+ case 'r':
2498+ add('\r');
2499+ break;
2500+ // tab
2501+ case 't':
2502+ add('\t');
2503+ break;
2504+
2505+ // unicode escapes
2506+ case 'u':
2507+ {
2508+ const int codepoint1 = get_codepoint();
2509+ int codepoint = codepoint1; // start with codepoint1
2510+
2511+ if (JSON_UNLIKELY(codepoint1 == -1))
2512+ {
2513+ error_message = "invalid string: '\\u' must be followed by 4 hex digits";
2514+ return token_type::parse_error;
2515+ }
2516+
2517+ // check if code point is a high surrogate
2518+ if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
2519+ {
2520+ // expect next \uxxxx entry
2521+ if (JSON_LIKELY(get() == '\\' and get() == 'u'))
2522+ {
2523+ const int codepoint2 = get_codepoint();
2524+
2525+ if (JSON_UNLIKELY(codepoint2 == -1))
2526+ {
2527+ error_message = "invalid string: '\\u' must be followed by 4 hex digits";
2528+ return token_type::parse_error;
2529+ }
2530+
2531+ // check if codepoint2 is a low surrogate
2532+ if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
2533+ {
2534+ // overwrite codepoint
2535+ codepoint =
2536+ // high surrogate occupies the most significant 22 bits
2537+ (codepoint1 << 10)
2538+ // low surrogate occupies the least significant 15 bits
2539+ + codepoint2
2540+ // there is still the 0xD800, 0xDC00 and 0x10000 noise
2541+ // in the result so we have to subtract with:
2542+ // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
2543+ - 0x35FDC00;
2544+ }
2545+ else
2546+ {
2547+ error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
2548+ return token_type::parse_error;
2549+ }
2550+ }
2551+ else
2552+ {
2553+ error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
2554+ return token_type::parse_error;
2555+ }
2556+ }
2557+ else
2558+ {
2559+ if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
2560+ {
2561+ error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
2562+ return token_type::parse_error;
2563+ }
2564+ }
2565+
2566+ // result of the above calculation yields a proper codepoint
2567+ assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
2568+
2569+ // translate codepoint into bytes
2570+ if (codepoint < 0x80)
2571+ {
2572+ // 1-byte characters: 0xxxxxxx (ASCII)
2573+ add(codepoint);
2574+ }
2575+ else if (codepoint <= 0x7FF)
2576+ {
2577+ // 2-byte characters: 110xxxxx 10xxxxxx
2578+ add(0xC0 | (codepoint >> 6));
2579+ add(0x80 | (codepoint & 0x3F));
2580+ }
2581+ else if (codepoint <= 0xFFFF)
2582+ {
2583+ // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
2584+ add(0xE0 | (codepoint >> 12));
2585+ add(0x80 | ((codepoint >> 6) & 0x3F));
2586+ add(0x80 | (codepoint & 0x3F));
2587+ }
2588+ else
2589+ {
2590+ // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2591+ add(0xF0 | (codepoint >> 18));
2592+ add(0x80 | ((codepoint >> 12) & 0x3F));
2593+ add(0x80 | ((codepoint >> 6) & 0x3F));
2594+ add(0x80 | (codepoint & 0x3F));
2595+ }
2596+
2597+ break;
2598+ }
2599+
2600+ // other characters after escape
2601+ default:
2602+ error_message = "invalid string: forbidden character after backslash";
2603+ return token_type::parse_error;
2604+ }
2605+
2606+ break;
2607+ }
2608+
2609+ // invalid control characters
2610+ case 0x00:
2611+ case 0x01:
2612+ case 0x02:
2613+ case 0x03:
2614+ case 0x04:
2615+ case 0x05:
2616+ case 0x06:
2617+ case 0x07:
2618+ case 0x08:
2619+ case 0x09:
2620+ case 0x0A:
2621+ case 0x0B:
2622+ case 0x0C:
2623+ case 0x0D:
2624+ case 0x0E:
2625+ case 0x0F:
2626+ case 0x10:
2627+ case 0x11:
2628+ case 0x12:
2629+ case 0x13:
2630+ case 0x14:
2631+ case 0x15:
2632+ case 0x16:
2633+ case 0x17:
2634+ case 0x18:
2635+ case 0x19:
2636+ case 0x1A:
2637+ case 0x1B:
2638+ case 0x1C:
2639+ case 0x1D:
2640+ case 0x1E:
2641+ case 0x1F:
2642+ {
2643+ error_message = "invalid string: control character must be escaped";
2644+ return token_type::parse_error;
2645+ }
2646+
2647+ // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
2648+ case 0x20:
2649+ case 0x21:
2650+ case 0x23:
2651+ case 0x24:
2652+ case 0x25:
2653+ case 0x26:
2654+ case 0x27:
2655+ case 0x28:
2656+ case 0x29:
2657+ case 0x2A:
2658+ case 0x2B:
2659+ case 0x2C:
2660+ case 0x2D:
2661+ case 0x2E:
2662+ case 0x2F:
2663+ case 0x30:
2664+ case 0x31:
2665+ case 0x32:
2666+ case 0x33:
2667+ case 0x34:
2668+ case 0x35:
2669+ case 0x36:
2670+ case 0x37:
2671+ case 0x38:
2672+ case 0x39:
2673+ case 0x3A:
2674+ case 0x3B:
2675+ case 0x3C:
2676+ case 0x3D:
2677+ case 0x3E:
2678+ case 0x3F:
2679+ case 0x40:
2680+ case 0x41:
2681+ case 0x42:
2682+ case 0x43:
2683+ case 0x44:
2684+ case 0x45:
2685+ case 0x46:
2686+ case 0x47:
2687+ case 0x48:
2688+ case 0x49:
2689+ case 0x4A:
2690+ case 0x4B:
2691+ case 0x4C:
2692+ case 0x4D:
2693+ case 0x4E:
2694+ case 0x4F:
2695+ case 0x50:
2696+ case 0x51:
2697+ case 0x52:
2698+ case 0x53:
2699+ case 0x54:
2700+ case 0x55:
2701+ case 0x56:
2702+ case 0x57:
2703+ case 0x58:
2704+ case 0x59:
2705+ case 0x5A:
2706+ case 0x5B:
2707+ case 0x5D:
2708+ case 0x5E:
2709+ case 0x5F:
2710+ case 0x60:
2711+ case 0x61:
2712+ case 0x62:
2713+ case 0x63:
2714+ case 0x64:
2715+ case 0x65:
2716+ case 0x66:
2717+ case 0x67:
2718+ case 0x68:
2719+ case 0x69:
2720+ case 0x6A:
2721+ case 0x6B:
2722+ case 0x6C:
2723+ case 0x6D:
2724+ case 0x6E:
2725+ case 0x6F:
2726+ case 0x70:
2727+ case 0x71:
2728+ case 0x72:
2729+ case 0x73:
2730+ case 0x74:
2731+ case 0x75:
2732+ case 0x76:
2733+ case 0x77:
2734+ case 0x78:
2735+ case 0x79:
2736+ case 0x7A:
2737+ case 0x7B:
2738+ case 0x7C:
2739+ case 0x7D:
2740+ case 0x7E:
2741+ case 0x7F:
2742+ {
2743+ add(current);
2744+ break;
2745+ }
2746+
2747+ // U+0080..U+07FF: bytes C2..DF 80..BF
2748+ case 0xC2:
2749+ case 0xC3:
2750+ case 0xC4:
2751+ case 0xC5:
2752+ case 0xC6:
2753+ case 0xC7:
2754+ case 0xC8:
2755+ case 0xC9:
2756+ case 0xCA:
2757+ case 0xCB:
2758+ case 0xCC:
2759+ case 0xCD:
2760+ case 0xCE:
2761+ case 0xCF:
2762+ case 0xD0:
2763+ case 0xD1:
2764+ case 0xD2:
2765+ case 0xD3:
2766+ case 0xD4:
2767+ case 0xD5:
2768+ case 0xD6:
2769+ case 0xD7:
2770+ case 0xD8:
2771+ case 0xD9:
2772+ case 0xDA:
2773+ case 0xDB:
2774+ case 0xDC:
2775+ case 0xDD:
2776+ case 0xDE:
2777+ case 0xDF:
2778+ {
2779+ if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
2780+ {
2781+ return token_type::parse_error;
2782+ }
2783+ break;
2784+ }
2785+
2786+ // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
2787+ case 0xE0:
2788+ {
2789+ if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
2790+ {
2791+ return token_type::parse_error;
2792+ }
2793+ break;
2794+ }
2795+
2796+ // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
2797+ // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
2798+ case 0xE1:
2799+ case 0xE2:
2800+ case 0xE3:
2801+ case 0xE4:
2802+ case 0xE5:
2803+ case 0xE6:
2804+ case 0xE7:
2805+ case 0xE8:
2806+ case 0xE9:
2807+ case 0xEA:
2808+ case 0xEB:
2809+ case 0xEC:
2810+ case 0xEE:
2811+ case 0xEF:
2812+ {
2813+ if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
2814+ {
2815+ return token_type::parse_error;
2816+ }
2817+ break;
2818+ }
2819+
2820+ // U+D000..U+D7FF: bytes ED 80..9F 80..BF
2821+ case 0xED:
2822+ {
2823+ if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
2824+ {
2825+ return token_type::parse_error;
2826+ }
2827+ break;
2828+ }
2829+
2830+ // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
2831+ case 0xF0:
2832+ {
2833+ if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
2834+ {
2835+ return token_type::parse_error;
2836+ }
2837+ break;
2838+ }
2839+
2840+ // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
2841+ case 0xF1:
2842+ case 0xF2:
2843+ case 0xF3:
2844+ {
2845+ if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
2846+ {
2847+ return token_type::parse_error;
2848+ }
2849+ break;
2850+ }
2851+
2852+ // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
2853+ case 0xF4:
2854+ {
2855+ if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
2856+ {
2857+ return token_type::parse_error;
2858+ }
2859+ break;
2860+ }
2861+
2862+ // remaining bytes (80..C1 and F5..FF) are ill-formed
2863+ default:
2864+ {
2865+ error_message = "invalid string: ill-formed UTF-8 byte";
2866+ return token_type::parse_error;
2867+ }
2868+ }
2869+ }
2870+ }
2871+
2872+ static void strtof(float& f, const char* str, char** endptr) noexcept
2873+ {
2874+ f = std::strtof(str, endptr);
2875+ }
2876+
2877+ static void strtof(double& f, const char* str, char** endptr) noexcept
2878+ {
2879+ f = std::strtod(str, endptr);
2880+ }
2881+
2882+ static void strtof(long double& f, const char* str, char** endptr) noexcept
2883+ {
2884+ f = std::strtold(str, endptr);
2885+ }
2886+
2887+ /*!
2888+ @brief scan a number literal
2889+
2890+ This function scans a string according to Sect. 6 of RFC 7159.
2891+
2892+ The function is realized with a deterministic finite state machine derived
2893+ from the grammar described in RFC 7159. Starting in state "init", the
2894+ input is read and used to determined the next state. Only state "done"
2895+ accepts the number. State "error" is a trap state to model errors. In the
2896+ table below, "anything" means any character but the ones listed before.
2897+
2898+ state | 0 | 1-9 | e E | + | - | . | anything
2899+ ---------|----------|----------|----------|---------|---------|----------|-----------
2900+ init | zero | any1 | [error] | [error] | minus | [error] | [error]
2901+ minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
2902+ zero | done | done | exponent | done | done | decimal1 | done
2903+ any1 | any1 | any1 | exponent | done | done | decimal1 | done
2904+ decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
2905+ decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
2906+ exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
2907+ sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
2908+ any2 | any2 | any2 | done | done | done | done | done
2909+
2910+ The state machine is realized with one label per state (prefixed with
2911+ "scan_number_") and `goto` statements between them. The state machine
2912+ contains cycles, but any cycle can be left when EOF is read. Therefore,
2913+ the function is guaranteed to terminate.
2914+
2915+ During scanning, the read bytes are stored in token_buffer. This string is
2916+ then converted to a signed integer, an unsigned integer, or a
2917+ floating-point number.
2918+
2919+ @return token_type::value_unsigned, token_type::value_integer, or
2920+ token_type::value_float if number could be successfully scanned,
2921+ token_type::parse_error otherwise
2922+
2923+ @note The scanner is independent of the current locale. Internally, the
2924+ locale's decimal point is used instead of `.` to work with the
2925+ locale-dependent converters.
2926+ */
2927+ token_type scan_number()
2928+ {
2929+ // reset token_buffer to store the number's bytes
2930+ reset();
2931+
2932+ // the type of the parsed number; initially set to unsigned; will be
2933+ // changed if minus sign, decimal point or exponent is read
2934+ token_type number_type = token_type::value_unsigned;
2935+
2936+ // state (init): we just found out we need to scan a number
2937+ switch (current)
2938+ {
2939+ case '-':
2940+ {
2941+ add(current);
2942+ goto scan_number_minus;
2943+ }
2944+
2945+ case '0':
2946+ {
2947+ add(current);
2948+ goto scan_number_zero;
2949+ }
2950+
2951+ case '1':
2952+ case '2':
2953+ case '3':
2954+ case '4':
2955+ case '5':
2956+ case '6':
2957+ case '7':
2958+ case '8':
2959+ case '9':
2960+ {
2961+ add(current);
2962+ goto scan_number_any1;
2963+ }
2964+
2965+ // LCOV_EXCL_START
2966+ default:
2967+ {
2968+ // all other characters are rejected outside scan_number()
2969+ assert(false);
2970+ }
2971+ // LCOV_EXCL_STOP
2972+ }
2973+
2974+scan_number_minus:
2975+ // state: we just parsed a leading minus sign
2976+ number_type = token_type::value_integer;
2977+ switch (get())
2978+ {
2979+ case '0':
2980+ {
2981+ add(current);
2982+ goto scan_number_zero;
2983+ }
2984+
2985+ case '1':
2986+ case '2':
2987+ case '3':
2988+ case '4':
2989+ case '5':
2990+ case '6':
2991+ case '7':
2992+ case '8':
2993+ case '9':
2994+ {
2995+ add(current);
2996+ goto scan_number_any1;
2997+ }
2998+
2999+ default:
3000+ {
3001+ error_message = "invalid number; expected digit after '-'";
3002+ return token_type::parse_error;
3003+ }
3004+ }
3005+
3006+scan_number_zero:
3007+ // state: we just parse a zero (maybe with a leading minus sign)
3008+ switch (get())
3009+ {
3010+ case '.':
3011+ {
3012+ add(decimal_point_char);
3013+ goto scan_number_decimal1;
3014+ }
3015+
3016+ case 'e':
3017+ case 'E':
3018+ {
3019+ add(current);
3020+ goto scan_number_exponent;
3021+ }
3022+
3023+ default:
3024+ goto scan_number_done;
3025+ }
3026+
3027+scan_number_any1:
3028+ // state: we just parsed a number 0-9 (maybe with a leading minus sign)
3029+ switch (get())
3030+ {
3031+ case '0':
3032+ case '1':
3033+ case '2':
3034+ case '3':
3035+ case '4':
3036+ case '5':
3037+ case '6':
3038+ case '7':
3039+ case '8':
3040+ case '9':
3041+ {
3042+ add(current);
3043+ goto scan_number_any1;
3044+ }
3045+
3046+ case '.':
3047+ {
3048+ add(decimal_point_char);
3049+ goto scan_number_decimal1;
3050+ }
3051+
3052+ case 'e':
3053+ case 'E':
3054+ {
3055+ add(current);
3056+ goto scan_number_exponent;
3057+ }
3058+
3059+ default:
3060+ goto scan_number_done;
3061+ }
3062+
3063+scan_number_decimal1:
3064+ // state: we just parsed a decimal point
3065+ number_type = token_type::value_float;
3066+ switch (get())
3067+ {
3068+ case '0':
3069+ case '1':
3070+ case '2':
3071+ case '3':
3072+ case '4':
3073+ case '5':
3074+ case '6':
3075+ case '7':
3076+ case '8':
3077+ case '9':
3078+ {
3079+ add(current);
3080+ goto scan_number_decimal2;
3081+ }
3082+
3083+ default:
3084+ {
3085+ error_message = "invalid number; expected digit after '.'";
3086+ return token_type::parse_error;
3087+ }
3088+ }
3089+
3090+scan_number_decimal2:
3091+ // we just parsed at least one number after a decimal point
3092+ switch (get())
3093+ {
3094+ case '0':
3095+ case '1':
3096+ case '2':
3097+ case '3':
3098+ case '4':
3099+ case '5':
3100+ case '6':
3101+ case '7':
3102+ case '8':
3103+ case '9':
3104+ {
3105+ add(current);
3106+ goto scan_number_decimal2;
3107+ }
3108+
3109+ case 'e':
3110+ case 'E':
3111+ {
3112+ add(current);
3113+ goto scan_number_exponent;
3114+ }
3115+
3116+ default:
3117+ goto scan_number_done;
3118+ }
3119+
3120+scan_number_exponent:
3121+ // we just parsed an exponent
3122+ number_type = token_type::value_float;
3123+ switch (get())
3124+ {
3125+ case '+':
3126+ case '-':
3127+ {
3128+ add(current);
3129+ goto scan_number_sign;
3130+ }
3131+
3132+ case '0':
3133+ case '1':
3134+ case '2':
3135+ case '3':
3136+ case '4':
3137+ case '5':
3138+ case '6':
3139+ case '7':
3140+ case '8':
3141+ case '9':
3142+ {
3143+ add(current);
3144+ goto scan_number_any2;
3145+ }
3146+
3147+ default:
3148+ {
3149+ error_message =
3150+ "invalid number; expected '+', '-', or digit after exponent";
3151+ return token_type::parse_error;
3152+ }
3153+ }
3154+
3155+scan_number_sign:
3156+ // we just parsed an exponent sign
3157+ switch (get())
3158+ {
3159+ case '0':
3160+ case '1':
3161+ case '2':
3162+ case '3':
3163+ case '4':
3164+ case '5':
3165+ case '6':
3166+ case '7':
3167+ case '8':
3168+ case '9':
3169+ {
3170+ add(current);
3171+ goto scan_number_any2;
3172+ }
3173+
3174+ default:
3175+ {
3176+ error_message = "invalid number; expected digit after exponent sign";
3177+ return token_type::parse_error;
3178+ }
3179+ }
3180+
3181+scan_number_any2:
3182+ // we just parsed a number after the exponent or exponent sign
3183+ switch (get())
3184+ {
3185+ case '0':
3186+ case '1':
3187+ case '2':
3188+ case '3':
3189+ case '4':
3190+ case '5':
3191+ case '6':
3192+ case '7':
3193+ case '8':
3194+ case '9':
3195+ {
3196+ add(current);
3197+ goto scan_number_any2;
3198+ }
3199+
3200+ default:
3201+ goto scan_number_done;
3202+ }
3203+
3204+scan_number_done:
3205+ // unget the character after the number (we only read it to know that
3206+ // we are done scanning a number)
3207+ unget();
3208+
3209+ char* endptr = nullptr;
3210+ errno = 0;
3211+
3212+ // try to parse integers first and fall back to floats
3213+ if (number_type == token_type::value_unsigned)
3214+ {
3215+ const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
3216+
3217+ // we checked the number format before
3218+ assert(endptr == token_buffer.data() + token_buffer.size());
3219+
3220+ if (errno == 0)
3221+ {
3222+ value_unsigned = static_cast<number_unsigned_t>(x);
3223+ if (value_unsigned == x)
3224+ {
3225+ return token_type::value_unsigned;
3226+ }
3227+ }
3228+ }
3229+ else if (number_type == token_type::value_integer)
3230+ {
3231+ const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
3232+
3233+ // we checked the number format before
3234+ assert(endptr == token_buffer.data() + token_buffer.size());
3235+
3236+ if (errno == 0)
3237+ {
3238+ value_integer = static_cast<number_integer_t>(x);
3239+ if (value_integer == x)
3240+ {
3241+ return token_type::value_integer;
3242+ }
3243+ }
3244+ }
3245+
3246+ // this code is reached if we parse a floating-point number or if an
3247+ // integer conversion above failed
3248+ strtof(value_float, token_buffer.data(), &endptr);
3249+
3250+ // we checked the number format before
3251+ assert(endptr == token_buffer.data() + token_buffer.size());
3252+
3253+ return token_type::value_float;
3254+ }
3255+
3256+ /*!
3257+ @param[in] literal_text the literal text to expect
3258+ @param[in] length the length of the passed literal text
3259+ @param[in] return_type the token type to return on success
3260+ */
3261+ token_type scan_literal(const char* literal_text, const std::size_t length,
3262+ token_type return_type)
3263+ {
3264+ assert(current == literal_text[0]);
3265+ for (std::size_t i = 1; i < length; ++i)
3266+ {
3267+ if (JSON_UNLIKELY(get() != literal_text[i]))
3268+ {
3269+ error_message = "invalid literal";
3270+ return token_type::parse_error;
3271+ }
3272+ }
3273+ return return_type;
3274+ }
3275+
3276+ /////////////////////
3277+ // input management
3278+ /////////////////////
3279+
3280+ /// reset token_buffer; current character is beginning of token
3281+ void reset() noexcept
3282+ {
3283+ token_buffer.clear();
3284+ token_string.clear();
3285+ token_string.push_back(std::char_traits<char>::to_char_type(current));
3286+ }
3287+
3288+ /*
3289+ @brief get next character from the input
3290+
3291+ This function provides the interface to the used input adapter. It does
3292+ not throw in case the input reached EOF, but returns a
3293+ `std::char_traits<char>::eof()` in that case. Stores the scanned characters
3294+ for use in error messages.
3295+
3296+ @return character read from the input
3297+ */
3298+ std::char_traits<char>::int_type get()
3299+ {
3300+ ++chars_read;
3301+ if (next_unget)
3302+ {
3303+ // just reset the next_unget variable and work with current
3304+ next_unget = false;
3305+ }
3306+ else
3307+ {
3308+ current = ia->get_character();
3309+ }
3310+
3311+ if (JSON_LIKELY(current != std::char_traits<char>::eof()))
3312+ {
3313+ token_string.push_back(std::char_traits<char>::to_char_type(current));
3314+ }
3315+ return current;
3316+ }
3317+
3318+ /*!
3319+ @brief unget current character (read it again on next get)
3320+
3321+ We implement unget by setting variable next_unget to true. The input is not
3322+ changed - we just simulate ungetting by modifying chars_read and
3323+ token_string. The next call to get() will behave as if the unget character
3324+ is read again.
3325+ */
3326+ void unget()
3327+ {
3328+ next_unget = true;
3329+ --chars_read;
3330+ if (JSON_LIKELY(current != std::char_traits<char>::eof()))
3331+ {
3332+ assert(token_string.size() != 0);
3333+ token_string.pop_back();
3334+ }
3335+ }
3336+
3337+ /// add a character to token_buffer
3338+ void add(int c)
3339+ {
3340+ token_buffer.push_back(std::char_traits<char>::to_char_type(c));
3341+ }
3342+
3343+ public:
3344+ /////////////////////
3345+ // value getters
3346+ /////////////////////
3347+
3348+ /// return integer value
3349+ constexpr number_integer_t get_number_integer() const noexcept
3350+ {
3351+ return value_integer;
3352+ }
3353+
3354+ /// return unsigned integer value
3355+ constexpr number_unsigned_t get_number_unsigned() const noexcept
3356+ {
3357+ return value_unsigned;
3358+ }
3359+
3360+ /// return floating-point value
3361+ constexpr number_float_t get_number_float() const noexcept
3362+ {
3363+ return value_float;
3364+ }
3365+
3366+ /// return current string value (implicitly resets the token; useful only once)
3367+ string_t& get_string()
3368+ {
3369+ return token_buffer;
3370+ }
3371+
3372+ /////////////////////
3373+ // diagnostics
3374+ /////////////////////
3375+
3376+ /// return position of last read token
3377+ constexpr std::size_t get_position() const noexcept
3378+ {
3379+ return chars_read;
3380+ }
3381+
3382+ /// return the last read token (for errors only). Will never contain EOF
3383+ /// (an arbitrary value that is not a valid char value, often -1), because
3384+ /// 255 may legitimately occur. May contain NUL, which should be escaped.
3385+ std::string get_token_string() const
3386+ {
3387+ // escape control characters
3388+ std::string result;
3389+ for (const auto c : token_string)
3390+ {
3391+ if ('\x00' <= c and c <= '\x1F')
3392+ {
3393+ // escape control characters
3394+ char cs[9];
3395+ snprintf(cs, 9, "<U+%.4X>", static_cast<unsigned char>(c));
3396+ result += cs;
3397+ }
3398+ else
3399+ {
3400+ // add character as is
3401+ result.push_back(c);
3402+ }
3403+ }
3404+
3405+ return result;
3406+ }
3407+
3408+ /// return syntax error message
3409+ constexpr const char* get_error_message() const noexcept
3410+ {
3411+ return error_message;
3412+ }
3413+
3414+ /////////////////////
3415+ // actual scanner
3416+ /////////////////////
3417+
3418+ /*!
3419+ @brief skip the UTF-8 byte order mark
3420+ @return true iff there is no BOM or the correct BOM has been skipped
3421+ */
3422+ bool skip_bom()
3423+ {
3424+ if (get() == 0xEF)
3425+ {
3426+ if (get() == 0xBB and get() == 0xBF)
3427+ {
3428+ // we completely parsed the BOM
3429+ return true;
3430+ }
3431+ else
3432+ {
3433+ // after reading 0xEF, an unexpected character followed
3434+ return false;
3435+ }
3436+ }
3437+ else
3438+ {
3439+ // the first character is not the beginning of the BOM; unget it to
3440+ // process is later
3441+ unget();
3442+ return true;
3443+ }
3444+ }
3445+
3446+ token_type scan()
3447+ {
3448+ // initially, skip the BOM
3449+ if (chars_read == 0 and not skip_bom())
3450+ {
3451+ error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
3452+ return token_type::parse_error;
3453+ }
3454+
3455+ // read next character and ignore whitespace
3456+ do
3457+ {
3458+ get();
3459+ }
3460+ while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
3461+
3462+ switch (current)
3463+ {
3464+ // structural characters
3465+ case '[':
3466+ return token_type::begin_array;
3467+ case ']':
3468+ return token_type::end_array;
3469+ case '{':
3470+ return token_type::begin_object;
3471+ case '}':
3472+ return token_type::end_object;
3473+ case ':':
3474+ return token_type::name_separator;
3475+ case ',':
3476+ return token_type::value_separator;
3477+
3478+ // literals
3479+ case 't':
3480+ return scan_literal("true", 4, token_type::literal_true);
3481+ case 'f':
3482+ return scan_literal("false", 5, token_type::literal_false);
3483+ case 'n':
3484+ return scan_literal("null", 4, token_type::literal_null);
3485+
3486+ // string
3487+ case '\"':
3488+ return scan_string();
3489+
3490+ // number
3491+ case '-':
3492+ case '0':
3493+ case '1':
3494+ case '2':
3495+ case '3':
3496+ case '4':
3497+ case '5':
3498+ case '6':
3499+ case '7':
3500+ case '8':
3501+ case '9':
3502+ return scan_number();
3503+
3504+ // end of input (the null byte is needed when parsing from
3505+ // string literals)
3506+ case '\0':
3507+ case std::char_traits<char>::eof():
3508+ return token_type::end_of_input;
3509+
3510+ // error
3511+ default:
3512+ error_message = "invalid literal";
3513+ return token_type::parse_error;
3514+ }
3515+ }
3516+
3517+ private:
3518+ /// input adapter
3519+ detail::input_adapter_t ia = nullptr;
3520+
3521+ /// the current character
3522+ std::char_traits<char>::int_type current = std::char_traits<char>::eof();
3523+
3524+ /// whether the next get() call should just return current
3525+ bool next_unget = false;
3526+
3527+ /// the number of characters read
3528+ std::size_t chars_read = 0;
3529+
3530+ /// raw input token string (for error messages)
3531+ std::vector<char> token_string {};
3532+
3533+ /// buffer for variable-length tokens (numbers, strings)
3534+ string_t token_buffer {};
3535+
3536+ /// a description of occurred lexer errors
3537+ const char* error_message = "";
3538+
3539+ // number values
3540+ number_integer_t value_integer = 0;
3541+ number_unsigned_t value_unsigned = 0;
3542+ number_float_t value_float = 0;
3543+
3544+ /// the decimal point
3545+ const char decimal_point_char = '.';
3546+};
3547+}
3548+}
3549+
3550+// #include <nlohmann/detail/input/parser.hpp>
3551+
3552+
3553+#include <cassert> // assert
3554+#include <cmath> // isfinite
3555+#include <cstdint> // uint8_t
3556+#include <functional> // function
3557+#include <string> // string
3558+#include <utility> // move
3559+
3560+// #include <nlohmann/detail/exceptions.hpp>
3561+
3562+// #include <nlohmann/detail/macro_scope.hpp>
3563+
3564+// #include <nlohmann/detail/meta/is_sax.hpp>
3565+
3566+
3567+#include <cstdint> // size_t
3568+#include <utility> // declval
3569+
3570+// #include <nlohmann/detail/meta/detected.hpp>
3571+
3572+
3573+#include <type_traits>
3574+
3575+// #include <nlohmann/detail/meta/void_t.hpp>
3576+
3577+
3578+namespace nlohmann
3579+{
3580+namespace detail
3581+{
3582+template <typename...>
3583+using void_t = void;
3584+}
3585+}
3586+
3587+
3588+// http://en.cppreference.com/w/cpp/experimental/is_detected
3589+namespace nlohmann
3590+{
3591+namespace detail
3592+{
3593+struct nonesuch
3594+{
3595+ nonesuch() = delete;
3596+ ~nonesuch() = delete;
3597+ nonesuch(nonesuch const&) = delete;
3598+ void operator=(nonesuch const&) = delete;
3599+};
3600+
3601+template <class Default,
3602+ class AlwaysVoid,
3603+ template <class...> class Op,
3604+ class... Args>
3605+struct detector
3606+{
3607+ using value_t = std::false_type;
3608+ using type = Default;
3609+};
3610+
3611+template <class Default, template <class...> class Op, class... Args>
3612+struct detector<Default, void_t<Op<Args...>>, Op, Args...>
3613+{
3614+ using value_t = std::true_type;
3615+ using type = Op<Args...>;
3616+};
3617+
3618+template <template <class...> class Op, class... Args>
3619+using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
3620+
3621+template <template <class...> class Op, class... Args>
3622+using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
3623+
3624+template <class Default, template <class...> class Op, class... Args>
3625+using detected_or = detector<Default, void, Op, Args...>;
3626+
3627+template <class Default, template <class...> class Op, class... Args>
3628+using detected_or_t = typename detected_or<Default, Op, Args...>::type;
3629+
3630+template <class Expected, template <class...> class Op, class... Args>
3631+using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
3632+
3633+template <class To, template <class...> class Op, class... Args>
3634+using is_detected_convertible =
3635+ std::is_convertible<detected_t<Op, Args...>, To>;
3636+}
3637+}
3638+
3639+// #include <nlohmann/detail/meta/type_traits.hpp>
3640+
3641+
3642+namespace nlohmann
3643+{
3644+namespace detail
3645+{
3646+template <typename T>
3647+using null_function_t = decltype(std::declval<T&>().null());
3648+
3649+template <typename T>
3650+using boolean_function_t =
3651+ decltype(std::declval<T&>().boolean(std::declval<bool>()));
3652+
3653+template <typename T, typename Integer>
3654+using number_integer_function_t =
3655+ decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
3656+
3657+template <typename T, typename Unsigned>
3658+using number_unsigned_function_t =
3659+ decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
3660+
3661+template <typename T, typename Float, typename String>
3662+using number_float_function_t = decltype(std::declval<T&>().number_float(
3663+ std::declval<Float>(), std::declval<const String&>()));
3664+
3665+template <typename T, typename String>
3666+using string_function_t =
3667+ decltype(std::declval<T&>().string(std::declval<String&>()));
3668+
3669+template <typename T>
3670+using start_object_function_t =
3671+ decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
3672+
3673+template <typename T, typename String>
3674+using key_function_t =
3675+ decltype(std::declval<T&>().key(std::declval<String&>()));
3676+
3677+template <typename T>
3678+using end_object_function_t = decltype(std::declval<T&>().end_object());
3679+
3680+template <typename T>
3681+using start_array_function_t =
3682+ decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
3683+
3684+template <typename T>
3685+using end_array_function_t = decltype(std::declval<T&>().end_array());
3686+
3687+template <typename T, typename Exception>
3688+using parse_error_function_t = decltype(std::declval<T&>().parse_error(
3689+ std::declval<std::size_t>(), std::declval<const std::string&>(),
3690+ std::declval<const Exception&>()));
3691+
3692+template <typename SAX, typename BasicJsonType>
3693+struct is_sax
3694+{
3695+ private:
3696+ static_assert(is_basic_json<BasicJsonType>::value,
3697+ "BasicJsonType must be of type basic_json<...>");
3698+
3699+ using number_integer_t = typename BasicJsonType::number_integer_t;
3700+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
3701+ using number_float_t = typename BasicJsonType::number_float_t;
3702+ using string_t = typename BasicJsonType::string_t;
3703+ using exception_t = typename BasicJsonType::exception;
3704+
3705+ public:
3706+ static constexpr bool value =
3707+ is_detected_exact<bool, null_function_t, SAX>::value &&
3708+ is_detected_exact<bool, boolean_function_t, SAX>::value &&
3709+ is_detected_exact<bool, number_integer_function_t, SAX,
3710+ number_integer_t>::value &&
3711+ is_detected_exact<bool, number_unsigned_function_t, SAX,
3712+ number_unsigned_t>::value &&
3713+ is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
3714+ string_t>::value &&
3715+ is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
3716+ is_detected_exact<bool, start_object_function_t, SAX>::value &&
3717+ is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
3718+ is_detected_exact<bool, end_object_function_t, SAX>::value &&
3719+ is_detected_exact<bool, start_array_function_t, SAX>::value &&
3720+ is_detected_exact<bool, end_array_function_t, SAX>::value &&
3721+ is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
3722+};
3723+
3724+template <typename SAX, typename BasicJsonType>
3725+struct is_sax_static_asserts
3726+{
3727+ private:
3728+ static_assert(is_basic_json<BasicJsonType>::value,
3729+ "BasicJsonType must be of type basic_json<...>");
3730+
3731+ using number_integer_t = typename BasicJsonType::number_integer_t;
3732+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
3733+ using number_float_t = typename BasicJsonType::number_float_t;
3734+ using string_t = typename BasicJsonType::string_t;
3735+ using exception_t = typename BasicJsonType::exception;
3736+
3737+ public:
3738+ static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
3739+ "Missing/invalid function: bool null()");
3740+ static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
3741+ "Missing/invalid function: bool boolean(bool)");
3742+ static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
3743+ "Missing/invalid function: bool boolean(bool)");
3744+ static_assert(
3745+ is_detected_exact<bool, number_integer_function_t, SAX,
3746+ number_integer_t>::value,
3747+ "Missing/invalid function: bool number_integer(number_integer_t)");
3748+ static_assert(
3749+ is_detected_exact<bool, number_unsigned_function_t, SAX,
3750+ number_unsigned_t>::value,
3751+ "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
3752+ static_assert(is_detected_exact<bool, number_float_function_t, SAX,
3753+ number_float_t, string_t>::value,
3754+ "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
3755+ static_assert(
3756+ is_detected_exact<bool, string_function_t, SAX, string_t>::value,
3757+ "Missing/invalid function: bool string(string_t&)");
3758+ static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
3759+ "Missing/invalid function: bool start_object(std::size_t)");
3760+ static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
3761+ "Missing/invalid function: bool key(string_t&)");
3762+ static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
3763+ "Missing/invalid function: bool end_object()");
3764+ static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
3765+ "Missing/invalid function: bool start_array(std::size_t)");
3766+ static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
3767+ "Missing/invalid function: bool end_array()");
3768+ static_assert(
3769+ is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
3770+ "Missing/invalid function: bool parse_error(std::size_t, const "
3771+ "std::string&, const exception&)");
3772+};
3773+}
3774+}
3775+
3776+// #include <nlohmann/detail/input/input_adapters.hpp>
3777+
3778+// #include <nlohmann/detail/input/json_sax.hpp>
3779+
3780+
3781+#include <cstddef>
3782+#include <string>
3783+#include <vector>
3784+
3785+// #include <nlohmann/detail/input/parser.hpp>
3786+
3787+// #include <nlohmann/detail/exceptions.hpp>
3788+
3789+
3790+namespace nlohmann
3791+{
3792+
3793+/*!
3794+@brief SAX interface
3795+
3796+This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
3797+Each function is called in different situations while the input is parsed. The
3798+boolean return value informs the parser whether to continue processing the
3799+input.
3800+*/
3801+template<typename BasicJsonType>
3802+struct json_sax
3803+{
3804+ /// type for (signed) integers
3805+ using number_integer_t = typename BasicJsonType::number_integer_t;
3806+ /// type for unsigned integers
3807+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
3808+ /// type for floating-point numbers
3809+ using number_float_t = typename BasicJsonType::number_float_t;
3810+ /// type for strings
3811+ using string_t = typename BasicJsonType::string_t;
3812+
3813+ /*!
3814+ @brief a null value was read
3815+ @return whether parsing should proceed
3816+ */
3817+ virtual bool null() = 0;
3818+
3819+ /*!
3820+ @brief a boolean value was read
3821+ @param[in] val boolean value
3822+ @return whether parsing should proceed
3823+ */
3824+ virtual bool boolean(bool val) = 0;
3825+
3826+ /*!
3827+ @brief an integer number was read
3828+ @param[in] val integer value
3829+ @return whether parsing should proceed
3830+ */
3831+ virtual bool number_integer(number_integer_t val) = 0;
3832+
3833+ /*!
3834+ @brief an unsigned integer number was read
3835+ @param[in] val unsigned integer value
3836+ @return whether parsing should proceed
3837+ */
3838+ virtual bool number_unsigned(number_unsigned_t val) = 0;
3839+
3840+ /*!
3841+ @brief an floating-point number was read
3842+ @param[in] val floating-point value
3843+ @param[in] s raw token value
3844+ @return whether parsing should proceed
3845+ */
3846+ virtual bool number_float(number_float_t val, const string_t& s) = 0;
3847+
3848+ /*!
3849+ @brief a string was read
3850+ @param[in] val string value
3851+ @return whether parsing should proceed
3852+ @note It is safe to move the passed string.
3853+ */
3854+ virtual bool string(string_t& val) = 0;
3855+
3856+ /*!
3857+ @brief the beginning of an object was read
3858+ @param[in] elements number of object elements or -1 if unknown
3859+ @return whether parsing should proceed
3860+ @note binary formats may report the number of elements
3861+ */
3862+ virtual bool start_object(std::size_t elements) = 0;
3863+
3864+ /*!
3865+ @brief an object key was read
3866+ @param[in] val object key
3867+ @return whether parsing should proceed
3868+ @note It is safe to move the passed string.
3869+ */
3870+ virtual bool key(string_t& val) = 0;
3871+
3872+ /*!
3873+ @brief the end of an object was read
3874+ @return whether parsing should proceed
3875+ */
3876+ virtual bool end_object() = 0;
3877+
3878+ /*!
3879+ @brief the beginning of an array was read
3880+ @param[in] elements number of array elements or -1 if unknown
3881+ @return whether parsing should proceed
3882+ @note binary formats may report the number of elements
3883+ */
3884+ virtual bool start_array(std::size_t elements) = 0;
3885+
3886+ /*!
3887+ @brief the end of an array was read
3888+ @return whether parsing should proceed
3889+ */
3890+ virtual bool end_array() = 0;
3891+
3892+ /*!
3893+ @brief a parse error occurred
3894+ @param[in] position the position in the input where the error occurs
3895+ @param[in] last_token the last read token
3896+ @param[in] error_msg a detailed error message
3897+ @return whether parsing should proceed (must return false)
3898+ */
3899+ virtual bool parse_error(std::size_t position,
3900+ const std::string& last_token,
3901+ const detail::exception& ex) = 0;
3902+
3903+ virtual ~json_sax() = default;
3904+};
3905+
3906+
3907+namespace detail
3908+{
3909+/*!
3910+@brief SAX implementation to create a JSON value from SAX events
3911+
3912+This class implements the @ref json_sax interface and processes the SAX events
3913+to create a JSON value which makes it basically a DOM parser. The structure or
3914+hierarchy of the JSON value is managed by the stack `ref_stack` which contains
3915+a pointer to the respective array or object for each recursion depth.
3916+
3917+After successful parsing, the value that is passed by reference to the
3918+constructor contains the parsed value.
3919+
3920+@tparam BasicJsonType the JSON type
3921+*/
3922+template<typename BasicJsonType>
3923+class json_sax_dom_parser
3924+{
3925+ public:
3926+ using number_integer_t = typename BasicJsonType::number_integer_t;
3927+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
3928+ using number_float_t = typename BasicJsonType::number_float_t;
3929+ using string_t = typename BasicJsonType::string_t;
3930+
3931+ /*!
3932+ @param[in, out] r reference to a JSON value that is manipulated while
3933+ parsing
3934+ @param[in] allow_exceptions_ whether parse errors yield exceptions
3935+ */
3936+ explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
3937+ : root(r), allow_exceptions(allow_exceptions_)
3938+ {}
3939+
3940+ bool null()
3941+ {
3942+ handle_value(nullptr);
3943+ return true;
3944+ }
3945+
3946+ bool boolean(bool val)
3947+ {
3948+ handle_value(val);
3949+ return true;
3950+ }
3951+
3952+ bool number_integer(number_integer_t val)
3953+ {
3954+ handle_value(val);
3955+ return true;
3956+ }
3957+
3958+ bool number_unsigned(number_unsigned_t val)
3959+ {
3960+ handle_value(val);
3961+ return true;
3962+ }
3963+
3964+ bool number_float(number_float_t val, const string_t&)
3965+ {
3966+ handle_value(val);
3967+ return true;
3968+ }
3969+
3970+ bool string(string_t& val)
3971+ {
3972+ handle_value(val);
3973+ return true;
3974+ }
3975+
3976+ bool start_object(std::size_t len)
3977+ {
3978+ ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
3979+
3980+ if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
3981+ {
3982+ JSON_THROW(out_of_range::create(408,
3983+ "excessive object size: " + std::to_string(len)));
3984+ }
3985+
3986+ return true;
3987+ }
3988+
3989+ bool key(string_t& val)
3990+ {
3991+ // add null at given key and store the reference for later
3992+ object_element = &(ref_stack.back()->m_value.object->operator[](val));
3993+ return true;
3994+ }
3995+
3996+ bool end_object()
3997+ {
3998+ ref_stack.pop_back();
3999+ return true;
4000+ }
4001+
4002+ bool start_array(std::size_t len)
4003+ {
4004+ ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
4005+
4006+ if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
4007+ {
4008+ JSON_THROW(out_of_range::create(408,
4009+ "excessive array size: " + std::to_string(len)));
4010+ }
4011+
4012+ return true;
4013+ }
4014+
4015+ bool end_array()
4016+ {
4017+ ref_stack.pop_back();
4018+ return true;
4019+ }
4020+
4021+ bool parse_error(std::size_t, const std::string&,
4022+ const detail::exception& ex)
4023+ {
4024+ errored = true;
4025+ if (allow_exceptions)
4026+ {
4027+ // determine the proper exception type from the id
4028+ switch ((ex.id / 100) % 100)
4029+ {
4030+ case 1:
4031+ JSON_THROW(*reinterpret_cast<const detail::parse_error*>(&ex));
4032+ case 4:
4033+ JSON_THROW(*reinterpret_cast<const detail::out_of_range*>(&ex));
4034+ // LCOV_EXCL_START
4035+ case 2:
4036+ JSON_THROW(*reinterpret_cast<const detail::invalid_iterator*>(&ex));
4037+ case 3:
4038+ JSON_THROW(*reinterpret_cast<const detail::type_error*>(&ex));
4039+ case 5:
4040+ JSON_THROW(*reinterpret_cast<const detail::other_error*>(&ex));
4041+ default:
4042+ assert(false);
4043+ // LCOV_EXCL_STOP
4044+ }
4045+ }
4046+ return false;
4047+ }
4048+
4049+ constexpr bool is_errored() const
4050+ {
4051+ return errored;
4052+ }
4053+
4054+ private:
4055+ /*!
4056+ @invariant If the ref stack is empty, then the passed value will be the new
4057+ root.
4058+ @invariant If the ref stack contains a value, then it is an array or an
4059+ object to which we can add elements
4060+ */
4061+ template<typename Value>
4062+ BasicJsonType* handle_value(Value&& v)
4063+ {
4064+ if (ref_stack.empty())
4065+ {
4066+ root = BasicJsonType(std::forward<Value>(v));
4067+ return &root;
4068+ }
4069+ else
4070+ {
4071+ assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
4072+ if (ref_stack.back()->is_array())
4073+ {
4074+ ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
4075+ return &(ref_stack.back()->m_value.array->back());
4076+ }
4077+ else
4078+ {
4079+ assert(object_element);
4080+ *object_element = BasicJsonType(std::forward<Value>(v));
4081+ return object_element;
4082+ }
4083+ }
4084+ }
4085+
4086+ /// the parsed JSON value
4087+ BasicJsonType& root;
4088+ /// stack to model hierarchy of values
4089+ std::vector<BasicJsonType*> ref_stack;
4090+ /// helper to hold the reference for the next object element
4091+ BasicJsonType* object_element = nullptr;
4092+ /// whether a syntax error occurred
4093+ bool errored = false;
4094+ /// whether to throw exceptions in case of errors
4095+ const bool allow_exceptions = true;
4096+};
4097+
4098+template<typename BasicJsonType>
4099+class json_sax_dom_callback_parser
4100+{
4101+ public:
4102+ using number_integer_t = typename BasicJsonType::number_integer_t;
4103+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
4104+ using number_float_t = typename BasicJsonType::number_float_t;
4105+ using string_t = typename BasicJsonType::string_t;
4106+ using parser_callback_t = typename BasicJsonType::parser_callback_t;
4107+ using parse_event_t = typename BasicJsonType::parse_event_t;
4108+
4109+ json_sax_dom_callback_parser(BasicJsonType& r,
4110+ const parser_callback_t cb,
4111+ const bool allow_exceptions_ = true)
4112+ : root(r), callback(cb), allow_exceptions(allow_exceptions_)
4113+ {
4114+ keep_stack.push_back(true);
4115+ }
4116+
4117+ bool null()
4118+ {
4119+ handle_value(nullptr);
4120+ return true;
4121+ }
4122+
4123+ bool boolean(bool val)
4124+ {
4125+ handle_value(val);
4126+ return true;
4127+ }
4128+
4129+ bool number_integer(number_integer_t val)
4130+ {
4131+ handle_value(val);
4132+ return true;
4133+ }
4134+
4135+ bool number_unsigned(number_unsigned_t val)
4136+ {
4137+ handle_value(val);
4138+ return true;
4139+ }
4140+
4141+ bool number_float(number_float_t val, const string_t&)
4142+ {
4143+ handle_value(val);
4144+ return true;
4145+ }
4146+
4147+ bool string(string_t& val)
4148+ {
4149+ handle_value(val);
4150+ return true;
4151+ }
4152+
4153+ bool start_object(std::size_t len)
4154+ {
4155+ // check callback for object start
4156+ const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
4157+ keep_stack.push_back(keep);
4158+
4159+ auto val = handle_value(BasicJsonType::value_t::object, true);
4160+ ref_stack.push_back(val.second);
4161+
4162+ // check object limit
4163+ if (ref_stack.back())
4164+ {
4165+ if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
4166+ {
4167+ JSON_THROW(out_of_range::create(408,
4168+ "excessive object size: " + std::to_string(len)));
4169+ }
4170+ }
4171+
4172+ return true;
4173+ }
4174+
4175+ bool key(string_t& val)
4176+ {
4177+ BasicJsonType k = BasicJsonType(val);
4178+
4179+ // check callback for key
4180+ const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
4181+ key_keep_stack.push_back(keep);
4182+
4183+ // add discarded value at given key and store the reference for later
4184+ if (keep and ref_stack.back())
4185+ {
4186+ object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
4187+ }
4188+
4189+ return true;
4190+ }
4191+
4192+ bool end_object()
4193+ {
4194+ if (ref_stack.back())
4195+ {
4196+ if (not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
4197+ {
4198+ // discard object
4199+ *ref_stack.back() = discarded;
4200+ }
4201+ }
4202+
4203+ assert(not ref_stack.empty());
4204+ assert(not keep_stack.empty());
4205+ ref_stack.pop_back();
4206+ keep_stack.pop_back();
4207+
4208+ if (not ref_stack.empty() and ref_stack.back())
4209+ {
4210+ // remove discarded value
4211+ if (ref_stack.back()->is_object())
4212+ {
4213+ for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
4214+ {
4215+ if (it->is_discarded())
4216+ {
4217+ ref_stack.back()->erase(it);
4218+ break;
4219+ }
4220+ }
4221+ }
4222+ }
4223+
4224+ return true;
4225+ }
4226+
4227+ bool start_array(std::size_t len)
4228+ {
4229+ const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
4230+ keep_stack.push_back(keep);
4231+
4232+ auto val = handle_value(BasicJsonType::value_t::array, true);
4233+ ref_stack.push_back(val.second);
4234+
4235+ // check array limit
4236+ if (ref_stack.back())
4237+ {
4238+ if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
4239+ {
4240+ JSON_THROW(out_of_range::create(408,
4241+ "excessive array size: " + std::to_string(len)));
4242+ }
4243+ }
4244+
4245+ return true;
4246+ }
4247+
4248+ bool end_array()
4249+ {
4250+ bool keep = true;
4251+
4252+ if (ref_stack.back())
4253+ {
4254+ keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
4255+ if (not keep)
4256+ {
4257+ // discard array
4258+ *ref_stack.back() = discarded;
4259+ }
4260+ }
4261+
4262+ assert(not ref_stack.empty());
4263+ assert(not keep_stack.empty());
4264+ ref_stack.pop_back();
4265+ keep_stack.pop_back();
4266+
4267+ // remove discarded value
4268+ if (not keep and not ref_stack.empty())
4269+ {
4270+ if (ref_stack.back()->is_array())
4271+ {
4272+ ref_stack.back()->m_value.array->pop_back();
4273+ }
4274+ }
4275+
4276+ return true;
4277+ }
4278+
4279+ bool parse_error(std::size_t, const std::string&,
4280+ const detail::exception& ex)
4281+ {
4282+ errored = true;
4283+ if (allow_exceptions)
4284+ {
4285+ // determine the proper exception type from the id
4286+ switch ((ex.id / 100) % 100)
4287+ {
4288+ case 1:
4289+ JSON_THROW(*reinterpret_cast<const detail::parse_error*>(&ex));
4290+ case 4:
4291+ JSON_THROW(*reinterpret_cast<const detail::out_of_range*>(&ex));
4292+ // LCOV_EXCL_START
4293+ case 2:
4294+ JSON_THROW(*reinterpret_cast<const detail::invalid_iterator*>(&ex));
4295+ case 3:
4296+ JSON_THROW(*reinterpret_cast<const detail::type_error*>(&ex));
4297+ case 5:
4298+ JSON_THROW(*reinterpret_cast<const detail::other_error*>(&ex));
4299+ default:
4300+ assert(false);
4301+ // LCOV_EXCL_STOP
4302+ }
4303+ }
4304+ return false;
4305+ }
4306+
4307+ constexpr bool is_errored() const
4308+ {
4309+ return errored;
4310+ }
4311+
4312+ private:
4313+ /*!
4314+ @param[in] v value to add to the JSON value we build during parsing
4315+ @param[in] skip_callback whether we should skip calling the callback
4316+ function; this is required after start_array() and
4317+ start_object() SAX events, because otherwise we would call the
4318+ callback function with an empty array or object, respectively.
4319+
4320+ @invariant If the ref stack is empty, then the passed value will be the new
4321+ root.
4322+ @invariant If the ref stack contains a value, then it is an array or an
4323+ object to which we can add elements
4324+
4325+ @return pair of boolean (whether value should be kept) and pointer (to the
4326+ passed value in the ref_stack hierarchy; nullptr if not kept)
4327+ */
4328+ template<typename Value>
4329+ std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
4330+ {
4331+ assert(not keep_stack.empty());
4332+
4333+ // do not handle this value if we know it would be added to a discarded
4334+ // container
4335+ if (not keep_stack.back())
4336+ {
4337+ return {false, nullptr};
4338+ }
4339+
4340+ // create value
4341+ auto value = BasicJsonType(std::forward<Value>(v));
4342+
4343+ // check callback
4344+ const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
4345+
4346+ // do not handle this value if we just learnt it shall be discarded
4347+ if (not keep)
4348+ {
4349+ return {false, nullptr};
4350+ }
4351+
4352+ if (ref_stack.empty())
4353+ {
4354+ root = std::move(value);
4355+ return {true, &root};
4356+ }
4357+ else
4358+ {
4359+ // skip this value if we already decided to skip the parent
4360+ // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
4361+ if (not ref_stack.back())
4362+ {
4363+ return {false, nullptr};
4364+ }
4365+
4366+ assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
4367+ if (ref_stack.back()->is_array())
4368+ {
4369+ ref_stack.back()->m_value.array->push_back(std::move(value));
4370+ return {true, &(ref_stack.back()->m_value.array->back())};
4371+ }
4372+ else
4373+ {
4374+ // check if we should store an element for the current key
4375+ assert(not key_keep_stack.empty());
4376+ const bool store_element = key_keep_stack.back();
4377+ key_keep_stack.pop_back();
4378+
4379+ if (not store_element)
4380+ {
4381+ return {false, nullptr};
4382+ }
4383+
4384+ assert(object_element);
4385+ *object_element = std::move(value);
4386+ return {true, object_element};
4387+ }
4388+ }
4389+ }
4390+
4391+ /// the parsed JSON value
4392+ BasicJsonType& root;
4393+ /// stack to model hierarchy of values
4394+ std::vector<BasicJsonType*> ref_stack;
4395+ /// stack to manage which values to keep
4396+ std::vector<bool> keep_stack;
4397+ /// stack to manage which object keys to keep
4398+ std::vector<bool> key_keep_stack;
4399+ /// helper to hold the reference for the next object element
4400+ BasicJsonType* object_element = nullptr;
4401+ /// whether a syntax error occurred
4402+ bool errored = false;
4403+ /// callback function
4404+ const parser_callback_t callback = nullptr;
4405+ /// whether to throw exceptions in case of errors
4406+ const bool allow_exceptions = true;
4407+ /// a discarded value for the callback
4408+ BasicJsonType discarded = BasicJsonType::value_t::discarded;
4409+};
4410+
4411+template<typename BasicJsonType>
4412+class json_sax_acceptor
4413+{
4414+ public:
4415+ using number_integer_t = typename BasicJsonType::number_integer_t;
4416+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
4417+ using number_float_t = typename BasicJsonType::number_float_t;
4418+ using string_t = typename BasicJsonType::string_t;
4419+
4420+ bool null()
4421+ {
4422+ return true;
4423+ }
4424+
4425+ bool boolean(bool)
4426+ {
4427+ return true;
4428+ }
4429+
4430+ bool number_integer(number_integer_t)
4431+ {
4432+ return true;
4433+ }
4434+
4435+ bool number_unsigned(number_unsigned_t)
4436+ {
4437+ return true;
4438+ }
4439+
4440+ bool number_float(number_float_t, const string_t&)
4441+ {
4442+ return true;
4443+ }
4444+
4445+ bool string(string_t&)
4446+ {
4447+ return true;
4448+ }
4449+
4450+ bool start_object(std::size_t = std::size_t(-1))
4451+ {
4452+ return true;
4453+ }
4454+
4455+ bool key(string_t&)
4456+ {
4457+ return true;
4458+ }
4459+
4460+ bool end_object()
4461+ {
4462+ return true;
4463+ }
4464+
4465+ bool start_array(std::size_t = std::size_t(-1))
4466+ {
4467+ return true;
4468+ }
4469+
4470+ bool end_array()
4471+ {
4472+ return true;
4473+ }
4474+
4475+ bool parse_error(std::size_t, const std::string&, const detail::exception&)
4476+ {
4477+ return false;
4478+ }
4479+};
4480+}
4481+
4482+}
4483+
4484+// #include <nlohmann/detail/input/lexer.hpp>
4485+
4486+// #include <nlohmann/detail/value_t.hpp>
4487+
4488+
4489+namespace nlohmann
4490+{
4491+namespace detail
4492+{
4493+////////////
4494+// parser //
4495+////////////
4496+
4497+/*!
4498+@brief syntax analysis
4499+
4500+This class implements a recursive decent parser.
4501+*/
4502+template<typename BasicJsonType>
4503+class parser
4504+{
4505+ using number_integer_t = typename BasicJsonType::number_integer_t;
4506+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
4507+ using number_float_t = typename BasicJsonType::number_float_t;
4508+ using string_t = typename BasicJsonType::string_t;
4509+ using lexer_t = lexer<BasicJsonType>;
4510+ using token_type = typename lexer_t::token_type;
4511+
4512+ public:
4513+ enum class parse_event_t : uint8_t
4514+ {
4515+ /// the parser read `{` and started to process a JSON object
4516+ object_start,
4517+ /// the parser read `}` and finished processing a JSON object
4518+ object_end,
4519+ /// the parser read `[` and started to process a JSON array
4520+ array_start,
4521+ /// the parser read `]` and finished processing a JSON array
4522+ array_end,
4523+ /// the parser read a key of a value in an object
4524+ key,
4525+ /// the parser finished reading a JSON value
4526+ value
4527+ };
4528+
4529+ using parser_callback_t =
4530+ std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
4531+
4532+ /// a parser reading from an input adapter
4533+ explicit parser(detail::input_adapter_t&& adapter,
4534+ const parser_callback_t cb = nullptr,
4535+ const bool allow_exceptions_ = true)
4536+ : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
4537+ {
4538+ // read first token
4539+ get_token();
4540+ }
4541+
4542+ /*!
4543+ @brief public parser interface
4544+
4545+ @param[in] strict whether to expect the last token to be EOF
4546+ @param[in,out] result parsed JSON value
4547+
4548+ @throw parse_error.101 in case of an unexpected token
4549+ @throw parse_error.102 if to_unicode fails or surrogate error
4550+ @throw parse_error.103 if to_unicode fails
4551+ */
4552+ void parse(const bool strict, BasicJsonType& result)
4553+ {
4554+ if (callback)
4555+ {
4556+ json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
4557+ sax_parse_internal(&sdp);
4558+ result.assert_invariant();
4559+
4560+ // in strict mode, input must be completely read
4561+ if (strict and (get_token() != token_type::end_of_input))
4562+ {
4563+ sdp.parse_error(m_lexer.get_position(),
4564+ m_lexer.get_token_string(),
4565+ parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input)));
4566+ }
4567+
4568+ // in case of an error, return discarded value
4569+ if (sdp.is_errored())
4570+ {
4571+ result = value_t::discarded;
4572+ return;
4573+ }
4574+
4575+ // set top-level value to null if it was discarded by the callback
4576+ // function
4577+ if (result.is_discarded())
4578+ {
4579+ result = nullptr;
4580+ }
4581+ }
4582+ else
4583+ {
4584+ json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
4585+ sax_parse_internal(&sdp);
4586+ result.assert_invariant();
4587+
4588+ // in strict mode, input must be completely read
4589+ if (strict and (get_token() != token_type::end_of_input))
4590+ {
4591+ sdp.parse_error(m_lexer.get_position(),
4592+ m_lexer.get_token_string(),
4593+ parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input)));
4594+ }
4595+
4596+ // in case of an error, return discarded value
4597+ if (sdp.is_errored())
4598+ {
4599+ result = value_t::discarded;
4600+ return;
4601+ }
4602+ }
4603+ }
4604+
4605+ /*!
4606+ @brief public accept interface
4607+
4608+ @param[in] strict whether to expect the last token to be EOF
4609+ @return whether the input is a proper JSON text
4610+ */
4611+ bool accept(const bool strict = true)
4612+ {
4613+ json_sax_acceptor<BasicJsonType> sax_acceptor;
4614+ return sax_parse(&sax_acceptor, strict);
4615+ }
4616+
4617+ template <typename SAX>
4618+ bool sax_parse(SAX* sax, const bool strict = true)
4619+ {
4620+ (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
4621+ const bool result = sax_parse_internal(sax);
4622+
4623+ // strict mode: next byte must be EOF
4624+ if (result and strict and (get_token() != token_type::end_of_input))
4625+ {
4626+ return sax->parse_error(m_lexer.get_position(),
4627+ m_lexer.get_token_string(),
4628+ parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input)));
4629+ }
4630+
4631+ return result;
4632+ }
4633+
4634+ private:
4635+ template <typename SAX>
4636+ bool sax_parse_internal(SAX* sax)
4637+ {
4638+ // stack to remember the hieararchy of structured values we are parsing
4639+ // true = array; false = object
4640+ std::vector<bool> states;
4641+ // value to avoid a goto (see comment where set to true)
4642+ bool skip_to_state_evaluation = false;
4643+
4644+ while (true)
4645+ {
4646+ if (not skip_to_state_evaluation)
4647+ {
4648+ // invariant: get_token() was called before each iteration
4649+ switch (last_token)
4650+ {
4651+ case token_type::begin_object:
4652+ {
4653+ if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
4654+ {
4655+ return false;
4656+ }
4657+
4658+ // closing } -> we are done
4659+ if (get_token() == token_type::end_object)
4660+ {
4661+ if (JSON_UNLIKELY(not sax->end_object()))
4662+ {
4663+ return false;
4664+ }
4665+ break;
4666+ }
4667+
4668+ // parse key
4669+ if (JSON_UNLIKELY(last_token != token_type::value_string))
4670+ {
4671+ return sax->parse_error(m_lexer.get_position(),
4672+ m_lexer.get_token_string(),
4673+ parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string)));
4674+ }
4675+ else
4676+ {
4677+ if (JSON_UNLIKELY(not sax->key(m_lexer.get_string())))
4678+ {
4679+ return false;
4680+ }
4681+ }
4682+
4683+ // parse separator (:)
4684+ if (JSON_UNLIKELY(get_token() != token_type::name_separator))
4685+ {
4686+ return sax->parse_error(m_lexer.get_position(),
4687+ m_lexer.get_token_string(),
4688+ parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator)));
4689+ }
4690+
4691+ // remember we are now inside an object
4692+ states.push_back(false);
4693+
4694+ // parse values
4695+ get_token();
4696+ continue;
4697+ }
4698+
4699+ case token_type::begin_array:
4700+ {
4701+ if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
4702+ {
4703+ return false;
4704+ }
4705+
4706+ // closing ] -> we are done
4707+ if (get_token() == token_type::end_array)
4708+ {
4709+ if (JSON_UNLIKELY(not sax->end_array()))
4710+ {
4711+ return false;
4712+ }
4713+ break;
4714+ }
4715+
4716+ // remember we are now inside an array
4717+ states.push_back(true);
4718+
4719+ // parse values (no need to call get_token)
4720+ continue;
4721+ }
4722+
4723+ case token_type::value_float:
4724+ {
4725+ const auto res = m_lexer.get_number_float();
4726+
4727+ if (JSON_UNLIKELY(not std::isfinite(res)))
4728+ {
4729+ return sax->parse_error(m_lexer.get_position(),
4730+ m_lexer.get_token_string(),
4731+ out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
4732+ }
4733+ else
4734+ {
4735+ if (JSON_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
4736+ {
4737+ return false;
4738+ }
4739+ break;
4740+ }
4741+ }
4742+
4743+ case token_type::literal_false:
4744+ {
4745+ if (JSON_UNLIKELY(not sax->boolean(false)))
4746+ {
4747+ return false;
4748+ }
4749+ break;
4750+ }
4751+
4752+ case token_type::literal_null:
4753+ {
4754+ if (JSON_UNLIKELY(not sax->null()))
4755+ {
4756+ return false;
4757+ }
4758+ break;
4759+ }
4760+
4761+ case token_type::literal_true:
4762+ {
4763+ if (JSON_UNLIKELY(not sax->boolean(true)))
4764+ {
4765+ return false;
4766+ }
4767+ break;
4768+ }
4769+
4770+ case token_type::value_integer:
4771+ {
4772+ if (JSON_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
4773+ {
4774+ return false;
4775+ }
4776+ break;
4777+ }
4778+
4779+ case token_type::value_string:
4780+ {
4781+ if (JSON_UNLIKELY(not sax->string(m_lexer.get_string())))
4782+ {
4783+ return false;
4784+ }
4785+ break;
4786+ }
4787+
4788+ case token_type::value_unsigned:
4789+ {
4790+ if (JSON_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
4791+ {
4792+ return false;
4793+ }
4794+ break;
4795+ }
4796+
4797+ case token_type::parse_error:
4798+ {
4799+ // using "uninitialized" to avoid "expected" message
4800+ return sax->parse_error(m_lexer.get_position(),
4801+ m_lexer.get_token_string(),
4802+ parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized)));
4803+ }
4804+
4805+ default: // the last token was unexpected
4806+ {
4807+ return sax->parse_error(m_lexer.get_position(),
4808+ m_lexer.get_token_string(),
4809+ parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value)));
4810+ }
4811+ }
4812+ }
4813+ else
4814+ {
4815+ skip_to_state_evaluation = false;
4816+ }
4817+
4818+ // we reached this line after we successfully parsed a value
4819+ if (states.empty())
4820+ {
4821+ // empty stack: we reached the end of the hieararchy: done
4822+ return true;
4823+ }
4824+ else
4825+ {
4826+ if (states.back()) // array
4827+ {
4828+ // comma -> next value
4829+ if (get_token() == token_type::value_separator)
4830+ {
4831+ // parse a new value
4832+ get_token();
4833+ continue;
4834+ }
4835+
4836+ // closing ]
4837+ if (JSON_LIKELY(last_token == token_type::end_array))
4838+ {
4839+ if (JSON_UNLIKELY(not sax->end_array()))
4840+ {
4841+ return false;
4842+ }
4843+
4844+ // We are done with this array. Before we can parse a
4845+ // new value, we need to evaluate the new state first.
4846+ // By setting skip_to_state_evaluation to false, we
4847+ // are effectively jumping to the beginning of this if.
4848+ assert(not states.empty());
4849+ states.pop_back();
4850+ skip_to_state_evaluation = true;
4851+ continue;
4852+ }
4853+ else
4854+ {
4855+ return sax->parse_error(m_lexer.get_position(),
4856+ m_lexer.get_token_string(),
4857+ parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array)));
4858+ }
4859+ }
4860+ else // object
4861+ {
4862+ // comma -> next value
4863+ if (get_token() == token_type::value_separator)
4864+ {
4865+ // parse key
4866+ if (JSON_UNLIKELY(get_token() != token_type::value_string))
4867+ {
4868+ return sax->parse_error(m_lexer.get_position(),
4869+ m_lexer.get_token_string(),
4870+ parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string)));
4871+ }
4872+ else
4873+ {
4874+ if (JSON_UNLIKELY(not sax->key(m_lexer.get_string())))
4875+ {
4876+ return false;
4877+ }
4878+ }
4879+
4880+ // parse separator (:)
4881+ if (JSON_UNLIKELY(get_token() != token_type::name_separator))
4882+ {
4883+ return sax->parse_error(m_lexer.get_position(),
4884+ m_lexer.get_token_string(),
4885+ parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator)));
4886+ }
4887+
4888+ // parse values
4889+ get_token();
4890+ continue;
4891+ }
4892+
4893+ // closing }
4894+ if (JSON_LIKELY(last_token == token_type::end_object))
4895+ {
4896+ if (JSON_UNLIKELY(not sax->end_object()))
4897+ {
4898+ return false;
4899+ }
4900+
4901+ // We are done with this object. Before we can parse a
4902+ // new value, we need to evaluate the new state first.
4903+ // By setting skip_to_state_evaluation to false, we
4904+ // are effectively jumping to the beginning of this if.
4905+ assert(not states.empty());
4906+ states.pop_back();
4907+ skip_to_state_evaluation = true;
4908+ continue;
4909+ }
4910+ else
4911+ {
4912+ return sax->parse_error(m_lexer.get_position(),
4913+ m_lexer.get_token_string(),
4914+ parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object)));
4915+ }
4916+ }
4917+ }
4918+ }
4919+ }
4920+
4921+ /// get next token from lexer
4922+ token_type get_token()
4923+ {
4924+ return (last_token = m_lexer.scan());
4925+ }
4926+
4927+ std::string exception_message(const token_type expected)
4928+ {
4929+ std::string error_msg = "syntax error - ";
4930+ if (last_token == token_type::parse_error)
4931+ {
4932+ error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
4933+ m_lexer.get_token_string() + "'";
4934+ }
4935+ else
4936+ {
4937+ error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
4938+ }
4939+
4940+ if (expected != token_type::uninitialized)
4941+ {
4942+ error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
4943+ }
4944+
4945+ return error_msg;
4946+ }
4947+
4948+ private:
4949+ /// callback function
4950+ const parser_callback_t callback = nullptr;
4951+ /// the type of the last read token
4952+ token_type last_token = token_type::uninitialized;
4953+ /// the lexer
4954+ lexer_t m_lexer;
4955+ /// whether to throw exceptions in case of errors
4956+ const bool allow_exceptions = true;
4957+};
4958+}
4959+}
4960+
4961+// #include <nlohmann/detail/iterators/primitive_iterator.hpp>
4962+
4963+
4964+#include <cstddef> // ptrdiff_t
4965+#include <limits> // numeric_limits
4966+
4967+namespace nlohmann
4968+{
4969+namespace detail
4970+{
4971+/*
4972+@brief an iterator for primitive JSON types
4973+
4974+This class models an iterator for primitive JSON types (boolean, number,
4975+string). It's only purpose is to allow the iterator/const_iterator classes
4976+to "iterate" over primitive values. Internally, the iterator is modeled by
4977+a `difference_type` variable. Value begin_value (`0`) models the begin,
4978+end_value (`1`) models past the end.
4979+*/
4980+class primitive_iterator_t
4981+{
4982+ private:
4983+ using difference_type = std::ptrdiff_t;
4984+ static constexpr difference_type begin_value = 0;
4985+ static constexpr difference_type end_value = begin_value + 1;
4986+
4987+ /// iterator as signed integer type
4988+ difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
4989+
4990+ public:
4991+ constexpr difference_type get_value() const noexcept
4992+ {
4993+ return m_it;
4994+ }
4995+
4996+ /// set iterator to a defined beginning
4997+ void set_begin() noexcept
4998+ {
4999+ m_it = begin_value;
5000+ }
5001+
5002+ /// set iterator to a defined past the end
5003+ void set_end() noexcept
5004+ {
5005+ m_it = end_value;
5006+ }
5007+
5008+ /// return whether the iterator can be dereferenced
5009+ constexpr bool is_begin() const noexcept
5010+ {
5011+ return m_it == begin_value;
5012+ }
5013+
5014+ /// return whether the iterator is at end
5015+ constexpr bool is_end() const noexcept
5016+ {
5017+ return m_it == end_value;
5018+ }
5019+
5020+ friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
5021+ {
5022+ return lhs.m_it == rhs.m_it;
5023+ }
5024+
5025+ friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
5026+ {
5027+ return lhs.m_it < rhs.m_it;
5028+ }
5029+
5030+ primitive_iterator_t operator+(difference_type n) noexcept
5031+ {
5032+ auto result = *this;
5033+ result += n;
5034+ return result;
5035+ }
5036+
5037+ friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
5038+ {
5039+ return lhs.m_it - rhs.m_it;
5040+ }
5041+
5042+ primitive_iterator_t& operator++() noexcept
5043+ {
5044+ ++m_it;
5045+ return *this;
5046+ }
5047+
5048+ primitive_iterator_t const operator++(int) noexcept
5049+ {
5050+ auto result = *this;
5051+ ++m_it;
5052+ return result;
5053+ }
5054+
5055+ primitive_iterator_t& operator--() noexcept
5056+ {
5057+ --m_it;
5058+ return *this;
5059+ }
5060+
5061+ primitive_iterator_t const operator--(int) noexcept
5062+ {
5063+ auto result = *this;
5064+ --m_it;
5065+ return result;
5066+ }
5067+
5068+ primitive_iterator_t& operator+=(difference_type n) noexcept
5069+ {
5070+ m_it += n;
5071+ return *this;
5072+ }
5073+
5074+ primitive_iterator_t& operator-=(difference_type n) noexcept
5075+ {
5076+ m_it -= n;
5077+ return *this;
5078+ }
5079+};
5080+}
5081+}
5082+
5083+// #include <nlohmann/detail/iterators/internal_iterator.hpp>
5084+
5085+
5086+// #include <nlohmann/detail/iterators/primitive_iterator.hpp>
5087+
5088+
5089+namespace nlohmann
5090+{
5091+namespace detail
5092+{
5093+/*!
5094+@brief an iterator value
5095+
5096+@note This structure could easily be a union, but MSVC currently does not allow
5097+unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
5098+*/
5099+template<typename BasicJsonType> struct internal_iterator
5100+{
5101+ /// iterator for JSON objects
5102+ typename BasicJsonType::object_t::iterator object_iterator {};
5103+ /// iterator for JSON arrays
5104+ typename BasicJsonType::array_t::iterator array_iterator {};
5105+ /// generic iterator for all other types
5106+ primitive_iterator_t primitive_iterator {};
5107+};
5108+}
5109+}
5110+
5111+// #include <nlohmann/detail/iterators/iter_impl.hpp>
5112+
5113+
5114+#include <ciso646> // not
5115+#include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
5116+#include <type_traits> // conditional, is_const, remove_const
5117+
5118+// #include <nlohmann/detail/exceptions.hpp>
5119+
5120+// #include <nlohmann/detail/iterators/internal_iterator.hpp>
5121+
5122+// #include <nlohmann/detail/iterators/primitive_iterator.hpp>
5123+
5124+// #include <nlohmann/detail/macro_scope.hpp>
5125+
5126+// #include <nlohmann/detail/meta/cpp_future.hpp>
5127+
5128+// #include <nlohmann/detail/value_t.hpp>
5129+
5130+
5131+namespace nlohmann
5132+{
5133+namespace detail
5134+{
5135+// forward declare, to be able to friend it later on
5136+template<typename IteratorType> class iteration_proxy;
5137+
5138+/*!
5139+@brief a template for a bidirectional iterator for the @ref basic_json class
5140+
5141+This class implements a both iterators (iterator and const_iterator) for the
5142+@ref basic_json class.
5143+
5144+@note An iterator is called *initialized* when a pointer to a JSON value has
5145+ been set (e.g., by a constructor or a copy assignment). If the iterator is
5146+ default-constructed, it is *uninitialized* and most methods are undefined.
5147+ **The library uses assertions to detect calls on uninitialized iterators.**
5148+
5149+@requirement The class satisfies the following concept requirements:
5150+-
5151+[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
5152+ The iterator that can be moved can be moved in both directions (i.e.
5153+ incremented and decremented).
5154+
5155+@since version 1.0.0, simplified in version 2.0.9, change to bidirectional
5156+ iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
5157+*/
5158+template<typename BasicJsonType>
5159+class iter_impl
5160+{
5161+ /// allow basic_json to access private members
5162+ friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
5163+ friend BasicJsonType;
5164+ friend iteration_proxy<iter_impl>;
5165+
5166+ using object_t = typename BasicJsonType::object_t;
5167+ using array_t = typename BasicJsonType::array_t;
5168+ // make sure BasicJsonType is basic_json or const basic_json
5169+ static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
5170+ "iter_impl only accepts (const) basic_json");
5171+
5172+ public:
5173+
5174+ /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
5175+ /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
5176+ /// A user-defined iterator should provide publicly accessible typedefs named
5177+ /// iterator_category, value_type, difference_type, pointer, and reference.
5178+ /// Note that value_type is required to be non-const, even for constant iterators.
5179+ using iterator_category = std::bidirectional_iterator_tag;
5180+
5181+ /// the type of the values when the iterator is dereferenced
5182+ using value_type = typename BasicJsonType::value_type;
5183+ /// a type to represent differences between iterators
5184+ using difference_type = typename BasicJsonType::difference_type;
5185+ /// defines a pointer to the type iterated over (value_type)
5186+ using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
5187+ typename BasicJsonType::const_pointer,
5188+ typename BasicJsonType::pointer>::type;
5189+ /// defines a reference to the type iterated over (value_type)
5190+ using reference =
5191+ typename std::conditional<std::is_const<BasicJsonType>::value,
5192+ typename BasicJsonType::const_reference,
5193+ typename BasicJsonType::reference>::type;
5194+
5195+ /// default constructor
5196+ iter_impl() = default;
5197+
5198+ /*!
5199+ @brief constructor for a given JSON instance
5200+ @param[in] object pointer to a JSON object for this iterator
5201+ @pre object != nullptr
5202+ @post The iterator is initialized; i.e. `m_object != nullptr`.
5203+ */
5204+ explicit iter_impl(pointer object) noexcept : m_object(object)
5205+ {
5206+ assert(m_object != nullptr);
5207+
5208+ switch (m_object->m_type)
5209+ {
5210+ case value_t::object:
5211+ {
5212+ m_it.object_iterator = typename object_t::iterator();
5213+ break;
5214+ }
5215+
5216+ case value_t::array:
5217+ {
5218+ m_it.array_iterator = typename array_t::iterator();
5219+ break;
5220+ }
5221+
5222+ default:
5223+ {
5224+ m_it.primitive_iterator = primitive_iterator_t();
5225+ break;
5226+ }
5227+ }
5228+ }
5229+
5230+ /*!
5231+ @note The conventional copy constructor and copy assignment are implicitly
5232+ defined. Combined with the following converting constructor and
5233+ assignment, they support: (1) copy from iterator to iterator, (2)
5234+ copy from const iterator to const iterator, and (3) conversion from
5235+ iterator to const iterator. However conversion from const iterator
5236+ to iterator is not defined.
5237+ */
5238+
5239+ /*!
5240+ @brief converting constructor
5241+ @param[in] other non-const iterator to copy from
5242+ @note It is not checked whether @a other is initialized.
5243+ */
5244+ iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
5245+ : m_object(other.m_object), m_it(other.m_it) {}
5246+
5247+ /*!
5248+ @brief converting assignment
5249+ @param[in,out] other non-const iterator to copy from
5250+ @return const/non-const iterator
5251+ @note It is not checked whether @a other is initialized.
5252+ */
5253+ iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
5254+ {
5255+ m_object = other.m_object;
5256+ m_it = other.m_it;
5257+ return *this;
5258+ }
5259+
5260+ private:
5261+ /*!
5262+ @brief set the iterator to the first value
5263+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5264+ */
5265+ void set_begin() noexcept
5266+ {
5267+ assert(m_object != nullptr);
5268+
5269+ switch (m_object->m_type)
5270+ {
5271+ case value_t::object:
5272+ {
5273+ m_it.object_iterator = m_object->m_value.object->begin();
5274+ break;
5275+ }
5276+
5277+ case value_t::array:
5278+ {
5279+ m_it.array_iterator = m_object->m_value.array->begin();
5280+ break;
5281+ }
5282+
5283+ case value_t::null:
5284+ {
5285+ // set to end so begin()==end() is true: null is empty
5286+ m_it.primitive_iterator.set_end();
5287+ break;
5288+ }
5289+
5290+ default:
5291+ {
5292+ m_it.primitive_iterator.set_begin();
5293+ break;
5294+ }
5295+ }
5296+ }
5297+
5298+ /*!
5299+ @brief set the iterator past the last value
5300+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5301+ */
5302+ void set_end() noexcept
5303+ {
5304+ assert(m_object != nullptr);
5305+
5306+ switch (m_object->m_type)
5307+ {
5308+ case value_t::object:
5309+ {
5310+ m_it.object_iterator = m_object->m_value.object->end();
5311+ break;
5312+ }
5313+
5314+ case value_t::array:
5315+ {
5316+ m_it.array_iterator = m_object->m_value.array->end();
5317+ break;
5318+ }
5319+
5320+ default:
5321+ {
5322+ m_it.primitive_iterator.set_end();
5323+ break;
5324+ }
5325+ }
5326+ }
5327+
5328+ public:
5329+ /*!
5330+ @brief return a reference to the value pointed to by the iterator
5331+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5332+ */
5333+ reference operator*() const
5334+ {
5335+ assert(m_object != nullptr);
5336+
5337+ switch (m_object->m_type)
5338+ {
5339+ case value_t::object:
5340+ {
5341+ assert(m_it.object_iterator != m_object->m_value.object->end());
5342+ return m_it.object_iterator->second;
5343+ }
5344+
5345+ case value_t::array:
5346+ {
5347+ assert(m_it.array_iterator != m_object->m_value.array->end());
5348+ return *m_it.array_iterator;
5349+ }
5350+
5351+ case value_t::null:
5352+ JSON_THROW(invalid_iterator::create(214, "cannot get value"));
5353+
5354+ default:
5355+ {
5356+ if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
5357+ {
5358+ return *m_object;
5359+ }
5360+
5361+ JSON_THROW(invalid_iterator::create(214, "cannot get value"));
5362+ }
5363+ }
5364+ }
5365+
5366+ /*!
5367+ @brief dereference the iterator
5368+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5369+ */
5370+ pointer operator->() const
5371+ {
5372+ assert(m_object != nullptr);
5373+
5374+ switch (m_object->m_type)
5375+ {
5376+ case value_t::object:
5377+ {
5378+ assert(m_it.object_iterator != m_object->m_value.object->end());
5379+ return &(m_it.object_iterator->second);
5380+ }
5381+
5382+ case value_t::array:
5383+ {
5384+ assert(m_it.array_iterator != m_object->m_value.array->end());
5385+ return &*m_it.array_iterator;
5386+ }
5387+
5388+ default:
5389+ {
5390+ if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
5391+ {
5392+ return m_object;
5393+ }
5394+
5395+ JSON_THROW(invalid_iterator::create(214, "cannot get value"));
5396+ }
5397+ }
5398+ }
5399+
5400+ /*!
5401+ @brief post-increment (it++)
5402+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5403+ */
5404+ iter_impl const operator++(int)
5405+ {
5406+ auto result = *this;
5407+ ++(*this);
5408+ return result;
5409+ }
5410+
5411+ /*!
5412+ @brief pre-increment (++it)
5413+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5414+ */
5415+ iter_impl& operator++()
5416+ {
5417+ assert(m_object != nullptr);
5418+
5419+ switch (m_object->m_type)
5420+ {
5421+ case value_t::object:
5422+ {
5423+ std::advance(m_it.object_iterator, 1);
5424+ break;
5425+ }
5426+
5427+ case value_t::array:
5428+ {
5429+ std::advance(m_it.array_iterator, 1);
5430+ break;
5431+ }
5432+
5433+ default:
5434+ {
5435+ ++m_it.primitive_iterator;
5436+ break;
5437+ }
5438+ }
5439+
5440+ return *this;
5441+ }
5442+
5443+ /*!
5444+ @brief post-decrement (it--)
5445+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5446+ */
5447+ iter_impl const operator--(int)
5448+ {
5449+ auto result = *this;
5450+ --(*this);
5451+ return result;
5452+ }
5453+
5454+ /*!
5455+ @brief pre-decrement (--it)
5456+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5457+ */
5458+ iter_impl& operator--()
5459+ {
5460+ assert(m_object != nullptr);
5461+
5462+ switch (m_object->m_type)
5463+ {
5464+ case value_t::object:
5465+ {
5466+ std::advance(m_it.object_iterator, -1);
5467+ break;
5468+ }
5469+
5470+ case value_t::array:
5471+ {
5472+ std::advance(m_it.array_iterator, -1);
5473+ break;
5474+ }
5475+
5476+ default:
5477+ {
5478+ --m_it.primitive_iterator;
5479+ break;
5480+ }
5481+ }
5482+
5483+ return *this;
5484+ }
5485+
5486+ /*!
5487+ @brief comparison: equal
5488+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5489+ */
5490+ bool operator==(const iter_impl& other) const
5491+ {
5492+ // if objects are not the same, the comparison is undefined
5493+ if (JSON_UNLIKELY(m_object != other.m_object))
5494+ {
5495+ JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
5496+ }
5497+
5498+ assert(m_object != nullptr);
5499+
5500+ switch (m_object->m_type)
5501+ {
5502+ case value_t::object:
5503+ return (m_it.object_iterator == other.m_it.object_iterator);
5504+
5505+ case value_t::array:
5506+ return (m_it.array_iterator == other.m_it.array_iterator);
5507+
5508+ default:
5509+ return (m_it.primitive_iterator == other.m_it.primitive_iterator);
5510+ }
5511+ }
5512+
5513+ /*!
5514+ @brief comparison: not equal
5515+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5516+ */
5517+ bool operator!=(const iter_impl& other) const
5518+ {
5519+ return not operator==(other);
5520+ }
5521+
5522+ /*!
5523+ @brief comparison: smaller
5524+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5525+ */
5526+ bool operator<(const iter_impl& other) const
5527+ {
5528+ // if objects are not the same, the comparison is undefined
5529+ if (JSON_UNLIKELY(m_object != other.m_object))
5530+ {
5531+ JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
5532+ }
5533+
5534+ assert(m_object != nullptr);
5535+
5536+ switch (m_object->m_type)
5537+ {
5538+ case value_t::object:
5539+ JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
5540+
5541+ case value_t::array:
5542+ return (m_it.array_iterator < other.m_it.array_iterator);
5543+
5544+ default:
5545+ return (m_it.primitive_iterator < other.m_it.primitive_iterator);
5546+ }
5547+ }
5548+
5549+ /*!
5550+ @brief comparison: less than or equal
5551+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5552+ */
5553+ bool operator<=(const iter_impl& other) const
5554+ {
5555+ return not other.operator < (*this);
5556+ }
5557+
5558+ /*!
5559+ @brief comparison: greater than
5560+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5561+ */
5562+ bool operator>(const iter_impl& other) const
5563+ {
5564+ return not operator<=(other);
5565+ }
5566+
5567+ /*!
5568+ @brief comparison: greater than or equal
5569+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5570+ */
5571+ bool operator>=(const iter_impl& other) const
5572+ {
5573+ return not operator<(other);
5574+ }
5575+
5576+ /*!
5577+ @brief add to iterator
5578+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5579+ */
5580+ iter_impl& operator+=(difference_type i)
5581+ {
5582+ assert(m_object != nullptr);
5583+
5584+ switch (m_object->m_type)
5585+ {
5586+ case value_t::object:
5587+ JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
5588+
5589+ case value_t::array:
5590+ {
5591+ std::advance(m_it.array_iterator, i);
5592+ break;
5593+ }
5594+
5595+ default:
5596+ {
5597+ m_it.primitive_iterator += i;
5598+ break;
5599+ }
5600+ }
5601+
5602+ return *this;
5603+ }
5604+
5605+ /*!
5606+ @brief subtract from iterator
5607+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5608+ */
5609+ iter_impl& operator-=(difference_type i)
5610+ {
5611+ return operator+=(-i);
5612+ }
5613+
5614+ /*!
5615+ @brief add to iterator
5616+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5617+ */
5618+ iter_impl operator+(difference_type i) const
5619+ {
5620+ auto result = *this;
5621+ result += i;
5622+ return result;
5623+ }
5624+
5625+ /*!
5626+ @brief addition of distance and iterator
5627+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5628+ */
5629+ friend iter_impl operator+(difference_type i, const iter_impl& it)
5630+ {
5631+ auto result = it;
5632+ result += i;
5633+ return result;
5634+ }
5635+
5636+ /*!
5637+ @brief subtract from iterator
5638+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5639+ */
5640+ iter_impl operator-(difference_type i) const
5641+ {
5642+ auto result = *this;
5643+ result -= i;
5644+ return result;
5645+ }
5646+
5647+ /*!
5648+ @brief return difference
5649+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5650+ */
5651+ difference_type operator-(const iter_impl& other) const
5652+ {
5653+ assert(m_object != nullptr);
5654+
5655+ switch (m_object->m_type)
5656+ {
5657+ case value_t::object:
5658+ JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
5659+
5660+ case value_t::array:
5661+ return m_it.array_iterator - other.m_it.array_iterator;
5662+
5663+ default:
5664+ return m_it.primitive_iterator - other.m_it.primitive_iterator;
5665+ }
5666+ }
5667+
5668+ /*!
5669+ @brief access to successor
5670+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5671+ */
5672+ reference operator[](difference_type n) const
5673+ {
5674+ assert(m_object != nullptr);
5675+
5676+ switch (m_object->m_type)
5677+ {
5678+ case value_t::object:
5679+ JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
5680+
5681+ case value_t::array:
5682+ return *std::next(m_it.array_iterator, n);
5683+
5684+ case value_t::null:
5685+ JSON_THROW(invalid_iterator::create(214, "cannot get value"));
5686+
5687+ default:
5688+ {
5689+ if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
5690+ {
5691+ return *m_object;
5692+ }
5693+
5694+ JSON_THROW(invalid_iterator::create(214, "cannot get value"));
5695+ }
5696+ }
5697+ }
5698+
5699+ /*!
5700+ @brief return the key of an object iterator
5701+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5702+ */
5703+ const typename object_t::key_type& key() const
5704+ {
5705+ assert(m_object != nullptr);
5706+
5707+ if (JSON_LIKELY(m_object->is_object()))
5708+ {
5709+ return m_it.object_iterator->first;
5710+ }
5711+
5712+ JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
5713+ }
5714+
5715+ /*!
5716+ @brief return the value of an iterator
5717+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
5718+ */
5719+ reference value() const
5720+ {
5721+ return operator*();
5722+ }
5723+
5724+ private:
5725+ /// associated JSON instance
5726+ pointer m_object = nullptr;
5727+ /// the actual iterator of the associated instance
5728+ internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it;
5729+};
5730+}
5731+}
5732+
5733+// #include <nlohmann/detail/iterators/iteration_proxy.hpp>
5734+
5735+// #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
5736+
5737+
5738+#include <cstddef> // ptrdiff_t
5739+#include <iterator> // reverse_iterator
5740+#include <utility> // declval
5741+
5742+namespace nlohmann
5743+{
5744+namespace detail
5745+{
5746+//////////////////////
5747+// reverse_iterator //
5748+//////////////////////
5749+
5750+/*!
5751+@brief a template for a reverse iterator class
5752+
5753+@tparam Base the base iterator type to reverse. Valid types are @ref
5754+iterator (to create @ref reverse_iterator) and @ref const_iterator (to
5755+create @ref const_reverse_iterator).
5756+
5757+@requirement The class satisfies the following concept requirements:
5758+-
5759+[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
5760+ The iterator that can be moved can be moved in both directions (i.e.
5761+ incremented and decremented).
5762+- [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
5763+ It is possible to write to the pointed-to element (only if @a Base is
5764+ @ref iterator).
5765+
5766+@since version 1.0.0
5767+*/
5768+template<typename Base>
5769+class json_reverse_iterator : public std::reverse_iterator<Base>
5770+{
5771+ public:
5772+ using difference_type = std::ptrdiff_t;
5773+ /// shortcut to the reverse iterator adapter
5774+ using base_iterator = std::reverse_iterator<Base>;
5775+ /// the reference type for the pointed-to element
5776+ using reference = typename Base::reference;
5777+
5778+ /// create reverse iterator from iterator
5779+ explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
5780+ : base_iterator(it) {}
5781+
5782+ /// create reverse iterator from base class
5783+ explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
5784+
5785+ /// post-increment (it++)
5786+ json_reverse_iterator const operator++(int)
5787+ {
5788+ return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
5789+ }
5790+
5791+ /// pre-increment (++it)
5792+ json_reverse_iterator& operator++()
5793+ {
5794+ return static_cast<json_reverse_iterator&>(base_iterator::operator++());
5795+ }
5796+
5797+ /// post-decrement (it--)
5798+ json_reverse_iterator const operator--(int)
5799+ {
5800+ return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
5801+ }
5802+
5803+ /// pre-decrement (--it)
5804+ json_reverse_iterator& operator--()
5805+ {
5806+ return static_cast<json_reverse_iterator&>(base_iterator::operator--());
5807+ }
5808+
5809+ /// add to iterator
5810+ json_reverse_iterator& operator+=(difference_type i)
5811+ {
5812+ return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
5813+ }
5814+
5815+ /// add to iterator
5816+ json_reverse_iterator operator+(difference_type i) const
5817+ {
5818+ return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
5819+ }
5820+
5821+ /// subtract from iterator
5822+ json_reverse_iterator operator-(difference_type i) const
5823+ {
5824+ return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
5825+ }
5826+
5827+ /// return difference
5828+ difference_type operator-(const json_reverse_iterator& other) const
5829+ {
5830+ return base_iterator(*this) - base_iterator(other);
5831+ }
5832+
5833+ /// access to successor
5834+ reference operator[](difference_type n) const
5835+ {
5836+ return *(this->operator+(n));
5837+ }
5838+
5839+ /// return the key of an object iterator
5840+ auto key() const -> decltype(std::declval<Base>().key())
5841+ {
5842+ auto it = --this->base();
5843+ return it.key();
5844+ }
5845+
5846+ /// return the value of an iterator
5847+ reference value() const
5848+ {
5849+ auto it = --this->base();
5850+ return it.operator * ();
5851+ }
5852+};
5853+}
5854+}
5855+
5856+// #include <nlohmann/detail/output/output_adapters.hpp>
5857+
5858+
5859+#include <algorithm> // copy
5860+#include <cstddef> // size_t
5861+#include <ios> // streamsize
5862+#include <iterator> // back_inserter
5863+#include <memory> // shared_ptr, make_shared
5864+#include <ostream> // basic_ostream
5865+#include <string> // basic_string
5866+#include <vector> // vector
5867+
5868+namespace nlohmann
5869+{
5870+namespace detail
5871+{
5872+/// abstract output adapter interface
5873+template<typename CharType> struct output_adapter_protocol
5874+{
5875+ virtual void write_character(CharType c) = 0;
5876+ virtual void write_characters(const CharType* s, std::size_t length) = 0;
5877+ virtual ~output_adapter_protocol() = default;
5878+};
5879+
5880+/// a type to simplify interfaces
5881+template<typename CharType>
5882+using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
5883+
5884+/// output adapter for byte vectors
5885+template<typename CharType>
5886+class output_vector_adapter : public output_adapter_protocol<CharType>
5887+{
5888+ public:
5889+ explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {}
5890+
5891+ void write_character(CharType c) override
5892+ {
5893+ v.push_back(c);
5894+ }
5895+
5896+ void write_characters(const CharType* s, std::size_t length) override
5897+ {
5898+ std::copy(s, s + length, std::back_inserter(v));
5899+ }
5900+
5901+ private:
5902+ std::vector<CharType>& v;
5903+};
5904+
5905+/// output adapter for output streams
5906+template<typename CharType>
5907+class output_stream_adapter : public output_adapter_protocol<CharType>
5908+{
5909+ public:
5910+ explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {}
5911+
5912+ void write_character(CharType c) override
5913+ {
5914+ stream.put(c);
5915+ }
5916+
5917+ void write_characters(const CharType* s, std::size_t length) override
5918+ {
5919+ stream.write(s, static_cast<std::streamsize>(length));
5920+ }
5921+
5922+ private:
5923+ std::basic_ostream<CharType>& stream;
5924+};
5925+
5926+/// output adapter for basic_string
5927+template<typename CharType, typename StringType = std::basic_string<CharType>>
5928+class output_string_adapter : public output_adapter_protocol<CharType>
5929+{
5930+ public:
5931+ explicit output_string_adapter(StringType& s) : str(s) {}
5932+
5933+ void write_character(CharType c) override
5934+ {
5935+ str.push_back(c);
5936+ }
5937+
5938+ void write_characters(const CharType* s, std::size_t length) override
5939+ {
5940+ str.append(s, length);
5941+ }
5942+
5943+ private:
5944+ StringType& str;
5945+};
5946+
5947+template<typename CharType, typename StringType = std::basic_string<CharType>>
5948+class output_adapter
5949+{
5950+ public:
5951+ output_adapter(std::vector<CharType>& vec)
5952+ : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
5953+
5954+ output_adapter(std::basic_ostream<CharType>& s)
5955+ : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
5956+
5957+ output_adapter(StringType& s)
5958+ : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
5959+
5960+ operator output_adapter_t<CharType>()
5961+ {
5962+ return oa;
5963+ }
5964+
5965+ private:
5966+ output_adapter_t<CharType> oa = nullptr;
5967+};
5968+}
5969+}
5970+
5971+// #include <nlohmann/detail/input/binary_reader.hpp>
5972+
5973+
5974+#include <algorithm> // generate_n
5975+#include <array> // array
5976+#include <cassert> // assert
5977+#include <cmath> // ldexp
5978+#include <cstddef> // size_t
5979+#include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
5980+#include <cstdio> // snprintf
5981+#include <cstring> // memcpy
5982+#include <iterator> // back_inserter
5983+#include <limits> // numeric_limits
5984+#include <string> // char_traits, string
5985+#include <utility> // make_pair, move
5986+
5987+// #include <nlohmann/detail/input/input_adapters.hpp>
5988+
5989+// #include <nlohmann/detail/input/json_sax.hpp>
5990+
5991+// #include <nlohmann/detail/exceptions.hpp>
5992+
5993+// #include <nlohmann/detail/macro_scope.hpp>
5994+
5995+// #include <nlohmann/detail/meta/is_sax.hpp>
5996+
5997+// #include <nlohmann/detail/value_t.hpp>
5998+
5999+
6000+namespace nlohmann
6001+{
6002+namespace detail
6003+{
6004+///////////////////
6005+// binary reader //
6006+///////////////////
6007+
6008+/*!
6009+@brief deserialization of CBOR, MessagePack, and UBJSON values
6010+*/
6011+template<typename BasicJsonType, typename SAX = json_sax_dom_parser<BasicJsonType>>
6012+class binary_reader
6013+{
6014+ using number_integer_t = typename BasicJsonType::number_integer_t;
6015+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
6016+ using number_float_t = typename BasicJsonType::number_float_t;
6017+ using string_t = typename BasicJsonType::string_t;
6018+ using json_sax_t = SAX;
6019+
6020+ public:
6021+ /*!
6022+ @brief create a binary reader
6023+
6024+ @param[in] adapter input adapter to read from
6025+ */
6026+ explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
6027+ {
6028+ (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
6029+ assert(ia);
6030+ }
6031+
6032+ /*!
6033+ @param[in] format the binary format to parse
6034+ @param[in] sax_ a SAX event processor
6035+ @param[in] strict whether to expect the input to be consumed completed
6036+
6037+ @return
6038+ */
6039+ bool sax_parse(const input_format_t format,
6040+ json_sax_t* sax_,
6041+ const bool strict = true)
6042+ {
6043+ sax = sax_;
6044+ bool result = false;
6045+
6046+ switch (format)
6047+ {
6048+ case input_format_t::cbor:
6049+ result = parse_cbor_internal();
6050+ break;
6051+
6052+ case input_format_t::msgpack:
6053+ result = parse_msgpack_internal();
6054+ break;
6055+
6056+ case input_format_t::ubjson:
6057+ result = parse_ubjson_internal();
6058+ break;
6059+
6060+ // LCOV_EXCL_START
6061+ default:
6062+ assert(false);
6063+ // LCOV_EXCL_STOP
6064+ }
6065+
6066+ // strict mode: next byte must be EOF
6067+ if (result and strict)
6068+ {
6069+ if (format == input_format_t::ubjson)
6070+ {
6071+ get_ignore_noop();
6072+ }
6073+ else
6074+ {
6075+ get();
6076+ }
6077+
6078+ if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
6079+ {
6080+ return sax->parse_error(chars_read, get_token_string(), parse_error::create(110, chars_read, "expected end of input"));
6081+ }
6082+ }
6083+
6084+ return result;
6085+ }
6086+
6087+ /*!
6088+ @brief determine system byte order
6089+
6090+ @return true if and only if system's byte order is little endian
6091+
6092+ @note from http://stackoverflow.com/a/1001328/266378
6093+ */
6094+ static constexpr bool little_endianess(int num = 1) noexcept
6095+ {
6096+ return (*reinterpret_cast<char*>(&num) == 1);
6097+ }
6098+
6099+ private:
6100+ /*!
6101+ @param[in] get_char whether a new character should be retrieved from the
6102+ input (true, default) or whether the last read
6103+ character should be considered instead
6104+
6105+ @return whether a valid CBOR value was passed to the SAX parser
6106+ */
6107+ bool parse_cbor_internal(const bool get_char = true)
6108+ {
6109+ switch (get_char ? get() : current)
6110+ {
6111+ // EOF
6112+ case std::char_traits<char>::eof():
6113+ return unexpect_eof();
6114+
6115+ // Integer 0x00..0x17 (0..23)
6116+ case 0x00:
6117+ case 0x01:
6118+ case 0x02:
6119+ case 0x03:
6120+ case 0x04:
6121+ case 0x05:
6122+ case 0x06:
6123+ case 0x07:
6124+ case 0x08:
6125+ case 0x09:
6126+ case 0x0A:
6127+ case 0x0B:
6128+ case 0x0C:
6129+ case 0x0D:
6130+ case 0x0E:
6131+ case 0x0F:
6132+ case 0x10:
6133+ case 0x11:
6134+ case 0x12:
6135+ case 0x13:
6136+ case 0x14:
6137+ case 0x15:
6138+ case 0x16:
6139+ case 0x17:
6140+ return sax->number_unsigned(static_cast<number_unsigned_t>(current));
6141+
6142+ case 0x18: // Unsigned integer (one-byte uint8_t follows)
6143+ {
6144+ uint8_t number;
6145+ return get_number(number) and sax->number_unsigned(number);
6146+ }
6147+
6148+ case 0x19: // Unsigned integer (two-byte uint16_t follows)
6149+ {
6150+ uint16_t number;
6151+ return get_number(number) and sax->number_unsigned(number);
6152+ }
6153+
6154+ case 0x1A: // Unsigned integer (four-byte uint32_t follows)
6155+ {
6156+ uint32_t number;
6157+ return get_number(number) and sax->number_unsigned(number);
6158+ }
6159+
6160+ case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
6161+ {
6162+ uint64_t number;
6163+ return get_number(number) and sax->number_unsigned(number);
6164+ }
6165+
6166+ // Negative integer -1-0x00..-1-0x17 (-1..-24)
6167+ case 0x20:
6168+ case 0x21:
6169+ case 0x22:
6170+ case 0x23:
6171+ case 0x24:
6172+ case 0x25:
6173+ case 0x26:
6174+ case 0x27:
6175+ case 0x28:
6176+ case 0x29:
6177+ case 0x2A:
6178+ case 0x2B:
6179+ case 0x2C:
6180+ case 0x2D:
6181+ case 0x2E:
6182+ case 0x2F:
6183+ case 0x30:
6184+ case 0x31:
6185+ case 0x32:
6186+ case 0x33:
6187+ case 0x34:
6188+ case 0x35:
6189+ case 0x36:
6190+ case 0x37:
6191+ return sax->number_integer(static_cast<int8_t>(0x20 - 1 - current));
6192+
6193+ case 0x38: // Negative integer (one-byte uint8_t follows)
6194+ {
6195+ uint8_t number;
6196+ return get_number(number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
6197+ }
6198+
6199+ case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
6200+ {
6201+ uint16_t number;
6202+ return get_number(number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
6203+ }
6204+
6205+ case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
6206+ {
6207+ uint32_t number;
6208+ return get_number(number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
6209+ }
6210+
6211+ case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
6212+ {
6213+ uint64_t number;
6214+ return get_number(number) and sax->number_integer(static_cast<number_integer_t>(-1)
6215+ - static_cast<number_integer_t>(number));
6216+ }
6217+
6218+ // UTF-8 string (0x00..0x17 bytes follow)
6219+ case 0x60:
6220+ case 0x61:
6221+ case 0x62:
6222+ case 0x63:
6223+ case 0x64:
6224+ case 0x65:
6225+ case 0x66:
6226+ case 0x67:
6227+ case 0x68:
6228+ case 0x69:
6229+ case 0x6A:
6230+ case 0x6B:
6231+ case 0x6C:
6232+ case 0x6D:
6233+ case 0x6E:
6234+ case 0x6F:
6235+ case 0x70:
6236+ case 0x71:
6237+ case 0x72:
6238+ case 0x73:
6239+ case 0x74:
6240+ case 0x75:
6241+ case 0x76:
6242+ case 0x77:
6243+ case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
6244+ case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
6245+ case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
6246+ case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
6247+ case 0x7F: // UTF-8 string (indefinite length)
6248+ {
6249+ string_t s;
6250+ return get_cbor_string(s) and sax->string(s);
6251+ }
6252+
6253+ // array (0x00..0x17 data items follow)
6254+ case 0x80:
6255+ case 0x81:
6256+ case 0x82:
6257+ case 0x83:
6258+ case 0x84:
6259+ case 0x85:
6260+ case 0x86:
6261+ case 0x87:
6262+ case 0x88:
6263+ case 0x89:
6264+ case 0x8A:
6265+ case 0x8B:
6266+ case 0x8C:
6267+ case 0x8D:
6268+ case 0x8E:
6269+ case 0x8F:
6270+ case 0x90:
6271+ case 0x91:
6272+ case 0x92:
6273+ case 0x93:
6274+ case 0x94:
6275+ case 0x95:
6276+ case 0x96:
6277+ case 0x97:
6278+ return get_cbor_array(static_cast<std::size_t>(current & 0x1F));
6279+
6280+ case 0x98: // array (one-byte uint8_t for n follows)
6281+ {
6282+ uint8_t len;
6283+ return get_number(len) and get_cbor_array(static_cast<std::size_t>(len));
6284+ }
6285+
6286+ case 0x99: // array (two-byte uint16_t for n follow)
6287+ {
6288+ uint16_t len;
6289+ return get_number(len) and get_cbor_array(static_cast<std::size_t>(len));
6290+ }
6291+
6292+ case 0x9A: // array (four-byte uint32_t for n follow)
6293+ {
6294+ uint32_t len;
6295+ return get_number(len) and get_cbor_array(static_cast<std::size_t>(len));
6296+ }
6297+
6298+ case 0x9B: // array (eight-byte uint64_t for n follow)
6299+ {
6300+ uint64_t len;
6301+ return get_number(len) and get_cbor_array(static_cast<std::size_t>(len));
6302+ }
6303+
6304+ case 0x9F: // array (indefinite length)
6305+ return get_cbor_array(std::size_t(-1));
6306+
6307+ // map (0x00..0x17 pairs of data items follow)
6308+ case 0xA0:
6309+ case 0xA1:
6310+ case 0xA2:
6311+ case 0xA3:
6312+ case 0xA4:
6313+ case 0xA5:
6314+ case 0xA6:
6315+ case 0xA7:
6316+ case 0xA8:
6317+ case 0xA9:
6318+ case 0xAA:
6319+ case 0xAB:
6320+ case 0xAC:
6321+ case 0xAD:
6322+ case 0xAE:
6323+ case 0xAF:
6324+ case 0xB0:
6325+ case 0xB1:
6326+ case 0xB2:
6327+ case 0xB3:
6328+ case 0xB4:
6329+ case 0xB5:
6330+ case 0xB6:
6331+ case 0xB7:
6332+ return get_cbor_object(static_cast<std::size_t>(current & 0x1F));
6333+
6334+ case 0xB8: // map (one-byte uint8_t for n follows)
6335+ {
6336+ uint8_t len;
6337+ return get_number(len) and get_cbor_object(static_cast<std::size_t>(len));
6338+ }
6339+
6340+ case 0xB9: // map (two-byte uint16_t for n follow)
6341+ {
6342+ uint16_t len;
6343+ return get_number(len) and get_cbor_object(static_cast<std::size_t>(len));
6344+ }
6345+
6346+ case 0xBA: // map (four-byte uint32_t for n follow)
6347+ {
6348+ uint32_t len;
6349+ return get_number(len) and get_cbor_object(static_cast<std::size_t>(len));
6350+ }
6351+
6352+ case 0xBB: // map (eight-byte uint64_t for n follow)
6353+ {
6354+ uint64_t len;
6355+ return get_number(len) and get_cbor_object(static_cast<std::size_t>(len));
6356+ }
6357+
6358+ case 0xBF: // map (indefinite length)
6359+ return get_cbor_object(std::size_t(-1));
6360+
6361+ case 0xF4: // false
6362+ return sax->boolean(false);
6363+
6364+ case 0xF5: // true
6365+ return sax->boolean(true);
6366+
6367+ case 0xF6: // null
6368+ return sax->null();
6369+
6370+ case 0xF9: // Half-Precision Float (two-byte IEEE 754)
6371+ {
6372+ const int byte1 = get();
6373+ if (JSON_UNLIKELY(not unexpect_eof()))
6374+ {
6375+ return false;
6376+ }
6377+ const int byte2 = get();
6378+ if (JSON_UNLIKELY(not unexpect_eof()))
6379+ {
6380+ return false;
6381+ }
6382+
6383+ // code from RFC 7049, Appendix D, Figure 3:
6384+ // As half-precision floating-point numbers were only added
6385+ // to IEEE 754 in 2008, today's programming platforms often
6386+ // still only have limited support for them. It is very
6387+ // easy to include at least decoding support for them even
6388+ // without such support. An example of a small decoder for
6389+ // half-precision floating-point numbers in the C language
6390+ // is shown in Fig. 3.
6391+ const int half = (byte1 << 8) + byte2;
6392+ const double val = [&half]
6393+ {
6394+ const int exp = (half >> 10) & 0x1F;
6395+ const int mant = half & 0x3FF;
6396+ assert(0 <= exp and exp <= 32);
6397+ assert(0 <= mant and mant <= 1024);
6398+ switch (exp)
6399+ {
6400+ case 0:
6401+ return std::ldexp(mant, -24);
6402+ case 31:
6403+ return (mant == 0)
6404+ ? std::numeric_limits<double>::infinity()
6405+ : std::numeric_limits<double>::quiet_NaN();
6406+ default:
6407+ return std::ldexp(mant + 1024, exp - 25);
6408+ }
6409+ }();
6410+ return sax->number_float((half & 0x8000) != 0
6411+ ? static_cast<number_float_t>(-val)
6412+ : static_cast<number_float_t>(val), "");
6413+ }
6414+
6415+ case 0xFA: // Single-Precision Float (four-byte IEEE 754)
6416+ {
6417+ float number;
6418+ return get_number(number) and sax->number_float(static_cast<number_float_t>(number), "");
6419+ }
6420+
6421+ case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
6422+ {
6423+ double number;
6424+ return get_number(number) and sax->number_float(static_cast<number_float_t>(number), "");
6425+ }
6426+
6427+ default: // anything else (0xFF is handled inside the other types)
6428+ {
6429+ auto last_token = get_token_string();
6430+ return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + last_token));
6431+ }
6432+ }
6433+ }
6434+
6435+ /*!
6436+ @return whether a valid MessagePack value was passed to the SAX parser
6437+ */
6438+ bool parse_msgpack_internal()
6439+ {
6440+ switch (get())
6441+ {
6442+ // EOF
6443+ case std::char_traits<char>::eof():
6444+ return unexpect_eof();
6445+
6446+ // positive fixint
6447+ case 0x00:
6448+ case 0x01:
6449+ case 0x02:
6450+ case 0x03:
6451+ case 0x04:
6452+ case 0x05:
6453+ case 0x06:
6454+ case 0x07:
6455+ case 0x08:
6456+ case 0x09:
6457+ case 0x0A:
6458+ case 0x0B:
6459+ case 0x0C:
6460+ case 0x0D:
6461+ case 0x0E:
6462+ case 0x0F:
6463+ case 0x10:
6464+ case 0x11:
6465+ case 0x12:
6466+ case 0x13:
6467+ case 0x14:
6468+ case 0x15:
6469+ case 0x16:
6470+ case 0x17:
6471+ case 0x18:
6472+ case 0x19:
6473+ case 0x1A:
6474+ case 0x1B:
6475+ case 0x1C:
6476+ case 0x1D:
6477+ case 0x1E:
6478+ case 0x1F:
6479+ case 0x20:
6480+ case 0x21:
6481+ case 0x22:
6482+ case 0x23:
6483+ case 0x24:
6484+ case 0x25:
6485+ case 0x26:
6486+ case 0x27:
6487+ case 0x28:
6488+ case 0x29:
6489+ case 0x2A:
6490+ case 0x2B:
6491+ case 0x2C:
6492+ case 0x2D:
6493+ case 0x2E:
6494+ case 0x2F:
6495+ case 0x30:
6496+ case 0x31:
6497+ case 0x32:
6498+ case 0x33:
6499+ case 0x34:
6500+ case 0x35:
6501+ case 0x36:
6502+ case 0x37:
6503+ case 0x38:
6504+ case 0x39:
6505+ case 0x3A:
6506+ case 0x3B:
6507+ case 0x3C:
6508+ case 0x3D:
6509+ case 0x3E:
6510+ case 0x3F:
6511+ case 0x40:
6512+ case 0x41:
6513+ case 0x42:
6514+ case 0x43:
6515+ case 0x44:
6516+ case 0x45:
6517+ case 0x46:
6518+ case 0x47:
6519+ case 0x48:
6520+ case 0x49:
6521+ case 0x4A:
6522+ case 0x4B:
6523+ case 0x4C:
6524+ case 0x4D:
6525+ case 0x4E:
6526+ case 0x4F:
6527+ case 0x50:
6528+ case 0x51:
6529+ case 0x52:
6530+ case 0x53:
6531+ case 0x54:
6532+ case 0x55:
6533+ case 0x56:
6534+ case 0x57:
6535+ case 0x58:
6536+ case 0x59:
6537+ case 0x5A:
6538+ case 0x5B:
6539+ case 0x5C:
6540+ case 0x5D:
6541+ case 0x5E:
6542+ case 0x5F:
6543+ case 0x60:
6544+ case 0x61:
6545+ case 0x62:
6546+ case 0x63:
6547+ case 0x64:
6548+ case 0x65:
6549+ case 0x66:
6550+ case 0x67:
6551+ case 0x68:
6552+ case 0x69:
6553+ case 0x6A:
6554+ case 0x6B:
6555+ case 0x6C:
6556+ case 0x6D:
6557+ case 0x6E:
6558+ case 0x6F:
6559+ case 0x70:
6560+ case 0x71:
6561+ case 0x72:
6562+ case 0x73:
6563+ case 0x74:
6564+ case 0x75:
6565+ case 0x76:
6566+ case 0x77:
6567+ case 0x78:
6568+ case 0x79:
6569+ case 0x7A:
6570+ case 0x7B:
6571+ case 0x7C:
6572+ case 0x7D:
6573+ case 0x7E:
6574+ case 0x7F:
6575+ return sax->number_unsigned(static_cast<number_unsigned_t>(current));
6576+
6577+ // fixmap
6578+ case 0x80:
6579+ case 0x81:
6580+ case 0x82:
6581+ case 0x83:
6582+ case 0x84:
6583+ case 0x85:
6584+ case 0x86:
6585+ case 0x87:
6586+ case 0x88:
6587+ case 0x89:
6588+ case 0x8A:
6589+ case 0x8B:
6590+ case 0x8C:
6591+ case 0x8D:
6592+ case 0x8E:
6593+ case 0x8F:
6594+ return get_msgpack_object(static_cast<std::size_t>(current & 0x0F));
6595+
6596+ // fixarray
6597+ case 0x90:
6598+ case 0x91:
6599+ case 0x92:
6600+ case 0x93:
6601+ case 0x94:
6602+ case 0x95:
6603+ case 0x96:
6604+ case 0x97:
6605+ case 0x98:
6606+ case 0x99:
6607+ case 0x9A:
6608+ case 0x9B:
6609+ case 0x9C:
6610+ case 0x9D:
6611+ case 0x9E:
6612+ case 0x9F:
6613+ return get_msgpack_array(static_cast<std::size_t>(current & 0x0F));
6614+
6615+ // fixstr
6616+ case 0xA0:
6617+ case 0xA1:
6618+ case 0xA2:
6619+ case 0xA3:
6620+ case 0xA4:
6621+ case 0xA5:
6622+ case 0xA6:
6623+ case 0xA7:
6624+ case 0xA8:
6625+ case 0xA9:
6626+ case 0xAA:
6627+ case 0xAB:
6628+ case 0xAC:
6629+ case 0xAD:
6630+ case 0xAE:
6631+ case 0xAF:
6632+ case 0xB0:
6633+ case 0xB1:
6634+ case 0xB2:
6635+ case 0xB3:
6636+ case 0xB4:
6637+ case 0xB5:
6638+ case 0xB6:
6639+ case 0xB7:
6640+ case 0xB8:
6641+ case 0xB9:
6642+ case 0xBA:
6643+ case 0xBB:
6644+ case 0xBC:
6645+ case 0xBD:
6646+ case 0xBE:
6647+ case 0xBF:
6648+ {
6649+ string_t s;
6650+ return get_msgpack_string(s) and sax->string(s);
6651+ }
6652+
6653+ case 0xC0: // nil
6654+ return sax->null();
6655+
6656+ case 0xC2: // false
6657+ return sax->boolean(false);
6658+
6659+ case 0xC3: // true
6660+ return sax->boolean(true);
6661+
6662+ case 0xCA: // float 32
6663+ {
6664+ float number;
6665+ return get_number(number) and sax->number_float(static_cast<number_float_t>(number), "");
6666+ }
6667+
6668+ case 0xCB: // float 64
6669+ {
6670+ double number;
6671+ return get_number(number) and sax->number_float(static_cast<number_float_t>(number), "");
6672+ }
6673+
6674+ case 0xCC: // uint 8
6675+ {
6676+ uint8_t number;
6677+ return get_number(number) and sax->number_unsigned(number);
6678+ }
6679+
6680+ case 0xCD: // uint 16
6681+ {
6682+ uint16_t number;
6683+ return get_number(number) and sax->number_unsigned(number);
6684+ }
6685+
6686+ case 0xCE: // uint 32
6687+ {
6688+ uint32_t number;
6689+ return get_number(number) and sax->number_unsigned(number);
6690+ }
6691+
6692+ case 0xCF: // uint 64
6693+ {
6694+ uint64_t number;
6695+ return get_number(number) and sax->number_unsigned(number);
6696+ }
6697+
6698+ case 0xD0: // int 8
6699+ {
6700+ int8_t number;
6701+ return get_number(number) and sax->number_integer(number);
6702+ }
6703+
6704+ case 0xD1: // int 16
6705+ {
6706+ int16_t number;
6707+ return get_number(number) and sax->number_integer(number);
6708+ }
6709+
6710+ case 0xD2: // int 32
6711+ {
6712+ int32_t number;
6713+ return get_number(number) and sax->number_integer(number);
6714+ }
6715+
6716+ case 0xD3: // int 64
6717+ {
6718+ int64_t number;
6719+ return get_number(number) and sax->number_integer(number);
6720+ }
6721+
6722+ case 0xD9: // str 8
6723+ case 0xDA: // str 16
6724+ case 0xDB: // str 32
6725+ {
6726+ string_t s;
6727+ return get_msgpack_string(s) and sax->string(s);
6728+ }
6729+
6730+ case 0xDC: // array 16
6731+ {
6732+ uint16_t len;
6733+ return get_number(len) and get_msgpack_array(static_cast<std::size_t>(len));
6734+ }
6735+
6736+ case 0xDD: // array 32
6737+ {
6738+ uint32_t len;
6739+ return get_number(len) and get_msgpack_array(static_cast<std::size_t>(len));
6740+ }
6741+
6742+ case 0xDE: // map 16
6743+ {
6744+ uint16_t len;
6745+ return get_number(len) and get_msgpack_object(static_cast<std::size_t>(len));
6746+ }
6747+
6748+ case 0xDF: // map 32
6749+ {
6750+ uint32_t len;
6751+ return get_number(len) and get_msgpack_object(static_cast<std::size_t>(len));
6752+ }
6753+
6754+ // negative fixint
6755+ case 0xE0:
6756+ case 0xE1:
6757+ case 0xE2:
6758+ case 0xE3:
6759+ case 0xE4:
6760+ case 0xE5:
6761+ case 0xE6:
6762+ case 0xE7:
6763+ case 0xE8:
6764+ case 0xE9:
6765+ case 0xEA:
6766+ case 0xEB:
6767+ case 0xEC:
6768+ case 0xED:
6769+ case 0xEE:
6770+ case 0xEF:
6771+ case 0xF0:
6772+ case 0xF1:
6773+ case 0xF2:
6774+ case 0xF3:
6775+ case 0xF4:
6776+ case 0xF5:
6777+ case 0xF6:
6778+ case 0xF7:
6779+ case 0xF8:
6780+ case 0xF9:
6781+ case 0xFA:
6782+ case 0xFB:
6783+ case 0xFC:
6784+ case 0xFD:
6785+ case 0xFE:
6786+ case 0xFF:
6787+ return sax->number_integer(static_cast<int8_t>(current));
6788+
6789+ default: // anything else
6790+ {
6791+ auto last_token = get_token_string();
6792+ return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, "error reading MessagePack; last byte: 0x" + last_token));
6793+ }
6794+ }
6795+ }
6796+
6797+ /*!
6798+ @param[in] get_char whether a new character should be retrieved from the
6799+ input (true, default) or whether the last read
6800+ character should be considered instead
6801+
6802+ @return whether a valid UBJSON value was passed to the SAX parser
6803+ */
6804+ bool parse_ubjson_internal(const bool get_char = true)
6805+ {
6806+ return get_ubjson_value(get_char ? get_ignore_noop() : current);
6807+ }
6808+
6809+ /*!
6810+ @brief get next character from the input
6811+
6812+ This function provides the interface to the used input adapter. It does
6813+ not throw in case the input reached EOF, but returns a -'ve valued
6814+ `std::char_traits<char>::eof()` in that case.
6815+
6816+ @return character read from the input
6817+ */
6818+ int get()
6819+ {
6820+ ++chars_read;
6821+ return (current = ia->get_character());
6822+ }
6823+
6824+ /*!
6825+ @return character read from the input after ignoring all 'N' entries
6826+ */
6827+ int get_ignore_noop()
6828+ {
6829+ do
6830+ {
6831+ get();
6832+ }
6833+ while (current == 'N');
6834+
6835+ return current;
6836+ }
6837+
6838+ /*
6839+ @brief read a number from the input
6840+
6841+ @tparam NumberType the type of the number
6842+ @param[out] result number of type @a NumberType
6843+
6844+ @return whether conversion completed
6845+
6846+ @note This function needs to respect the system's endianess, because
6847+ bytes in CBOR, MessagePack, and UBJSON are stored in network order
6848+ (big endian) and therefore need reordering on little endian systems.
6849+ */
6850+ template<typename NumberType>
6851+ bool get_number(NumberType& result)
6852+ {
6853+ // step 1: read input into array with system's byte order
6854+ std::array<uint8_t, sizeof(NumberType)> vec;
6855+ for (std::size_t i = 0; i < sizeof(NumberType); ++i)
6856+ {
6857+ get();
6858+ if (JSON_UNLIKELY(not unexpect_eof()))
6859+ {
6860+ return false;
6861+ }
6862+
6863+ // reverse byte order prior to conversion if necessary
6864+ if (is_little_endian)
6865+ {
6866+ vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);
6867+ }
6868+ else
6869+ {
6870+ vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE
6871+ }
6872+ }
6873+
6874+ // step 2: convert array into number of type T and return
6875+ std::memcpy(&result, vec.data(), sizeof(NumberType));
6876+ return true;
6877+ }
6878+
6879+ /*!
6880+ @brief create a string by reading characters from the input
6881+
6882+ @tparam NumberType the type of the number
6883+ @param[in] len number of characters to read
6884+ @param[out] string created by reading @a len bytes
6885+
6886+ @return whether string creation completed
6887+
6888+ @note We can not reserve @a len bytes for the result, because @a len
6889+ may be too large. Usually, @ref unexpect_eof() detects the end of
6890+ the input before we run out of string memory.
6891+ */
6892+ template<typename NumberType>
6893+ bool get_string(const NumberType len, string_t& result)
6894+ {
6895+ bool success = true;
6896+ std::generate_n(std::back_inserter(result), len, [this, &success]()
6897+ {
6898+ get();
6899+ if (JSON_UNLIKELY(not unexpect_eof()))
6900+ {
6901+ success = false;
6902+ }
6903+ return static_cast<char>(current);
6904+ });
6905+ return success;
6906+ }
6907+
6908+ /*!
6909+ @brief reads a CBOR string
6910+
6911+ This function first reads starting bytes to determine the expected
6912+ string length and then copies this number of bytes into a string.
6913+ Additionally, CBOR's strings with indefinite lengths are supported.
6914+
6915+ @param[out] result created string
6916+
6917+ @return whether string creation completed
6918+ */
6919+ bool get_cbor_string(string_t& result)
6920+ {
6921+ if (JSON_UNLIKELY(not unexpect_eof()))
6922+ {
6923+ return false;
6924+ }
6925+
6926+ switch (current)
6927+ {
6928+ // UTF-8 string (0x00..0x17 bytes follow)
6929+ case 0x60:
6930+ case 0x61:
6931+ case 0x62:
6932+ case 0x63:
6933+ case 0x64:
6934+ case 0x65:
6935+ case 0x66:
6936+ case 0x67:
6937+ case 0x68:
6938+ case 0x69:
6939+ case 0x6A:
6940+ case 0x6B:
6941+ case 0x6C:
6942+ case 0x6D:
6943+ case 0x6E:
6944+ case 0x6F:
6945+ case 0x70:
6946+ case 0x71:
6947+ case 0x72:
6948+ case 0x73:
6949+ case 0x74:
6950+ case 0x75:
6951+ case 0x76:
6952+ case 0x77:
6953+ {
6954+ return get_string(current & 0x1F, result);
6955+ }
6956+
6957+ case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
6958+ {
6959+ uint8_t len;
6960+ return get_number(len) and get_string(len, result);
6961+ }
6962+
6963+ case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
6964+ {
6965+ uint16_t len;
6966+ return get_number(len) and get_string(len, result);
6967+ }
6968+
6969+ case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
6970+ {
6971+ uint32_t len;
6972+ return get_number(len) and get_string(len, result);
6973+ }
6974+
6975+ case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
6976+ {
6977+ uint64_t len;
6978+ return get_number(len) and get_string(len, result);
6979+ }
6980+
6981+ case 0x7F: // UTF-8 string (indefinite length)
6982+ {
6983+ while (get() != 0xFF)
6984+ {
6985+ string_t chunk;
6986+ if (not get_cbor_string(chunk))
6987+ {
6988+ return false;
6989+ }
6990+ result.append(chunk);
6991+ }
6992+ return true;
6993+ }
6994+
6995+ default:
6996+ {
6997+ auto last_token = get_token_string();
6998+ return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + last_token));
6999+ }
7000+ }
7001+ }
7002+
7003+ /*!
7004+ @param[in] len the length of the array or std::size_t(-1) for an
7005+ array of indefinite size
7006+ @return whether array creation completed
7007+ */
7008+ bool get_cbor_array(const std::size_t len)
7009+ {
7010+ if (JSON_UNLIKELY(not sax->start_array(len)))
7011+ {
7012+ return false;
7013+ }
7014+
7015+ if (len != std::size_t(-1))
7016+ for (std::size_t i = 0; i < len; ++i)
7017+ {
7018+ if (JSON_UNLIKELY(not parse_cbor_internal()))
7019+ {
7020+ return false;
7021+ }
7022+ }
7023+ else
7024+ {
7025+ while (get() != 0xFF)
7026+ {
7027+ if (JSON_UNLIKELY(not parse_cbor_internal(false)))
7028+ {
7029+ return false;
7030+ }
7031+ }
7032+ }
7033+
7034+ return sax->end_array();
7035+ }
7036+
7037+ /*!
7038+ @param[in] len the length of the object or std::size_t(-1) for an
7039+ object of indefinite size
7040+ @return whether object creation completed
7041+ */
7042+ bool get_cbor_object(const std::size_t len)
7043+ {
7044+ if (not JSON_UNLIKELY(sax->start_object(len)))
7045+ {
7046+ return false;
7047+ }
7048+
7049+ string_t key;
7050+ if (len != std::size_t(-1))
7051+ {
7052+ for (std::size_t i = 0; i < len; ++i)
7053+ {
7054+ get();
7055+ if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
7056+ {
7057+ return false;
7058+ }
7059+
7060+ if (JSON_UNLIKELY(not parse_cbor_internal()))
7061+ {
7062+ return false;
7063+ }
7064+ key.clear();
7065+ }
7066+ }
7067+ else
7068+ {
7069+ while (get() != 0xFF)
7070+ {
7071+ if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
7072+ {
7073+ return false;
7074+ }
7075+
7076+ if (JSON_UNLIKELY(not parse_cbor_internal()))
7077+ {
7078+ return false;
7079+ }
7080+ key.clear();
7081+ }
7082+ }
7083+
7084+ return sax->end_object();
7085+ }
7086+
7087+ /*!
7088+ @brief reads a MessagePack string
7089+
7090+ This function first reads starting bytes to determine the expected
7091+ string length and then copies this number of bytes into a string.
7092+
7093+ @param[out] result created string
7094+
7095+ @return whether string creation completed
7096+ */
7097+ bool get_msgpack_string(string_t& result)
7098+ {
7099+ if (JSON_UNLIKELY(not unexpect_eof()))
7100+ {
7101+ return false;
7102+ }
7103+
7104+ switch (current)
7105+ {
7106+ // fixstr
7107+ case 0xA0:
7108+ case 0xA1:
7109+ case 0xA2:
7110+ case 0xA3:
7111+ case 0xA4:
7112+ case 0xA5:
7113+ case 0xA6:
7114+ case 0xA7:
7115+ case 0xA8:
7116+ case 0xA9:
7117+ case 0xAA:
7118+ case 0xAB:
7119+ case 0xAC:
7120+ case 0xAD:
7121+ case 0xAE:
7122+ case 0xAF:
7123+ case 0xB0:
7124+ case 0xB1:
7125+ case 0xB2:
7126+ case 0xB3:
7127+ case 0xB4:
7128+ case 0xB5:
7129+ case 0xB6:
7130+ case 0xB7:
7131+ case 0xB8:
7132+ case 0xB9:
7133+ case 0xBA:
7134+ case 0xBB:
7135+ case 0xBC:
7136+ case 0xBD:
7137+ case 0xBE:
7138+ case 0xBF:
7139+ {
7140+ return get_string(current & 0x1F, result);
7141+ }
7142+
7143+ case 0xD9: // str 8
7144+ {
7145+ uint8_t len;
7146+ return get_number(len) and get_string(len, result);
7147+ }
7148+
7149+ case 0xDA: // str 16
7150+ {
7151+ uint16_t len;
7152+ return get_number(len) and get_string(len, result);
7153+ }
7154+
7155+ case 0xDB: // str 32
7156+ {
7157+ uint32_t len;
7158+ return get_number(len) and get_string(len, result);
7159+ }
7160+
7161+ default:
7162+ {
7163+ auto last_token = get_token_string();
7164+ return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "expected a MessagePack string; last byte: 0x" + last_token));
7165+ }
7166+ }
7167+ }
7168+
7169+ /*!
7170+ @param[in] len the length of the array
7171+ @return whether array creation completed
7172+ */
7173+ bool get_msgpack_array(const std::size_t len)
7174+ {
7175+ if (JSON_UNLIKELY(not sax->start_array(len)))
7176+ {
7177+ return false;
7178+ }
7179+
7180+ for (std::size_t i = 0; i < len; ++i)
7181+ {
7182+ if (JSON_UNLIKELY(not parse_msgpack_internal()))
7183+ {
7184+ return false;
7185+ }
7186+ }
7187+
7188+ return sax->end_array();
7189+ }
7190+
7191+ /*!
7192+ @param[in] len the length of the object
7193+ @return whether object creation completed
7194+ */
7195+ bool get_msgpack_object(const std::size_t len)
7196+ {
7197+ if (JSON_UNLIKELY(not sax->start_object(len)))
7198+ {
7199+ return false;
7200+ }
7201+
7202+ string_t key;
7203+ for (std::size_t i = 0; i < len; ++i)
7204+ {
7205+ get();
7206+ if (JSON_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
7207+ {
7208+ return false;
7209+ }
7210+
7211+ if (JSON_UNLIKELY(not parse_msgpack_internal()))
7212+ {
7213+ return false;
7214+ }
7215+ key.clear();
7216+ }
7217+
7218+ return sax->end_object();
7219+ }
7220+
7221+ /*!
7222+ @brief reads a UBJSON string
7223+
7224+ This function is either called after reading the 'S' byte explicitly
7225+ indicating a string, or in case of an object key where the 'S' byte can be
7226+ left out.
7227+
7228+ @param[out] result created string
7229+ @param[in] get_char whether a new character should be retrieved from the
7230+ input (true, default) or whether the last read
7231+ character should be considered instead
7232+
7233+ @return whether string creation completed
7234+ */
7235+ bool get_ubjson_string(string_t& result, const bool get_char = true)
7236+ {
7237+ if (get_char)
7238+ {
7239+ get(); // TODO: may we ignore N here?
7240+ }
7241+
7242+ if (JSON_UNLIKELY(not unexpect_eof()))
7243+ {
7244+ return false;
7245+ }
7246+
7247+ switch (current)
7248+ {
7249+ case 'U':
7250+ {
7251+ uint8_t len;
7252+ return get_number(len) and get_string(len, result);
7253+ }
7254+
7255+ case 'i':
7256+ {
7257+ int8_t len;
7258+ return get_number(len) and get_string(len, result);
7259+ }
7260+
7261+ case 'I':
7262+ {
7263+ int16_t len;
7264+ return get_number(len) and get_string(len, result);
7265+ }
7266+
7267+ case 'l':
7268+ {
7269+ int32_t len;
7270+ return get_number(len) and get_string(len, result);
7271+ }
7272+
7273+ case 'L':
7274+ {
7275+ int64_t len;
7276+ return get_number(len) and get_string(len, result);
7277+ }
7278+
7279+ default:
7280+ auto last_token = get_token_string();
7281+ return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "expected a UBJSON string; last byte: 0x" + last_token));
7282+ }
7283+ }
7284+
7285+ /*!
7286+ @param[out] result determined size
7287+ @return whether size determination completed
7288+ */
7289+ bool get_ubjson_size_value(std::size_t& result)
7290+ {
7291+ switch (get_ignore_noop())
7292+ {
7293+ case 'U':
7294+ {
7295+ uint8_t number;
7296+ if (JSON_UNLIKELY(not get_number(number)))
7297+ {
7298+ return false;
7299+ }
7300+ result = static_cast<std::size_t>(number);
7301+ return true;
7302+ }
7303+
7304+ case 'i':
7305+ {
7306+ int8_t number;
7307+ if (JSON_UNLIKELY(not get_number(number)))
7308+ {
7309+ return false;
7310+ }
7311+ result = static_cast<std::size_t>(number);
7312+ return true;
7313+ }
7314+
7315+ case 'I':
7316+ {
7317+ int16_t number;
7318+ if (JSON_UNLIKELY(not get_number(number)))
7319+ {
7320+ return false;
7321+ }
7322+ result = static_cast<std::size_t>(number);
7323+ return true;
7324+ }
7325+
7326+ case 'l':
7327+ {
7328+ int32_t number;
7329+ if (JSON_UNLIKELY(not get_number(number)))
7330+ {
7331+ return false;
7332+ }
7333+ result = static_cast<std::size_t>(number);
7334+ return true;
7335+ }
7336+
7337+ case 'L':
7338+ {
7339+ int64_t number;
7340+ if (JSON_UNLIKELY(not get_number(number)))
7341+ {
7342+ return false;
7343+ }
7344+ result = static_cast<std::size_t>(number);
7345+ return true;
7346+ }
7347+
7348+ default:
7349+ {
7350+ auto last_token = get_token_string();
7351+ return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "byte after '#' must denote a number type; last byte: 0x" + last_token));
7352+ }
7353+ }
7354+ }
7355+
7356+ /*!
7357+ @brief determine the type and size for a container
7358+
7359+ In the optimized UBJSON format, a type and a size can be provided to allow
7360+ for a more compact representation.
7361+
7362+ @param[out] result pair of the size and the type
7363+
7364+ @return whether pair creation completed
7365+ */
7366+ bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
7367+ {
7368+ result.first = string_t::npos; // size
7369+ result.second = 0; // type
7370+
7371+ get_ignore_noop();
7372+
7373+ if (current == '$')
7374+ {
7375+ result.second = get(); // must not ignore 'N', because 'N' maybe the type
7376+ if (JSON_UNLIKELY(not unexpect_eof()))
7377+ {
7378+ return false;
7379+ }
7380+
7381+ get_ignore_noop();
7382+ if (JSON_UNLIKELY(current != '#'))
7383+ {
7384+ if (JSON_UNLIKELY(not unexpect_eof()))
7385+ {
7386+ return false;
7387+ }
7388+ auto last_token = get_token_string();
7389+ return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, "expected '#' after UBJSON type information; last byte: 0x" + last_token));
7390+ }
7391+
7392+ return get_ubjson_size_value(result.first);
7393+ }
7394+ else if (current == '#')
7395+ {
7396+ return get_ubjson_size_value(result.first);
7397+ }
7398+ return true;
7399+ }
7400+
7401+ /*!
7402+ @param prefix the previously read or set type prefix
7403+ @return whether value creation completed
7404+ */
7405+ bool get_ubjson_value(const int prefix)
7406+ {
7407+ switch (prefix)
7408+ {
7409+ case std::char_traits<char>::eof(): // EOF
7410+ return unexpect_eof();
7411+
7412+ case 'T': // true
7413+ return sax->boolean(true);
7414+ case 'F': // false
7415+ return sax->boolean(false);
7416+
7417+ case 'Z': // null
7418+ return sax->null();
7419+
7420+ case 'U':
7421+ {
7422+ uint8_t number;
7423+ return get_number(number) and sax->number_unsigned(number);
7424+ }
7425+
7426+ case 'i':
7427+ {
7428+ int8_t number;
7429+ return get_number(number) and sax->number_integer(number);
7430+ }
7431+
7432+ case 'I':
7433+ {
7434+ int16_t number;
7435+ return get_number(number) and sax->number_integer(number);
7436+ }
7437+
7438+ case 'l':
7439+ {
7440+ int32_t number;
7441+ return get_number(number) and sax->number_integer(number);
7442+ }
7443+
7444+ case 'L':
7445+ {
7446+ int64_t number;
7447+ return get_number(number) and sax->number_integer(number);
7448+ }
7449+
7450+ case 'd':
7451+ {
7452+ float number;
7453+ return get_number(number) and sax->number_float(static_cast<number_float_t>(number), "");
7454+ }
7455+
7456+ case 'D':
7457+ {
7458+ double number;
7459+ return get_number(number) and sax->number_float(static_cast<number_float_t>(number), "");
7460+ }
7461+
7462+ case 'C': // char
7463+ {
7464+ get();
7465+ if (JSON_UNLIKELY(not unexpect_eof()))
7466+ {
7467+ return false;
7468+ }
7469+ if (JSON_UNLIKELY(current > 127))
7470+ {
7471+ auto last_token = get_token_string();
7472+ return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token));
7473+ }
7474+ string_t s(1, static_cast<char>(current));
7475+ return sax->string(s);
7476+ }
7477+
7478+ case 'S': // string
7479+ {
7480+ string_t s;
7481+ return get_ubjson_string(s) and sax->string(s);
7482+ }
7483+
7484+ case '[': // array
7485+ return get_ubjson_array();
7486+
7487+ case '{': // object
7488+ return get_ubjson_object();
7489+
7490+ default: // anything else
7491+ {
7492+ auto last_token = get_token_string();
7493+ return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, "error reading UBJSON; last byte: 0x" + last_token));
7494+ }
7495+ }
7496+ }
7497+
7498+ /*!
7499+ @return whether array creation completed
7500+ */
7501+ bool get_ubjson_array()
7502+ {
7503+ std::pair<std::size_t, int> size_and_type;
7504+ if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type)))
7505+ {
7506+ return false;
7507+ }
7508+
7509+ if (size_and_type.first != string_t::npos)
7510+ {
7511+ if (JSON_UNLIKELY(not sax->start_array(size_and_type.first)))
7512+ {
7513+ return false;
7514+ }
7515+
7516+ if (size_and_type.second != 0)
7517+ {
7518+ if (size_and_type.second != 'N')
7519+ {
7520+ for (std::size_t i = 0; i < size_and_type.first; ++i)
7521+ {
7522+ if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second)))
7523+ {
7524+ return false;
7525+ }
7526+ }
7527+ }
7528+ }
7529+ else
7530+ {
7531+ for (std::size_t i = 0; i < size_and_type.first; ++i)
7532+ {
7533+ if (JSON_UNLIKELY(not parse_ubjson_internal()))
7534+ {
7535+ return false;
7536+ }
7537+ }
7538+ }
7539+ }
7540+ else
7541+ {
7542+ if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
7543+ {
7544+ return false;
7545+ }
7546+
7547+ while (current != ']')
7548+ {
7549+ if (JSON_UNLIKELY(not parse_ubjson_internal(false)))
7550+ {
7551+ return false;
7552+ }
7553+ get_ignore_noop();
7554+ }
7555+ }
7556+
7557+ return sax->end_array();
7558+ }
7559+
7560+ /*!
7561+ @return whether object creation completed
7562+ */
7563+ bool get_ubjson_object()
7564+ {
7565+ std::pair<std::size_t, int> size_and_type;
7566+ if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type)))
7567+ {
7568+ return false;
7569+ }
7570+
7571+ string_t key;
7572+ if (size_and_type.first != string_t::npos)
7573+ {
7574+ if (JSON_UNLIKELY(not sax->start_object(size_and_type.first)))
7575+ {
7576+ return false;
7577+ }
7578+
7579+ if (size_and_type.second != 0)
7580+ {
7581+ for (std::size_t i = 0; i < size_and_type.first; ++i)
7582+ {
7583+ if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
7584+ {
7585+ return false;
7586+ }
7587+ if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second)))
7588+ {
7589+ return false;
7590+ }
7591+ key.clear();
7592+ }
7593+ }
7594+ else
7595+ {
7596+ for (std::size_t i = 0; i < size_and_type.first; ++i)
7597+ {
7598+ if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
7599+ {
7600+ return false;
7601+ }
7602+ if (JSON_UNLIKELY(not parse_ubjson_internal()))
7603+ {
7604+ return false;
7605+ }
7606+ key.clear();
7607+ }
7608+ }
7609+ }
7610+ else
7611+ {
7612+ if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
7613+ {
7614+ return false;
7615+ }
7616+
7617+ while (current != '}')
7618+ {
7619+ if (JSON_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
7620+ {
7621+ return false;
7622+ }
7623+ if (JSON_UNLIKELY(not parse_ubjson_internal()))
7624+ {
7625+ return false;
7626+ }
7627+ get_ignore_noop();
7628+ key.clear();
7629+ }
7630+ }
7631+
7632+ return sax->end_object();
7633+ }
7634+
7635+ /*!
7636+ @return whether the last read character is not EOF
7637+ */
7638+ bool unexpect_eof() const
7639+ {
7640+ if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
7641+ {
7642+ return sax->parse_error(chars_read, "<end of file>", parse_error::create(110, chars_read, "unexpected end of input"));
7643+ }
7644+ return true;
7645+ }
7646+
7647+ /*!
7648+ @return a string representation of the last read byte
7649+ */
7650+ std::string get_token_string() const
7651+ {
7652+ char cr[3];
7653+ snprintf(cr, 3, "%.2hhX", static_cast<unsigned char>(current));
7654+ return std::string{cr};
7655+ }
7656+
7657+ private:
7658+ /// input adapter
7659+ input_adapter_t ia = nullptr;
7660+
7661+ /// the current character
7662+ int current = std::char_traits<char>::eof();
7663+
7664+ /// the number of characters read
7665+ std::size_t chars_read = 0;
7666+
7667+ /// whether we can assume little endianess
7668+ const bool is_little_endian = little_endianess();
7669+
7670+ /// the SAX parser
7671+ json_sax_t* sax = nullptr;
7672+};
7673+}
7674+}
7675+
7676+// #include <nlohmann/detail/output/binary_writer.hpp>
7677+
7678+
7679+#include <algorithm> // reverse
7680+#include <array> // array
7681+#include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
7682+#include <cstring> // memcpy
7683+#include <limits> // numeric_limits
7684+
7685+// #include <nlohmann/detail/input/binary_reader.hpp>
7686+
7687+// #include <nlohmann/detail/output/output_adapters.hpp>
7688+
7689+
7690+namespace nlohmann
7691+{
7692+namespace detail
7693+{
7694+///////////////////
7695+// binary writer //
7696+///////////////////
7697+
7698+/*!
7699+@brief serialization to CBOR and MessagePack values
7700+*/
7701+template<typename BasicJsonType, typename CharType>
7702+class binary_writer
7703+{
7704+ public:
7705+ /*!
7706+ @brief create a binary writer
7707+
7708+ @param[in] adapter output adapter to write to
7709+ */
7710+ explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
7711+ {
7712+ assert(oa);
7713+ }
7714+
7715+ /*!
7716+ @brief[in] j JSON value to serialize
7717+ */
7718+ void write_cbor(const BasicJsonType& j)
7719+ {
7720+ switch (j.type())
7721+ {
7722+ case value_t::null:
7723+ {
7724+ oa->write_character(static_cast<CharType>(0xF6));
7725+ break;
7726+ }
7727+
7728+ case value_t::boolean:
7729+ {
7730+ oa->write_character(j.m_value.boolean
7731+ ? static_cast<CharType>(0xF5)
7732+ : static_cast<CharType>(0xF4));
7733+ break;
7734+ }
7735+
7736+ case value_t::number_integer:
7737+ {
7738+ if (j.m_value.number_integer >= 0)
7739+ {
7740+ // CBOR does not differentiate between positive signed
7741+ // integers and unsigned integers. Therefore, we used the
7742+ // code from the value_t::number_unsigned case here.
7743+ if (j.m_value.number_integer <= 0x17)
7744+ {
7745+ write_number(static_cast<uint8_t>(j.m_value.number_integer));
7746+ }
7747+ else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
7748+ {
7749+ oa->write_character(static_cast<CharType>(0x18));
7750+ write_number(static_cast<uint8_t>(j.m_value.number_integer));
7751+ }
7752+ else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
7753+ {
7754+ oa->write_character(static_cast<CharType>(0x19));
7755+ write_number(static_cast<uint16_t>(j.m_value.number_integer));
7756+ }
7757+ else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
7758+ {
7759+ oa->write_character(static_cast<CharType>(0x1A));
7760+ write_number(static_cast<uint32_t>(j.m_value.number_integer));
7761+ }
7762+ else
7763+ {
7764+ oa->write_character(static_cast<CharType>(0x1B));
7765+ write_number(static_cast<uint64_t>(j.m_value.number_integer));
7766+ }
7767+ }
7768+ else
7769+ {
7770+ // The conversions below encode the sign in the first
7771+ // byte, and the value is converted to a positive number.
7772+ const auto positive_number = -1 - j.m_value.number_integer;
7773+ if (j.m_value.number_integer >= -24)
7774+ {
7775+ write_number(static_cast<uint8_t>(0x20 + positive_number));
7776+ }
7777+ else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
7778+ {
7779+ oa->write_character(static_cast<CharType>(0x38));
7780+ write_number(static_cast<uint8_t>(positive_number));
7781+ }
7782+ else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
7783+ {
7784+ oa->write_character(static_cast<CharType>(0x39));
7785+ write_number(static_cast<uint16_t>(positive_number));
7786+ }
7787+ else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
7788+ {
7789+ oa->write_character(static_cast<CharType>(0x3A));
7790+ write_number(static_cast<uint32_t>(positive_number));
7791+ }
7792+ else
7793+ {
7794+ oa->write_character(static_cast<CharType>(0x3B));
7795+ write_number(static_cast<uint64_t>(positive_number));
7796+ }
7797+ }
7798+ break;
7799+ }
7800+
7801+ case value_t::number_unsigned:
7802+ {
7803+ if (j.m_value.number_unsigned <= 0x17)
7804+ {
7805+ write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
7806+ }
7807+ else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
7808+ {
7809+ oa->write_character(static_cast<CharType>(0x18));
7810+ write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
7811+ }
7812+ else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
7813+ {
7814+ oa->write_character(static_cast<CharType>(0x19));
7815+ write_number(static_cast<uint16_t>(j.m_value.number_unsigned));
7816+ }
7817+ else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
7818+ {
7819+ oa->write_character(static_cast<CharType>(0x1A));
7820+ write_number(static_cast<uint32_t>(j.m_value.number_unsigned));
7821+ }
7822+ else
7823+ {
7824+ oa->write_character(static_cast<CharType>(0x1B));
7825+ write_number(static_cast<uint64_t>(j.m_value.number_unsigned));
7826+ }
7827+ break;
7828+ }
7829+
7830+ case value_t::number_float:
7831+ {
7832+ oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
7833+ write_number(j.m_value.number_float);
7834+ break;
7835+ }
7836+
7837+ case value_t::string:
7838+ {
7839+ // step 1: write control byte and the string length
7840+ const auto N = j.m_value.string->size();
7841+ if (N <= 0x17)
7842+ {
7843+ write_number(static_cast<uint8_t>(0x60 + N));
7844+ }
7845+ else if (N <= (std::numeric_limits<uint8_t>::max)())
7846+ {
7847+ oa->write_character(static_cast<CharType>(0x78));
7848+ write_number(static_cast<uint8_t>(N));
7849+ }
7850+ else if (N <= (std::numeric_limits<uint16_t>::max)())
7851+ {
7852+ oa->write_character(static_cast<CharType>(0x79));
7853+ write_number(static_cast<uint16_t>(N));
7854+ }
7855+ else if (N <= (std::numeric_limits<uint32_t>::max)())
7856+ {
7857+ oa->write_character(static_cast<CharType>(0x7A));
7858+ write_number(static_cast<uint32_t>(N));
7859+ }
7860+ // LCOV_EXCL_START
7861+ else if (N <= (std::numeric_limits<uint64_t>::max)())
7862+ {
7863+ oa->write_character(static_cast<CharType>(0x7B));
7864+ write_number(static_cast<uint64_t>(N));
7865+ }
7866+ // LCOV_EXCL_STOP
7867+
7868+ // step 2: write the string
7869+ oa->write_characters(
7870+ reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
7871+ j.m_value.string->size());
7872+ break;
7873+ }
7874+
7875+ case value_t::array:
7876+ {
7877+ // step 1: write control byte and the array size
7878+ const auto N = j.m_value.array->size();
7879+ if (N <= 0x17)
7880+ {
7881+ write_number(static_cast<uint8_t>(0x80 + N));
7882+ }
7883+ else if (N <= (std::numeric_limits<uint8_t>::max)())
7884+ {
7885+ oa->write_character(static_cast<CharType>(0x98));
7886+ write_number(static_cast<uint8_t>(N));
7887+ }
7888+ else if (N <= (std::numeric_limits<uint16_t>::max)())
7889+ {
7890+ oa->write_character(static_cast<CharType>(0x99));
7891+ write_number(static_cast<uint16_t>(N));
7892+ }
7893+ else if (N <= (std::numeric_limits<uint32_t>::max)())
7894+ {
7895+ oa->write_character(static_cast<CharType>(0x9A));
7896+ write_number(static_cast<uint32_t>(N));
7897+ }
7898+ // LCOV_EXCL_START
7899+ else if (N <= (std::numeric_limits<uint64_t>::max)())
7900+ {
7901+ oa->write_character(static_cast<CharType>(0x9B));
7902+ write_number(static_cast<uint64_t>(N));
7903+ }
7904+ // LCOV_EXCL_STOP
7905+
7906+ // step 2: write each element
7907+ for (const auto& el : *j.m_value.array)
7908+ {
7909+ write_cbor(el);
7910+ }
7911+ break;
7912+ }
7913+
7914+ case value_t::object:
7915+ {
7916+ // step 1: write control byte and the object size
7917+ const auto N = j.m_value.object->size();
7918+ if (N <= 0x17)
7919+ {
7920+ write_number(static_cast<uint8_t>(0xA0 + N));
7921+ }
7922+ else if (N <= (std::numeric_limits<uint8_t>::max)())
7923+ {
7924+ oa->write_character(static_cast<CharType>(0xB8));
7925+ write_number(static_cast<uint8_t>(N));
7926+ }
7927+ else if (N <= (std::numeric_limits<uint16_t>::max)())
7928+ {
7929+ oa->write_character(static_cast<CharType>(0xB9));
7930+ write_number(static_cast<uint16_t>(N));
7931+ }
7932+ else if (N <= (std::numeric_limits<uint32_t>::max)())
7933+ {
7934+ oa->write_character(static_cast<CharType>(0xBA));
7935+ write_number(static_cast<uint32_t>(N));
7936+ }
7937+ // LCOV_EXCL_START
7938+ else if (N <= (std::numeric_limits<uint64_t>::max)())
7939+ {
7940+ oa->write_character(static_cast<CharType>(0xBB));
7941+ write_number(static_cast<uint64_t>(N));
7942+ }
7943+ // LCOV_EXCL_STOP
7944+
7945+ // step 2: write each element
7946+ for (const auto& el : *j.m_value.object)
7947+ {
7948+ write_cbor(el.first);
7949+ write_cbor(el.second);
7950+ }
7951+ break;
7952+ }
7953+
7954+ default:
7955+ break;
7956+ }
7957+ }
7958+
7959+ /*!
7960+ @brief[in] j JSON value to serialize
7961+ */
7962+ void write_msgpack(const BasicJsonType& j)
7963+ {
7964+ switch (j.type())
7965+ {
7966+ case value_t::null: // nil
7967+ {
7968+ oa->write_character(static_cast<CharType>(0xC0));
7969+ break;
7970+ }
7971+
7972+ case value_t::boolean: // true and false
7973+ {
7974+ oa->write_character(j.m_value.boolean
7975+ ? static_cast<CharType>(0xC3)
7976+ : static_cast<CharType>(0xC2));
7977+ break;
7978+ }
7979+
7980+ case value_t::number_integer:
7981+ {
7982+ if (j.m_value.number_integer >= 0)
7983+ {
7984+ // MessagePack does not differentiate between positive
7985+ // signed integers and unsigned integers. Therefore, we used
7986+ // the code from the value_t::number_unsigned case here.
7987+ if (j.m_value.number_unsigned < 128)
7988+ {
7989+ // positive fixnum
7990+ write_number(static_cast<uint8_t>(j.m_value.number_integer));
7991+ }
7992+ else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
7993+ {
7994+ // uint 8
7995+ oa->write_character(static_cast<CharType>(0xCC));
7996+ write_number(static_cast<uint8_t>(j.m_value.number_integer));
7997+ }
7998+ else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
7999+ {
8000+ // uint 16
8001+ oa->write_character(static_cast<CharType>(0xCD));
8002+ write_number(static_cast<uint16_t>(j.m_value.number_integer));
8003+ }
8004+ else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
8005+ {
8006+ // uint 32
8007+ oa->write_character(static_cast<CharType>(0xCE));
8008+ write_number(static_cast<uint32_t>(j.m_value.number_integer));
8009+ }
8010+ else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
8011+ {
8012+ // uint 64
8013+ oa->write_character(static_cast<CharType>(0xCF));
8014+ write_number(static_cast<uint64_t>(j.m_value.number_integer));
8015+ }
8016+ }
8017+ else
8018+ {
8019+ if (j.m_value.number_integer >= -32)
8020+ {
8021+ // negative fixnum
8022+ write_number(static_cast<int8_t>(j.m_value.number_integer));
8023+ }
8024+ else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and
8025+ j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
8026+ {
8027+ // int 8
8028+ oa->write_character(static_cast<CharType>(0xD0));
8029+ write_number(static_cast<int8_t>(j.m_value.number_integer));
8030+ }
8031+ else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and
8032+ j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
8033+ {
8034+ // int 16
8035+ oa->write_character(static_cast<CharType>(0xD1));
8036+ write_number(static_cast<int16_t>(j.m_value.number_integer));
8037+ }
8038+ else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and
8039+ j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
8040+ {
8041+ // int 32
8042+ oa->write_character(static_cast<CharType>(0xD2));
8043+ write_number(static_cast<int32_t>(j.m_value.number_integer));
8044+ }
8045+ else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and
8046+ j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
8047+ {
8048+ // int 64
8049+ oa->write_character(static_cast<CharType>(0xD3));
8050+ write_number(static_cast<int64_t>(j.m_value.number_integer));
8051+ }
8052+ }
8053+ break;
8054+ }
8055+
8056+ case value_t::number_unsigned:
8057+ {
8058+ if (j.m_value.number_unsigned < 128)
8059+ {
8060+ // positive fixnum
8061+ write_number(static_cast<uint8_t>(j.m_value.number_integer));
8062+ }
8063+ else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
8064+ {
8065+ // uint 8
8066+ oa->write_character(static_cast<CharType>(0xCC));
8067+ write_number(static_cast<uint8_t>(j.m_value.number_integer));
8068+ }
8069+ else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
8070+ {
8071+ // uint 16
8072+ oa->write_character(static_cast<CharType>(0xCD));
8073+ write_number(static_cast<uint16_t>(j.m_value.number_integer));
8074+ }
8075+ else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
8076+ {
8077+ // uint 32
8078+ oa->write_character(static_cast<CharType>(0xCE));
8079+ write_number(static_cast<uint32_t>(j.m_value.number_integer));
8080+ }
8081+ else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
8082+ {
8083+ // uint 64
8084+ oa->write_character(static_cast<CharType>(0xCF));
8085+ write_number(static_cast<uint64_t>(j.m_value.number_integer));
8086+ }
8087+ break;
8088+ }
8089+
8090+ case value_t::number_float:
8091+ {
8092+ oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
8093+ write_number(j.m_value.number_float);
8094+ break;
8095+ }
8096+
8097+ case value_t::string:
8098+ {
8099+ // step 1: write control byte and the string length
8100+ const auto N = j.m_value.string->size();
8101+ if (N <= 31)
8102+ {
8103+ // fixstr
8104+ write_number(static_cast<uint8_t>(0xA0 | N));
8105+ }
8106+ else if (N <= (std::numeric_limits<uint8_t>::max)())
8107+ {
8108+ // str 8
8109+ oa->write_character(static_cast<CharType>(0xD9));
8110+ write_number(static_cast<uint8_t>(N));
8111+ }
8112+ else if (N <= (std::numeric_limits<uint16_t>::max)())
8113+ {
8114+ // str 16
8115+ oa->write_character(static_cast<CharType>(0xDA));
8116+ write_number(static_cast<uint16_t>(N));
8117+ }
8118+ else if (N <= (std::numeric_limits<uint32_t>::max)())
8119+ {
8120+ // str 32
8121+ oa->write_character(static_cast<CharType>(0xDB));
8122+ write_number(static_cast<uint32_t>(N));
8123+ }
8124+
8125+ // step 2: write the string
8126+ oa->write_characters(
8127+ reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
8128+ j.m_value.string->size());
8129+ break;
8130+ }
8131+
8132+ case value_t::array:
8133+ {
8134+ // step 1: write control byte and the array size
8135+ const auto N = j.m_value.array->size();
8136+ if (N <= 15)
8137+ {
8138+ // fixarray
8139+ write_number(static_cast<uint8_t>(0x90 | N));
8140+ }
8141+ else if (N <= (std::numeric_limits<uint16_t>::max)())
8142+ {
8143+ // array 16
8144+ oa->write_character(static_cast<CharType>(0xDC));
8145+ write_number(static_cast<uint16_t>(N));
8146+ }
8147+ else if (N <= (std::numeric_limits<uint32_t>::max)())
8148+ {
8149+ // array 32
8150+ oa->write_character(static_cast<CharType>(0xDD));
8151+ write_number(static_cast<uint32_t>(N));
8152+ }
8153+
8154+ // step 2: write each element
8155+ for (const auto& el : *j.m_value.array)
8156+ {
8157+ write_msgpack(el);
8158+ }
8159+ break;
8160+ }
8161+
8162+ case value_t::object:
8163+ {
8164+ // step 1: write control byte and the object size
8165+ const auto N = j.m_value.object->size();
8166+ if (N <= 15)
8167+ {
8168+ // fixmap
8169+ write_number(static_cast<uint8_t>(0x80 | (N & 0xF)));
8170+ }
8171+ else if (N <= (std::numeric_limits<uint16_t>::max)())
8172+ {
8173+ // map 16
8174+ oa->write_character(static_cast<CharType>(0xDE));
8175+ write_number(static_cast<uint16_t>(N));
8176+ }
8177+ else if (N <= (std::numeric_limits<uint32_t>::max)())
8178+ {
8179+ // map 32
8180+ oa->write_character(static_cast<CharType>(0xDF));
8181+ write_number(static_cast<uint32_t>(N));
8182+ }
8183+
8184+ // step 2: write each element
8185+ for (const auto& el : *j.m_value.object)
8186+ {
8187+ write_msgpack(el.first);
8188+ write_msgpack(el.second);
8189+ }
8190+ break;
8191+ }
8192+
8193+ default:
8194+ break;
8195+ }
8196+ }
8197+
8198+ /*!
8199+ @param[in] j JSON value to serialize
8200+ @param[in] use_count whether to use '#' prefixes (optimized format)
8201+ @param[in] use_type whether to use '$' prefixes (optimized format)
8202+ @param[in] add_prefix whether prefixes need to be used for this value
8203+ */
8204+ void write_ubjson(const BasicJsonType& j, const bool use_count,
8205+ const bool use_type, const bool add_prefix = true)
8206+ {
8207+ switch (j.type())
8208+ {
8209+ case value_t::null:
8210+ {
8211+ if (add_prefix)
8212+ {
8213+ oa->write_character(static_cast<CharType>('Z'));
8214+ }
8215+ break;
8216+ }
8217+
8218+ case value_t::boolean:
8219+ {
8220+ if (add_prefix)
8221+ oa->write_character(j.m_value.boolean
8222+ ? static_cast<CharType>('T')
8223+ : static_cast<CharType>('F'));
8224+ break;
8225+ }
8226+
8227+ case value_t::number_integer:
8228+ {
8229+ write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
8230+ break;
8231+ }
8232+
8233+ case value_t::number_unsigned:
8234+ {
8235+ write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
8236+ break;
8237+ }
8238+
8239+ case value_t::number_float:
8240+ {
8241+ write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
8242+ break;
8243+ }
8244+
8245+ case value_t::string:
8246+ {
8247+ if (add_prefix)
8248+ {
8249+ oa->write_character(static_cast<CharType>('S'));
8250+ }
8251+ write_number_with_ubjson_prefix(j.m_value.string->size(), true);
8252+ oa->write_characters(
8253+ reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
8254+ j.m_value.string->size());
8255+ break;
8256+ }
8257+
8258+ case value_t::array:
8259+ {
8260+ if (add_prefix)
8261+ {
8262+ oa->write_character(static_cast<CharType>('['));
8263+ }
8264+
8265+ bool prefix_required = true;
8266+ if (use_type and not j.m_value.array->empty())
8267+ {
8268+ assert(use_count);
8269+ const CharType first_prefix = ubjson_prefix(j.front());
8270+ const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
8271+ [this, first_prefix](const BasicJsonType & v)
8272+ {
8273+ return ubjson_prefix(v) == first_prefix;
8274+ });
8275+
8276+ if (same_prefix)
8277+ {
8278+ prefix_required = false;
8279+ oa->write_character(static_cast<CharType>('$'));
8280+ oa->write_character(first_prefix);
8281+ }
8282+ }
8283+
8284+ if (use_count)
8285+ {
8286+ oa->write_character(static_cast<CharType>('#'));
8287+ write_number_with_ubjson_prefix(j.m_value.array->size(), true);
8288+ }
8289+
8290+ for (const auto& el : *j.m_value.array)
8291+ {
8292+ write_ubjson(el, use_count, use_type, prefix_required);
8293+ }
8294+
8295+ if (not use_count)
8296+ {
8297+ oa->write_character(static_cast<CharType>(']'));
8298+ }
8299+
8300+ break;
8301+ }
8302+
8303+ case value_t::object:
8304+ {
8305+ if (add_prefix)
8306+ {
8307+ oa->write_character(static_cast<CharType>('{'));
8308+ }
8309+
8310+ bool prefix_required = true;
8311+ if (use_type and not j.m_value.object->empty())
8312+ {
8313+ assert(use_count);
8314+ const CharType first_prefix = ubjson_prefix(j.front());
8315+ const bool same_prefix = std::all_of(j.begin(), j.end(),
8316+ [this, first_prefix](const BasicJsonType & v)
8317+ {
8318+ return ubjson_prefix(v) == first_prefix;
8319+ });
8320+
8321+ if (same_prefix)
8322+ {
8323+ prefix_required = false;
8324+ oa->write_character(static_cast<CharType>('$'));
8325+ oa->write_character(first_prefix);
8326+ }
8327+ }
8328+
8329+ if (use_count)
8330+ {
8331+ oa->write_character(static_cast<CharType>('#'));
8332+ write_number_with_ubjson_prefix(j.m_value.object->size(), true);
8333+ }
8334+
8335+ for (const auto& el : *j.m_value.object)
8336+ {
8337+ write_number_with_ubjson_prefix(el.first.size(), true);
8338+ oa->write_characters(
8339+ reinterpret_cast<const CharType*>(el.first.c_str()),
8340+ el.first.size());
8341+ write_ubjson(el.second, use_count, use_type, prefix_required);
8342+ }
8343+
8344+ if (not use_count)
8345+ {
8346+ oa->write_character(static_cast<CharType>('}'));
8347+ }
8348+
8349+ break;
8350+ }
8351+
8352+ default:
8353+ break;
8354+ }
8355+ }
8356+
8357+ private:
8358+ /*
8359+ @brief write a number to output input
8360+
8361+ @param[in] n number of type @a NumberType
8362+ @tparam NumberType the type of the number
8363+
8364+ @note This function needs to respect the system's endianess, because bytes
8365+ in CBOR, MessagePack, and UBJSON are stored in network order (big
8366+ endian) and therefore need reordering on little endian systems.
8367+ */
8368+ template<typename NumberType>
8369+ void write_number(const NumberType n)
8370+ {
8371+ // step 1: write number to array of length NumberType
8372+ std::array<CharType, sizeof(NumberType)> vec;
8373+ std::memcpy(vec.data(), &n, sizeof(NumberType));
8374+
8375+ // step 2: write array to output (with possible reordering)
8376+ if (is_little_endian)
8377+ {
8378+ // reverse byte order prior to conversion if necessary
8379+ std::reverse(vec.begin(), vec.end());
8380+ }
8381+
8382+ oa->write_characters(vec.data(), sizeof(NumberType));
8383+ }
8384+
8385+ // UBJSON: write number (floating point)
8386+ template<typename NumberType, typename std::enable_if<
8387+ std::is_floating_point<NumberType>::value, int>::type = 0>
8388+ void write_number_with_ubjson_prefix(const NumberType n,
8389+ const bool add_prefix)
8390+ {
8391+ if (add_prefix)
8392+ {
8393+ oa->write_character(get_ubjson_float_prefix(n));
8394+ }
8395+ write_number(n);
8396+ }
8397+
8398+ // UBJSON: write number (unsigned integer)
8399+ template<typename NumberType, typename std::enable_if<
8400+ std::is_unsigned<NumberType>::value, int>::type = 0>
8401+ void write_number_with_ubjson_prefix(const NumberType n,
8402+ const bool add_prefix)
8403+ {
8404+ if (n <= static_cast<uint64_t>((std::numeric_limits<int8_t>::max)()))
8405+ {
8406+ if (add_prefix)
8407+ {
8408+ oa->write_character(static_cast<CharType>('i')); // int8
8409+ }
8410+ write_number(static_cast<uint8_t>(n));
8411+ }
8412+ else if (n <= (std::numeric_limits<uint8_t>::max)())
8413+ {
8414+ if (add_prefix)
8415+ {
8416+ oa->write_character(static_cast<CharType>('U')); // uint8
8417+ }
8418+ write_number(static_cast<uint8_t>(n));
8419+ }
8420+ else if (n <= static_cast<uint64_t>((std::numeric_limits<int16_t>::max)()))
8421+ {
8422+ if (add_prefix)
8423+ {
8424+ oa->write_character(static_cast<CharType>('I')); // int16
8425+ }
8426+ write_number(static_cast<int16_t>(n));
8427+ }
8428+ else if (n <= static_cast<uint64_t>((std::numeric_limits<int32_t>::max)()))
8429+ {
8430+ if (add_prefix)
8431+ {
8432+ oa->write_character(static_cast<CharType>('l')); // int32
8433+ }
8434+ write_number(static_cast<int32_t>(n));
8435+ }
8436+ else if (n <= static_cast<uint64_t>((std::numeric_limits<int64_t>::max)()))
8437+ {
8438+ if (add_prefix)
8439+ {
8440+ oa->write_character(static_cast<CharType>('L')); // int64
8441+ }
8442+ write_number(static_cast<int64_t>(n));
8443+ }
8444+ else
8445+ {
8446+ JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n)));
8447+ }
8448+ }
8449+
8450+ // UBJSON: write number (signed integer)
8451+ template<typename NumberType, typename std::enable_if<
8452+ std::is_signed<NumberType>::value and
8453+ not std::is_floating_point<NumberType>::value, int>::type = 0>
8454+ void write_number_with_ubjson_prefix(const NumberType n,
8455+ const bool add_prefix)
8456+ {
8457+ if ((std::numeric_limits<int8_t>::min)() <= n and n <= (std::numeric_limits<int8_t>::max)())
8458+ {
8459+ if (add_prefix)
8460+ {
8461+ oa->write_character(static_cast<CharType>('i')); // int8
8462+ }
8463+ write_number(static_cast<int8_t>(n));
8464+ }
8465+ else if (static_cast<int64_t>((std::numeric_limits<uint8_t>::min)()) <= n and n <= static_cast<int64_t>((std::numeric_limits<uint8_t>::max)()))
8466+