Dendro  5.01
Dendro in Greek language means tree. The Dendro library is a large scale (262K cores on ORNL's Titan) distributed memory adaptive octree framework. The main goal of Dendro is to perform large scale multiphysics simulations efficeiently in mordern supercomputers. Dendro consists of efficient parallel data structures and algorithms to perform variational ( finite element) methods and finite difference mthods on 2:1 balanced arbitary adaptive octrees which enables the users to perform simulations raning from black holes (binary black hole mergers) to blood flow in human body, where applications ranging from relativity, astrophysics to biomedical engineering.
json.hpp
1 /*
2  __ _____ _____ _____
3  __| | __| | | | JSON for Modern C++
4 | | |__ | | | | | | version 3.1.2
5 |_____|_____|_____|_|___| https://github.com/nlohmann/json
6 
7 Licensed under the MIT License <http://opensource.org/licenses/MIT>.
8 Copyright (c) 2013-2018 Niels Lohmann <http://nlohmann.me>.
9 
10 Permission is hereby granted, free of charge, to any person obtaining a copy
11 of this software and associated documentation files (the "Software"), to deal
12 in the Software without restriction, including without limitation the rights
13 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 copies of the Software, and to permit persons to whom the Software is
15 furnished to do so, subject to the following conditions:
16 
17 The above copyright notice and this permission notice shall be included in all
18 copies or substantial portions of the Software.
19 
20 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26 SOFTWARE.
27 */
28 
29 #ifndef NLOHMANN_JSON_HPP
30 #define NLOHMANN_JSON_HPP
31 
32 #define NLOHMANN_JSON_VERSION_MAJOR 3
33 #define NLOHMANN_JSON_VERSION_MINOR 1
34 #define NLOHMANN_JSON_VERSION_PATCH 2
35 
36 #include <algorithm> // all_of, find, for_each
37 #include <cassert> // assert
38 #include <ciso646> // and, not, or
39 #include <cstddef> // nullptr_t, ptrdiff_t, size_t
40 #include <functional> // hash, less
41 #include <initializer_list> // initializer_list
42 #include <iosfwd> // istream, ostream
43 #include <iterator> // iterator_traits, random_access_iterator_tag
44 #include <numeric> // accumulate
45 #include <string> // string, stoi, to_string
46 #include <utility> // declval, forward, move, pair, swap
47 
48 #include <json_fwd.hpp>
49 #ifndef NLOHMANN_JSON_FWD_HPP
50 #define NLOHMANN_JSON_FWD_HPP
51 
52 #include <cstdint> // int64_t, uint64_t
53 #include <map> // map
54 #include <memory> // allocator
55 #include <string> // string
56 #include <vector> // vector
57 
63 namespace nlohmann
64 {
72 template<typename = void, typename = void>
74 
75 template<template<typename U, typename V, typename... Args> class ObjectType =
76  std::map,
77  template<typename U, typename... Args> class ArrayType = std::vector,
78  class StringType = std::string, class BooleanType = bool,
79  class NumberIntegerType = std::int64_t,
80  class NumberUnsignedType = std::uint64_t,
81  class NumberFloatType = double,
82  template<typename U> class AllocatorType = std::allocator,
83  template<typename T, typename SFINAE = void> class JSONSerializer =
85 class basic_json;
86 
98 template<typename BasicJsonType>
100 
110 }
111 
112 #endif
113 
114 // #include <nlohmann/detail/macro_scope.hpp>
115 
116 
117 // This file contains all internal macro definitions
118 // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
119 
120 // exclude unsupported compilers
121 #if defined(__clang__)
122  #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
123  #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
124  #endif
125 #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
126  #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900
127  #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
128  #endif
129 #endif
130 
131 // disable float-equal warnings on GCC/clang
132 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
133  #pragma GCC diagnostic push
134  #pragma GCC diagnostic ignored "-Wfloat-equal"
135 #endif
136 
137 // disable documentation warnings on clang
138 #if defined(__clang__)
139  #pragma GCC diagnostic push
140  #pragma GCC diagnostic ignored "-Wdocumentation"
141 #endif
142 
143 // allow for portable deprecation warnings
144 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
145  #define JSON_DEPRECATED __attribute__((deprecated))
146 #elif defined(_MSC_VER)
147  #define JSON_DEPRECATED __declspec(deprecated)
148 #else
149  #define JSON_DEPRECATED
150 #endif
151 
152 // allow to disable exceptions
153 #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
154  #define JSON_THROW(exception) throw exception
155  #define JSON_TRY try
156  #define JSON_CATCH(exception) catch(exception)
157 #else
158  #define JSON_THROW(exception) std::abort()
159  #define JSON_TRY if(true)
160  #define JSON_CATCH(exception) if(false)
161 #endif
162 
163 // override exception macros
164 #if defined(JSON_THROW_USER)
165  #undef JSON_THROW
166  #define JSON_THROW JSON_THROW_USER
167 #endif
168 #if defined(JSON_TRY_USER)
169  #undef JSON_TRY
170  #define JSON_TRY JSON_TRY_USER
171 #endif
172 #if defined(JSON_CATCH_USER)
173  #undef JSON_CATCH
174  #define JSON_CATCH JSON_CATCH_USER
175 #endif
176 
177 // manual branch prediction
178 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
179  #define JSON_LIKELY(x) __builtin_expect(!!(x), 1)
180  #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
181 #else
182  #define JSON_LIKELY(x) x
183  #define JSON_UNLIKELY(x) x
184 #endif
185 
186 // C++ language standard detection
187 #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
188  #define JSON_HAS_CPP_17
189  #define JSON_HAS_CPP_14
190 #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
191  #define JSON_HAS_CPP_14
192 #endif
193 
194 // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
195 // may be removed in the future once the class is split.
196 
197 #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
198  template<template<typename, typename, typename...> class ObjectType, \
199  template<typename, typename...> class ArrayType, \
200  class StringType, class BooleanType, class NumberIntegerType, \
201  class NumberUnsignedType, class NumberFloatType, \
202  template<typename> class AllocatorType, \
203  template<typename, typename = void> class JSONSerializer>
204 
205 #define NLOHMANN_BASIC_JSON_TPL \
206  basic_json<ObjectType, ArrayType, StringType, BooleanType, \
207  NumberIntegerType, NumberUnsignedType, NumberFloatType, \
208  AllocatorType, JSONSerializer>
209 
220 #define NLOHMANN_JSON_HAS_HELPER(type) \
221  template<typename T> struct has_##type { \
222  private: \
223  template<typename U, typename = typename U::type> \
224  static int detect(U &&); \
225  static void detect(...); \
226  public: \
227  static constexpr bool value = \
228  std::is_integral<decltype(detect(std::declval<T>()))>::value; \
229  }
230 
231 // #include <nlohmann/detail/meta.hpp>
232 
233 
234 #include <ciso646> // not
235 #include <cstddef> // size_t
236 #include <limits> // numeric_limits
237 #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
238 #include <utility> // declval
239 
240 // #include <nlohmann/json_fwd.hpp>
241 
242 // #include <nlohmann/detail/macro_scope.hpp>
243 
244 
245 namespace nlohmann
246 {
255 namespace detail
256 {
258 // helpers //
260 
261 template<typename> struct is_basic_json : std::false_type {};
262 
263 NLOHMANN_BASIC_JSON_TPL_DECLARATION
264 struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
265 
266 // alias templates to reduce boilerplate
267 template<bool B, typename T = void>
268 using enable_if_t = typename std::enable_if<B, T>::type;
269 
270 template<typename T>
271 using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
272 
273 // implementation of C++14 index_sequence and affiliates
274 // source: https://stackoverflow.com/a/32223343
275 template<std::size_t... Ints>
277 {
278  using type = index_sequence;
279  using value_type = std::size_t;
280  static constexpr std::size_t size() noexcept
281  {
282  return sizeof...(Ints);
283  }
284 };
285 
286 template<class Sequence1, class Sequence2>
288 
289 template<std::size_t... I1, std::size_t... I2>
291  : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
292 
293 template<std::size_t N>
295  : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
296  typename make_index_sequence < N - N / 2 >::type > {};
297 
298 template<> struct make_index_sequence<0> : index_sequence<> {};
299 template<> struct make_index_sequence<1> : index_sequence<0> {};
300 
301 template<typename... Ts>
302 using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
303 
304 /*
305 Implementation of two C++17 constructs: conjunction, negation. This is needed
306 to avoid evaluating all the traits in a condition
307 
308 For example: not std::is_same<void, T>::value and has_value_type<T>::value
309 will not compile when T = void (on MSVC at least). Whereas
310 conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
311 stop evaluating if negation<...>::value == false
312 
313 Please note that those constructs must be used with caution, since symbols can
314 become very long quickly (which can slow down compilation and cause MSVC
315 internal compiler errors). Only use it when you have to (see example ahead).
316 */
317 template<class...> struct conjunction : std::true_type {};
318 template<class B1> struct conjunction<B1> : B1 {};
319 template<class B1, class... Bn>
320 struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
321 
322 template<class B> struct negation : std::integral_constant<bool, not B::value> {};
323 
324 // dispatch utility (taken from ranges-v3)
325 template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
326 template<> struct priority_tag<0> {};
327 
329 // has_/is_ functions //
331 
332 // source: https://stackoverflow.com/a/37193089/4116453
333 
334 template <typename T, typename = void>
335 struct is_complete_type : std::false_type {};
336 
337 template <typename T>
338 struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
339 
340 NLOHMANN_JSON_HAS_HELPER(mapped_type);
341 NLOHMANN_JSON_HAS_HELPER(key_type);
342 NLOHMANN_JSON_HAS_HELPER(value_type);
343 NLOHMANN_JSON_HAS_HELPER(iterator);
344 
345 template<bool B, class RealType, class CompatibleObjectType>
346 struct is_compatible_object_type_impl : std::false_type {};
347 
348 template<class RealType, class CompatibleObjectType>
349 struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
350 {
351  static constexpr auto value =
352  std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and
353  std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value;
354 };
355 
356 template<class BasicJsonType, class CompatibleObjectType>
358 {
359  static auto constexpr value = is_compatible_object_type_impl <
361  has_mapped_type<CompatibleObjectType>,
362  has_key_type<CompatibleObjectType>>::value,
363  typename BasicJsonType::object_t, CompatibleObjectType >::value;
364 };
365 
366 template<typename BasicJsonType, typename T>
368 {
369  static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
370  std::is_same<T, typename BasicJsonType::const_iterator>::value or
371  std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
372  std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value;
373 };
374 
375 template<class BasicJsonType, class CompatibleArrayType>
377 {
378  static auto constexpr value =
381  BasicJsonType, CompatibleArrayType>>,
382  negation<std::is_constructible<typename BasicJsonType::string_t,
383  CompatibleArrayType>>,
385  has_value_type<CompatibleArrayType>,
386  has_iterator<CompatibleArrayType>>::value;
387 };
388 
389 template<bool, typename, typename>
390 struct is_compatible_integer_type_impl : std::false_type {};
391 
392 template<typename RealIntegerType, typename CompatibleNumberIntegerType>
393 struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
394 {
395  // is there an assert somewhere on overflows?
396  using RealLimits = std::numeric_limits<RealIntegerType>;
397  using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
398 
399  static constexpr auto value =
400  std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and
401  CompatibleLimits::is_integer and
402  RealLimits::is_signed == CompatibleLimits::is_signed;
403 };
404 
405 template<typename RealIntegerType, typename CompatibleNumberIntegerType>
407 {
408  static constexpr auto value =
410  std::is_integral<CompatibleNumberIntegerType>::value and
411  not std::is_same<bool, CompatibleNumberIntegerType>::value,
412  RealIntegerType, CompatibleNumberIntegerType > ::value;
413 };
414 
415 // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
416 template<typename BasicJsonType, typename T>
418 {
419  private:
420  // also check the return type of from_json
421  template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
422  std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
423  static int detect(U&&);
424  static void detect(...);
425 
426  public:
427  static constexpr bool value = std::is_integral<decltype(
428  detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
429 };
430 
431 // This trait checks if JSONSerializer<T>::from_json(json const&) exists
432 // this overload is used for non-default-constructible user-defined-types
433 template<typename BasicJsonType, typename T>
435 {
436  private:
437  template <
438  typename U,
439  typename = enable_if_t<std::is_same<
440  T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value >>
441  static int detect(U&&);
442  static void detect(...);
443 
444  public:
445  static constexpr bool value = std::is_integral<decltype(detect(
446  std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
447 };
448 
449 // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
450 template<typename BasicJsonType, typename T>
452 {
453  private:
454  template<typename U, typename = decltype(uncvref_t<U>::to_json(
455  std::declval<BasicJsonType&>(), std::declval<T>()))>
456  static int detect(U&&);
457  static void detect(...);
458 
459  public:
460  static constexpr bool value = std::is_integral<decltype(detect(
461  std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
462 };
463 
464 template <typename BasicJsonType, typename CompatibleCompleteType>
466 {
467  static constexpr bool value =
468  not std::is_base_of<std::istream, CompatibleCompleteType>::value and
472 };
473 
474 template <typename BasicJsonType, typename CompatibleType>
476  : conjunction<is_complete_type<CompatibleType>,
477  is_compatible_complete_type<BasicJsonType, CompatibleType>>
478 {
479 };
480 
481 // taken from ranges-v3
482 template<typename T>
484 {
485  static constexpr T value{};
486 };
487 
488 template<typename T>
489 constexpr T static_const<T>::value;
490 }
491 }
492 
493 // #include <nlohmann/detail/exceptions.hpp>
494 
495 
496 #include <exception> // exception
497 #include <stdexcept> // runtime_error
498 #include <string> // to_string
499 
500 namespace nlohmann
501 {
502 namespace detail
503 {
505 // exceptions //
507 
536 class exception : public std::exception
537 {
538  public:
540  const char* what() const noexcept override
541  {
542  return m.what();
543  }
544 
546  const int id;
547 
548  protected:
549  exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
550 
551  static std::string name(const std::string& ename, int id_)
552  {
553  return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
554  }
555 
556  private:
558  std::runtime_error m;
559 };
560 
604 class parse_error : public exception
605 {
606  public:
615  static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
616  {
617  std::string w = exception::name("parse_error", id_) + "parse error" +
618  (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") +
619  ": " + what_arg;
620  return parse_error(id_, byte_, w.c_str());
621  }
622 
632  const std::size_t byte;
633 
634  private:
635  parse_error(int id_, std::size_t byte_, const char* what_arg)
636  : exception(id_, what_arg), byte(byte_) {}
637 };
638 
677 {
678  public:
679  static invalid_iterator create(int id_, const std::string& what_arg)
680  {
681  std::string w = exception::name("invalid_iterator", id_) + what_arg;
682  return invalid_iterator(id_, w.c_str());
683  }
684 
685  private:
686  invalid_iterator(int id_, const char* what_arg)
687  : exception(id_, what_arg) {}
688 };
689 
728 class type_error : public exception
729 {
730  public:
731  static type_error create(int id_, const std::string& what_arg)
732  {
733  std::string w = exception::name("type_error", id_) + what_arg;
734  return type_error(id_, w.c_str());
735  }
736 
737  private:
738  type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
739 };
740 
773 class out_of_range : public exception
774 {
775  public:
776  static out_of_range create(int id_, const std::string& what_arg)
777  {
778  std::string w = exception::name("out_of_range", id_) + what_arg;
779  return out_of_range(id_, w.c_str());
780  }
781 
782  private:
783  out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
784 };
785 
810 class other_error : public exception
811 {
812  public:
813  static other_error create(int id_, const std::string& what_arg)
814  {
815  std::string w = exception::name("other_error", id_) + what_arg;
816  return other_error(id_, w.c_str());
817  }
818 
819  private:
820  other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
821 };
822 }
823 }
824 
825 // #include <nlohmann/detail/value_t.hpp>
826 
827 
828 #include <array> // array
829 #include <ciso646> // and
830 #include <cstddef> // size_t
831 #include <cstdint> // uint8_t
832 
833 namespace nlohmann
834 {
835 namespace detail
836 {
838 // JSON type enumeration //
840 
865 enum class value_t : std::uint8_t
866 {
867  null,
868  object,
869  array,
870  string,
871  boolean,
874  number_float,
875  discarded
876 };
877 
888 inline bool operator<(const value_t lhs, const value_t rhs) noexcept
889 {
890  static constexpr std::array<std::uint8_t, 8> order = {{
891  0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
892  1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
893  }
894  };
895 
896  const auto l_index = static_cast<std::size_t>(lhs);
897  const auto r_index = static_cast<std::size_t>(rhs);
898  return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
899 }
900 }
901 }
902 
903 // #include <nlohmann/detail/conversions/from_json.hpp>
904 
905 
906 #include <algorithm> // transform
907 #include <array> // array
908 #include <ciso646> // and, not
909 #include <forward_list> // forward_list
910 #include <iterator> // inserter, front_inserter, end
911 #include <string> // string
912 #include <tuple> // tuple, make_tuple
913 #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
914 #include <utility> // pair, declval
915 #include <valarray> // valarray
916 
917 // #include <nlohmann/detail/exceptions.hpp>
918 
919 // #include <nlohmann/detail/macro_scope.hpp>
920 
921 // #include <nlohmann/detail/meta.hpp>
922 
923 // #include <nlohmann/detail/value_t.hpp>
924 
925 
926 namespace nlohmann
927 {
928 namespace detail
929 {
930 // overloads for basic_json template parameters
931 template<typename BasicJsonType, typename ArithmeticType,
932  enable_if_t<std::is_arithmetic<ArithmeticType>::value and
933  not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
934  int> = 0>
935 void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
936 {
937  switch (static_cast<value_t>(j))
938  {
940  {
941  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
942  break;
943  }
945  {
946  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
947  break;
948  }
950  {
951  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
952  break;
953  }
954 
955  default:
956  JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
957  }
958 }
959 
960 template<typename BasicJsonType>
961 void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
962 {
963  if (JSON_UNLIKELY(not j.is_boolean()))
964  {
965  JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
966  }
967  b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
968 }
969 
970 template<typename BasicJsonType>
971 void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
972 {
973  if (JSON_UNLIKELY(not j.is_string()))
974  {
975  JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
976  }
977  s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
978 }
979 
980 template<typename BasicJsonType>
981 void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
982 {
983  get_arithmetic_value(j, val);
984 }
985 
986 template<typename BasicJsonType>
987 void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
988 {
989  get_arithmetic_value(j, val);
990 }
991 
992 template<typename BasicJsonType>
993 void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
994 {
995  get_arithmetic_value(j, val);
996 }
997 
998 template<typename BasicJsonType, typename EnumType,
999  enable_if_t<std::is_enum<EnumType>::value, int> = 0>
1000 void from_json(const BasicJsonType& j, EnumType& e)
1001 {
1002  typename std::underlying_type<EnumType>::type val;
1003  get_arithmetic_value(j, val);
1004  e = static_cast<EnumType>(val);
1005 }
1006 
1007 template<typename BasicJsonType>
1008 void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
1009 {
1010  if (JSON_UNLIKELY(not j.is_array()))
1011  {
1012  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1013  }
1014  arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
1015 }
1016 
1017 // forward_list doesn't have an insert method
1018 template<typename BasicJsonType, typename T, typename Allocator,
1019  enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
1020 void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
1021 {
1022  if (JSON_UNLIKELY(not j.is_array()))
1023  {
1024  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1025  }
1026  std::transform(j.rbegin(), j.rend(),
1027  std::front_inserter(l), [](const BasicJsonType & i)
1028  {
1029  return i.template get<T>();
1030  });
1031 }
1032 
1033 // valarray doesn't have an insert method
1034 template<typename BasicJsonType, typename T,
1035  enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
1036 void from_json(const BasicJsonType& j, std::valarray<T>& l)
1037 {
1038  if (JSON_UNLIKELY(not j.is_array()))
1039  {
1040  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1041  }
1042  l.resize(j.size());
1043  std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
1044 }
1045 
1046 template<typename BasicJsonType, typename CompatibleArrayType>
1047 void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/)
1048 {
1049  using std::end;
1050 
1051  std::transform(j.begin(), j.end(),
1052  std::inserter(arr, end(arr)), [](const BasicJsonType & i)
1053  {
1054  // get<BasicJsonType>() returns *this, this won't call a from_json
1055  // method when value_type is BasicJsonType
1056  return i.template get<typename CompatibleArrayType::value_type>();
1057  });
1058 }
1059 
1060 template<typename BasicJsonType, typename CompatibleArrayType>
1061 auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/)
1062 -> decltype(
1063  arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
1064  void())
1065 {
1066  using std::end;
1067 
1068  arr.reserve(j.size());
1069  std::transform(j.begin(), j.end(),
1070  std::inserter(arr, end(arr)), [](const BasicJsonType & i)
1071  {
1072  // get<BasicJsonType>() returns *this, this won't call a from_json
1073  // method when value_type is BasicJsonType
1074  return i.template get<typename CompatibleArrayType::value_type>();
1075  });
1076 }
1077 
1078 template<typename BasicJsonType, typename T, std::size_t N>
1079 void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/)
1080 {
1081  for (std::size_t i = 0; i < N; ++i)
1082  {
1083  arr[i] = j.at(i).template get<T>();
1084  }
1085 }
1086 
1087 template <
1088  typename BasicJsonType, typename CompatibleArrayType,
1089  enable_if_t <
1091  not std::is_same<typename BasicJsonType::array_t,
1092  CompatibleArrayType>::value and
1093  std::is_constructible <
1094  BasicJsonType, typename CompatibleArrayType::value_type >::value,
1095  int > = 0 >
1096 void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
1097 {
1098  if (JSON_UNLIKELY(not j.is_array()))
1099  {
1100  JSON_THROW(type_error::create(302, "type must be array, but is " +
1101  std::string(j.type_name())));
1102  }
1103 
1104  from_json_array_impl(j, arr, priority_tag<2> {});
1105 }
1106 
1107 template<typename BasicJsonType, typename CompatibleObjectType,
1108  enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
1109 void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
1110 {
1111  if (JSON_UNLIKELY(not j.is_object()))
1112  {
1113  JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
1114  }
1115 
1116  auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
1117  using value_type = typename CompatibleObjectType::value_type;
1118  std::transform(
1119  inner_object->begin(), inner_object->end(),
1120  std::inserter(obj, obj.begin()),
1121  [](typename BasicJsonType::object_t::value_type const & p)
1122  {
1123  return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>());
1124  });
1125 }
1126 
1127 // overload for arithmetic types, not chosen for basic_json template arguments
1128 // (BooleanType, etc..); note: Is it really necessary to provide explicit
1129 // overloads for boolean_t etc. in case of a custom BooleanType which is not
1130 // an arithmetic type?
1131 template<typename BasicJsonType, typename ArithmeticType,
1132  enable_if_t <
1133  std::is_arithmetic<ArithmeticType>::value and
1134  not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
1135  not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
1136  not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
1137  not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
1138  int> = 0>
1139 void from_json(const BasicJsonType& j, ArithmeticType& val)
1140 {
1141  switch (static_cast<value_t>(j))
1142  {
1144  {
1145  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
1146  break;
1147  }
1149  {
1150  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
1151  break;
1152  }
1153  case value_t::number_float:
1154  {
1155  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
1156  break;
1157  }
1158  case value_t::boolean:
1159  {
1160  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
1161  break;
1162  }
1163 
1164  default:
1165  JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
1166  }
1167 }
1168 
1169 template<typename BasicJsonType, typename A1, typename A2>
1170 void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
1171 {
1172  p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
1173 }
1174 
1175 template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
1176 void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>)
1177 {
1178  t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
1179 }
1180 
1181 template<typename BasicJsonType, typename... Args>
1182 void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
1183 {
1184  from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
1185 }
1186 
1188 {
1189  private:
1190  template<typename BasicJsonType, typename T>
1191  auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const
1192  noexcept(noexcept(from_json(j, val)))
1193  -> decltype(from_json(j, val), void())
1194  {
1195  return from_json(j, val);
1196  }
1197 
1198  template<typename BasicJsonType, typename T>
1199  void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept
1200  {
1201  static_assert(sizeof(BasicJsonType) == 0,
1202  "could not find from_json() method in T's namespace");
1203 #ifdef _MSC_VER
1204  // MSVC does not show a stacktrace for the above assert
1205  using decayed = uncvref_t<T>;
1206  static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
1207  "forcing MSVC stacktrace to show which T we're talking about.");
1208 #endif
1209  }
1210 
1211  public:
1212  template<typename BasicJsonType, typename T>
1213  void operator()(const BasicJsonType& j, T& val) const
1214  noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
1215  {
1216  return call(j, val, priority_tag<1> {});
1217  }
1218 };
1219 }
1220 
1224 namespace
1225 {
1226 constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
1227 }
1228 }
1229 
1230 // #include <nlohmann/detail/conversions/to_json.hpp>
1231 
1232 
1233 #include <ciso646> // or, and, not
1234 #include <iterator> // begin, end
1235 #include <tuple> // tuple, get
1236 #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
1237 #include <utility> // move, forward, declval, pair
1238 #include <valarray> // valarray
1239 #include <vector> // vector
1240 
1241 // #include <nlohmann/detail/meta.hpp>
1242 
1243 // #include <nlohmann/detail/value_t.hpp>
1244 
1245 
1246 namespace nlohmann
1247 {
1248 namespace detail
1249 {
1251 // constructors //
1253 
1254 template<value_t> struct external_constructor;
1255 
1256 template<>
1258 {
1259  template<typename BasicJsonType>
1260  static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
1261  {
1262  j.m_type = value_t::boolean;
1263  j.m_value = b;
1264  j.assert_invariant();
1265  }
1266 };
1267 
1268 template<>
1270 {
1271  template<typename BasicJsonType>
1272  static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
1273  {
1274  j.m_type = value_t::string;
1275  j.m_value = s;
1276  j.assert_invariant();
1277  }
1278 
1279  template<typename BasicJsonType>
1280  static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
1281  {
1282  j.m_type = value_t::string;
1283  j.m_value = std::move(s);
1284  j.assert_invariant();
1285  }
1286 };
1287 
1288 template<>
1290 {
1291  template<typename BasicJsonType>
1292  static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
1293  {
1294  j.m_type = value_t::number_float;
1295  j.m_value = val;
1296  j.assert_invariant();
1297  }
1298 };
1299 
1300 template<>
1302 {
1303  template<typename BasicJsonType>
1304  static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
1305  {
1306  j.m_type = value_t::number_unsigned;
1307  j.m_value = val;
1308  j.assert_invariant();
1309  }
1310 };
1311 
1312 template<>
1314 {
1315  template<typename BasicJsonType>
1316  static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
1317  {
1318  j.m_type = value_t::number_integer;
1319  j.m_value = val;
1320  j.assert_invariant();
1321  }
1322 };
1323 
1324 template<>
1326 {
1327  template<typename BasicJsonType>
1328  static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
1329  {
1330  j.m_type = value_t::array;
1331  j.m_value = arr;
1332  j.assert_invariant();
1333  }
1334 
1335  template<typename BasicJsonType>
1336  static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
1337  {
1338  j.m_type = value_t::array;
1339  j.m_value = std::move(arr);
1340  j.assert_invariant();
1341  }
1342 
1343  template<typename BasicJsonType, typename CompatibleArrayType,
1344  enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
1345  int> = 0>
1346  static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
1347  {
1348  using std::begin;
1349  using std::end;
1350  j.m_type = value_t::array;
1351  j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
1352  j.assert_invariant();
1353  }
1354 
1355  template<typename BasicJsonType>
1356  static void construct(BasicJsonType& j, const std::vector<bool>& arr)
1357  {
1358  j.m_type = value_t::array;
1359  j.m_value = value_t::array;
1360  j.m_value.array->reserve(arr.size());
1361  for (const bool x : arr)
1362  {
1363  j.m_value.array->push_back(x);
1364  }
1365  j.assert_invariant();
1366  }
1367 
1368  template<typename BasicJsonType, typename T,
1369  enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
1370  static void construct(BasicJsonType& j, const std::valarray<T>& arr)
1371  {
1372  j.m_type = value_t::array;
1373  j.m_value = value_t::array;
1374  j.m_value.array->resize(arr.size());
1375  std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
1376  j.assert_invariant();
1377  }
1378 };
1379 
1380 template<>
1382 {
1383  template<typename BasicJsonType>
1384  static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
1385  {
1386  j.m_type = value_t::object;
1387  j.m_value = obj;
1388  j.assert_invariant();
1389  }
1390 
1391  template<typename BasicJsonType>
1392  static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
1393  {
1394  j.m_type = value_t::object;
1395  j.m_value = std::move(obj);
1396  j.assert_invariant();
1397  }
1398 
1399  template<typename BasicJsonType, typename CompatibleObjectType,
1400  enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
1401  static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
1402  {
1403  using std::begin;
1404  using std::end;
1405 
1406  j.m_type = value_t::object;
1407  j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
1408  j.assert_invariant();
1409  }
1410 };
1411 
1413 // to_json //
1415 
1416 template<typename BasicJsonType, typename T,
1417  enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
1418 void to_json(BasicJsonType& j, T b) noexcept
1419 {
1421 }
1422 
1423 template<typename BasicJsonType, typename CompatibleString,
1424  enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
1425 void to_json(BasicJsonType& j, const CompatibleString& s)
1426 {
1428 }
1429 
1430 template<typename BasicJsonType>
1431 void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
1432 {
1434 }
1435 
1436 template<typename BasicJsonType, typename FloatType,
1437  enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
1438 void to_json(BasicJsonType& j, FloatType val) noexcept
1439 {
1440  external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
1441 }
1442 
1443 template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
1444  enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
1445 void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
1446 {
1447  external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
1448 }
1449 
1450 template<typename BasicJsonType, typename CompatibleNumberIntegerType,
1451  enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
1452 void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
1453 {
1454  external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
1455 }
1456 
1457 template<typename BasicJsonType, typename EnumType,
1458  enable_if_t<std::is_enum<EnumType>::value, int> = 0>
1459 void to_json(BasicJsonType& j, EnumType e) noexcept
1460 {
1461  using underlying_type = typename std::underlying_type<EnumType>::type;
1462  external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
1463 }
1464 
1465 template<typename BasicJsonType>
1466 void to_json(BasicJsonType& j, const std::vector<bool>& e)
1467 {
1469 }
1470 
1471 template<typename BasicJsonType, typename CompatibleArrayType,
1472  enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
1473  std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
1474  int> = 0>
1475 void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
1476 {
1478 }
1479 
1480 template<typename BasicJsonType, typename T,
1481  enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
1482 void to_json(BasicJsonType& j, std::valarray<T> arr)
1483 {
1485 }
1486 
1487 template<typename BasicJsonType>
1488 void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
1489 {
1491 }
1492 
1493 template<typename BasicJsonType, typename CompatibleObjectType,
1494  enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
1495 void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
1496 {
1498 }
1499 
1500 template<typename BasicJsonType>
1501 void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
1502 {
1504 }
1505 
1506 template<typename BasicJsonType, typename T, std::size_t N,
1507  enable_if_t<not std::is_constructible<typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0>
1508 void to_json(BasicJsonType& j, T (&arr)[N])
1509 {
1511 }
1512 
1513 template<typename BasicJsonType, typename... Args>
1514 void to_json(BasicJsonType& j, const std::pair<Args...>& p)
1515 {
1516  j = {p.first, p.second};
1517 }
1518 
1519 template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
1520 void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>)
1521 {
1522  j = {std::get<Idx>(t)...};
1523 }
1524 
1525 template<typename BasicJsonType, typename... Args>
1526 void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
1527 {
1528  to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
1529 }
1530 
1532 {
1533  private:
1534  template<typename BasicJsonType, typename T>
1535  auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
1536  -> decltype(to_json(j, std::forward<T>(val)), void())
1537  {
1538  return to_json(j, std::forward<T>(val));
1539  }
1540 
1541  template<typename BasicJsonType, typename T>
1542  void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept
1543  {
1544  static_assert(sizeof(BasicJsonType) == 0,
1545  "could not find to_json() method in T's namespace");
1546 
1547 #ifdef _MSC_VER
1548  // MSVC does not show a stacktrace for the above assert
1549  using decayed = uncvref_t<T>;
1550  static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
1551  "forcing MSVC stacktrace to show which T we're talking about.");
1552 #endif
1553  }
1554 
1555  public:
1556  template<typename BasicJsonType, typename T>
1557  void operator()(BasicJsonType& j, T&& val) const
1558  noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
1559  {
1560  return call(j, std::forward<T>(val), priority_tag<1> {});
1561  }
1562 };
1563 }
1564 
1566 namespace
1567 {
1568 constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
1569 }
1570 }
1571 
1572 // #include <nlohmann/detail/input/input_adapters.hpp>
1573 
1574 
1575 #include <algorithm> // min
1576 #include <array> // array
1577 #include <cassert> // assert
1578 #include <cstddef> // size_t
1579 #include <cstring> // strlen
1580 #include <ios> // streamsize, streamoff, streampos
1581 #include <istream> // istream
1582 #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
1583 #include <memory> // shared_ptr, make_shared, addressof
1584 #include <numeric> // accumulate
1585 #include <string> // string, char_traits
1586 #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
1587 #include <utility> // pair, declval
1588 
1589 // #include <nlohmann/detail/macro_scope.hpp>
1590 
1591 
1592 namespace nlohmann
1593 {
1594 namespace detail
1595 {
1597 // input adapters //
1599 
1612 {
1614  virtual std::char_traits<char>::int_type get_character() = 0;
1616  virtual void unget_character() = 0;
1617  virtual ~input_adapter_protocol() = default;
1618 };
1619 
1621 using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
1622 
1633 {
1634  public:
1635  ~input_stream_adapter() override
1636  {
1637  // clear stream flags; we use underlying streambuf I/O, do not
1638  // maintain ifstream flags
1639  is.clear();
1640  }
1641 
1642  explicit input_stream_adapter(std::istream& i)
1643  : is(i), sb(*i.rdbuf())
1644  {
1645  // skip byte order mark
1646  std::char_traits<char>::int_type c;
1647  if ((c = get_character()) == 0xEF)
1648  {
1649  if ((c = get_character()) == 0xBB)
1650  {
1651  if ((c = get_character()) == 0xBF)
1652  {
1653  return; // Ignore BOM
1654  }
1655  else if (c != std::char_traits<char>::eof())
1656  {
1657  is.unget();
1658  }
1659  is.putback('\xBB');
1660  }
1661  else if (c != std::char_traits<char>::eof())
1662  {
1663  is.unget();
1664  }
1665  is.putback('\xEF');
1666  }
1667  else if (c != std::char_traits<char>::eof())
1668  {
1669  is.unget(); // no byte order mark; process as usual
1670  }
1671  }
1672 
1673  // delete because of pointer members
1674  input_stream_adapter(const input_stream_adapter&) = delete;
1675  input_stream_adapter& operator=(input_stream_adapter&) = delete;
1676 
1677  // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
1678  // ensure that std::char_traits<char>::eof() and the character 0xFF do not
1679  // end up as the same value, eg. 0xFFFFFFFF.
1680  std::char_traits<char>::int_type get_character() override
1681  {
1682  return sb.sbumpc();
1683  }
1684 
1685  void unget_character() override
1686  {
1687  sb.sungetc(); // is.unget() avoided for performance
1688  }
1689 
1690  private:
1692  std::istream& is;
1693  std::streambuf& sb;
1694 };
1695 
1698 {
1699  public:
1700  input_buffer_adapter(const char* b, const std::size_t l)
1701  : cursor(b), limit(b + l), start(b)
1702  {
1703  // skip byte order mark
1704  if (l >= 3 and b[0] == '\xEF' and b[1] == '\xBB' and b[2] == '\xBF')
1705  {
1706  cursor += 3;
1707  }
1708  }
1709 
1710  // delete because of pointer members
1711  input_buffer_adapter(const input_buffer_adapter&) = delete;
1712  input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
1713 
1714  std::char_traits<char>::int_type get_character() noexcept override
1715  {
1716  if (JSON_LIKELY(cursor < limit))
1717  {
1718  return std::char_traits<char>::to_int_type(*(cursor++));
1719  }
1720 
1721  return std::char_traits<char>::eof();
1722  }
1723 
1724  void unget_character() noexcept override
1725  {
1726  if (JSON_LIKELY(cursor > start))
1727  {
1728  --cursor;
1729  }
1730  }
1731 
1732  private:
1734  const char* cursor;
1736  const char* limit;
1738  const char* start;
1739 };
1740 
1742 {
1743  public:
1744  // native support
1745 
1747  input_adapter(std::istream& i)
1748  : ia(std::make_shared<input_stream_adapter>(i)) {}
1749 
1751  input_adapter(std::istream&& i)
1752  : ia(std::make_shared<input_stream_adapter>(i)) {}
1753 
1755  template<typename CharT,
1756  typename std::enable_if<
1757  std::is_pointer<CharT>::value and
1758  std::is_integral<typename std::remove_pointer<CharT>::type>::value and
1759  sizeof(typename std::remove_pointer<CharT>::type) == 1,
1760  int>::type = 0>
1761  input_adapter(CharT b, std::size_t l)
1762  : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
1763 
1764  // derived support
1765 
1767  template<typename CharT,
1768  typename std::enable_if<
1769  std::is_pointer<CharT>::value and
1770  std::is_integral<typename std::remove_pointer<CharT>::type>::value and
1771  sizeof(typename std::remove_pointer<CharT>::type) == 1,
1772  int>::type = 0>
1773  input_adapter(CharT b)
1774  : input_adapter(reinterpret_cast<const char*>(b),
1775  std::strlen(reinterpret_cast<const char*>(b))) {}
1776 
1778  template<class IteratorType,
1779  typename std::enable_if<
1780  std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
1781  int>::type = 0>
1782  input_adapter(IteratorType first, IteratorType last)
1783  {
1784  // assertion to check that the iterator range is indeed contiguous,
1785  // see http://stackoverflow.com/a/35008842/266378 for more discussion
1786  assert(std::accumulate(
1787  first, last, std::pair<bool, int>(true, 0),
1788  [&first](std::pair<bool, int> res, decltype(*first) val)
1789  {
1790  res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
1791  return res;
1792  }).first);
1793 
1794  // assertion to check that each element is 1 byte long
1795  static_assert(
1796  sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
1797  "each element in the iterator range must have the size of 1 byte");
1798 
1799  const auto len = static_cast<size_t>(std::distance(first, last));
1800  if (JSON_LIKELY(len > 0))
1801  {
1802  // there is at least one element: use the address of first
1803  ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
1804  }
1805  else
1806  {
1807  // the address of first cannot be used: use nullptr
1808  ia = std::make_shared<input_buffer_adapter>(nullptr, len);
1809  }
1810  }
1811 
1813  template<class T, std::size_t N>
1815  : input_adapter(std::begin(array), std::end(array)) {}
1816 
1818  template<class ContiguousContainer, typename
1819  std::enable_if<not std::is_pointer<ContiguousContainer>::value and
1820  std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
1821  int>::type = 0>
1822  input_adapter(const ContiguousContainer& c)
1823  : input_adapter(std::begin(c), std::end(c)) {}
1824 
1825  operator input_adapter_t()
1826  {
1827  return ia;
1828  }
1829 
1830  private:
1832  input_adapter_t ia = nullptr;
1833 };
1834 }
1835 }
1836 
1837 // #include <nlohmann/detail/input/lexer.hpp>
1838 
1839 
1840 #include <clocale> // localeconv
1841 #include <cstddef> // size_t
1842 #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
1843 #include <initializer_list> // initializer_list
1844 #include <ios> // hex, uppercase
1845 #include <iomanip> // setw, setfill
1846 #include <sstream> // stringstream
1847 #include <string> // char_traits, string
1848 #include <vector> // vector
1849 
1850 // #include <nlohmann/detail/macro_scope.hpp>
1851 
1852 // #include <nlohmann/detail/input/input_adapters.hpp>
1853 
1854 
1855 namespace nlohmann
1856 {
1857 namespace detail
1858 {
1860 // lexer //
1862 
1868 template<typename BasicJsonType>
1869 class lexer
1870 {
1871  using number_integer_t = typename BasicJsonType::number_integer_t;
1872  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
1873  using number_float_t = typename BasicJsonType::number_float_t;
1874  using string_t = typename BasicJsonType::string_t;
1875 
1876  public:
1878  enum class token_type
1879  {
1880  uninitialized,
1881  literal_true,
1882  literal_false,
1883  literal_null,
1884  value_string,
1885  value_unsigned,
1886  value_integer,
1887  value_float,
1888  begin_array,
1889  begin_object,
1890  end_array,
1891  end_object,
1892  name_separator,
1893  value_separator,
1894  parse_error,
1895  end_of_input,
1896  literal_or_value
1897  };
1898 
1900  static const char* token_type_name(const token_type t) noexcept
1901  {
1902  switch (t)
1903  {
1904  case token_type::uninitialized:
1905  return "<uninitialized>";
1906  case token_type::literal_true:
1907  return "true literal";
1908  case token_type::literal_false:
1909  return "false literal";
1910  case token_type::literal_null:
1911  return "null literal";
1912  case token_type::value_string:
1913  return "string literal";
1917  return "number literal";
1918  case token_type::begin_array:
1919  return "'['";
1920  case token_type::begin_object:
1921  return "'{'";
1922  case token_type::end_array:
1923  return "']'";
1924  case token_type::end_object:
1925  return "'}'";
1926  case token_type::name_separator:
1927  return "':'";
1928  case token_type::value_separator:
1929  return "','";
1930  case token_type::parse_error:
1931  return "<parse error>";
1932  case token_type::end_of_input:
1933  return "end of input";
1934  case token_type::literal_or_value:
1935  return "'[', '{', or a literal";
1936  default: // catch non-enum values
1937  return "unknown token"; // LCOV_EXCL_LINE
1938  }
1939  }
1940 
1941  explicit lexer(detail::input_adapter_t adapter)
1942  : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
1943 
1944  // delete because of pointer members
1945  lexer(const lexer&) = delete;
1946  lexer& operator=(lexer&) = delete;
1947 
1948  private:
1950  // locales
1952 
1954  static char get_decimal_point() noexcept
1955  {
1956  const auto loc = localeconv();
1957  assert(loc != nullptr);
1958  return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
1959  }
1960 
1962  // scan functions
1964 
1980  int get_codepoint()
1981  {
1982  // this function only makes sense after reading `\u`
1983  assert(current == 'u');
1984  int codepoint = 0;
1985 
1986  const auto factors = { 12, 8, 4, 0 };
1987  for (const auto factor : factors)
1988  {
1989  get();
1990 
1991  if (current >= '0' and current <= '9')
1992  {
1993  codepoint += ((current - 0x30) << factor);
1994  }
1995  else if (current >= 'A' and current <= 'F')
1996  {
1997  codepoint += ((current - 0x37) << factor);
1998  }
1999  else if (current >= 'a' and current <= 'f')
2000  {
2001  codepoint += ((current - 0x57) << factor);
2002  }
2003  else
2004  {
2005  return -1;
2006  }
2007  }
2008 
2009  assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
2010  return codepoint;
2011  }
2012 
2028  bool next_byte_in_range(std::initializer_list<int> ranges)
2029  {
2030  assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
2031  add(current);
2032 
2033  for (auto range = ranges.begin(); range != ranges.end(); ++range)
2034  {
2035  get();
2036  if (JSON_LIKELY(*range <= current and current <= *(++range)))
2037  {
2038  add(current);
2039  }
2040  else
2041  {
2042  error_message = "invalid string: ill-formed UTF-8 byte";
2043  return false;
2044  }
2045  }
2046 
2047  return true;
2048  }
2049 
2065  token_type scan_string()
2066  {
2067  // reset token_buffer (ignore opening quote)
2068  reset();
2069 
2070  // we entered the function by reading an open quote
2071  assert(current == '\"');
2072 
2073  while (true)
2074  {
2075  // get next character
2076  switch (get())
2077  {
2078  // end of file while parsing string
2079  case std::char_traits<char>::eof():
2080  {
2081  error_message = "invalid string: missing closing quote";
2082  return token_type::parse_error;
2083  }
2084 
2085  // closing quote
2086  case '\"':
2087  {
2088  return token_type::value_string;
2089  }
2090 
2091  // escapes
2092  case '\\':
2093  {
2094  switch (get())
2095  {
2096  // quotation mark
2097  case '\"':
2098  add('\"');
2099  break;
2100  // reverse solidus
2101  case '\\':
2102  add('\\');
2103  break;
2104  // solidus
2105  case '/':
2106  add('/');
2107  break;
2108  // backspace
2109  case 'b':
2110  add('\b');
2111  break;
2112  // form feed
2113  case 'f':
2114  add('\f');
2115  break;
2116  // line feed
2117  case 'n':
2118  add('\n');
2119  break;
2120  // carriage return
2121  case 'r':
2122  add('\r');
2123  break;
2124  // tab
2125  case 't':
2126  add('\t');
2127  break;
2128 
2129  // unicode escapes
2130  case 'u':
2131  {
2132  const int codepoint1 = get_codepoint();
2133  int codepoint = codepoint1; // start with codepoint1
2134 
2135  if (JSON_UNLIKELY(codepoint1 == -1))
2136  {
2137  error_message = "invalid string: '\\u' must be followed by 4 hex digits";
2138  return token_type::parse_error;
2139  }
2140 
2141  // check if code point is a high surrogate
2142  if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
2143  {
2144  // expect next \uxxxx entry
2145  if (JSON_LIKELY(get() == '\\' and get() == 'u'))
2146  {
2147  const int codepoint2 = get_codepoint();
2148 
2149  if (JSON_UNLIKELY(codepoint2 == -1))
2150  {
2151  error_message = "invalid string: '\\u' must be followed by 4 hex digits";
2152  return token_type::parse_error;
2153  }
2154 
2155  // check if codepoint2 is a low surrogate
2156  if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
2157  {
2158  // overwrite codepoint
2159  codepoint =
2160  // high surrogate occupies the most significant 22 bits
2161  (codepoint1 << 10)
2162  // low surrogate occupies the least significant 15 bits
2163  + codepoint2
2164  // there is still the 0xD800, 0xDC00 and 0x10000 noise
2165  // in the result so we have to subtract with:
2166  // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
2167  - 0x35FDC00;
2168  }
2169  else
2170  {
2171  error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
2172  return token_type::parse_error;
2173  }
2174  }
2175  else
2176  {
2177  error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
2178  return token_type::parse_error;
2179  }
2180  }
2181  else
2182  {
2183  if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
2184  {
2185  error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
2186  return token_type::parse_error;
2187  }
2188  }
2189 
2190  // result of the above calculation yields a proper codepoint
2191  assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
2192 
2193  // translate codepoint into bytes
2194  if (codepoint < 0x80)
2195  {
2196  // 1-byte characters: 0xxxxxxx (ASCII)
2197  add(codepoint);
2198  }
2199  else if (codepoint <= 0x7FF)
2200  {
2201  // 2-byte characters: 110xxxxx 10xxxxxx
2202  add(0xC0 | (codepoint >> 6));
2203  add(0x80 | (codepoint & 0x3F));
2204  }
2205  else if (codepoint <= 0xFFFF)
2206  {
2207  // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
2208  add(0xE0 | (codepoint >> 12));
2209  add(0x80 | ((codepoint >> 6) & 0x3F));
2210  add(0x80 | (codepoint & 0x3F));
2211  }
2212  else
2213  {
2214  // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2215  add(0xF0 | (codepoint >> 18));
2216  add(0x80 | ((codepoint >> 12) & 0x3F));
2217  add(0x80 | ((codepoint >> 6) & 0x3F));
2218  add(0x80 | (codepoint & 0x3F));
2219  }
2220 
2221  break;
2222  }
2223 
2224  // other characters after escape
2225  default:
2226  error_message = "invalid string: forbidden character after backslash";
2227  return token_type::parse_error;
2228  }
2229 
2230  break;
2231  }
2232 
2233  // invalid control characters
2234  case 0x00:
2235  case 0x01:
2236  case 0x02:
2237  case 0x03:
2238  case 0x04:
2239  case 0x05:
2240  case 0x06:
2241  case 0x07:
2242  case 0x08:
2243  case 0x09:
2244  case 0x0A:
2245  case 0x0B:
2246  case 0x0C:
2247  case 0x0D:
2248  case 0x0E:
2249  case 0x0F:
2250  case 0x10:
2251  case 0x11:
2252  case 0x12:
2253  case 0x13:
2254  case 0x14:
2255  case 0x15:
2256  case 0x16:
2257  case 0x17:
2258  case 0x18:
2259  case 0x19:
2260  case 0x1A:
2261  case 0x1B:
2262  case 0x1C:
2263  case 0x1D:
2264  case 0x1E:
2265  case 0x1F:
2266  {
2267  error_message = "invalid string: control character must be escaped";
2268  return token_type::parse_error;
2269  }
2270 
2271  // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
2272  case 0x20:
2273  case 0x21:
2274  case 0x23:
2275  case 0x24:
2276  case 0x25:
2277  case 0x26:
2278  case 0x27:
2279  case 0x28:
2280  case 0x29:
2281  case 0x2A:
2282  case 0x2B:
2283  case 0x2C:
2284  case 0x2D:
2285  case 0x2E:
2286  case 0x2F:
2287  case 0x30:
2288  case 0x31:
2289  case 0x32:
2290  case 0x33:
2291  case 0x34:
2292  case 0x35:
2293  case 0x36:
2294  case 0x37:
2295  case 0x38:
2296  case 0x39:
2297  case 0x3A:
2298  case 0x3B:
2299  case 0x3C:
2300  case 0x3D:
2301  case 0x3E:
2302  case 0x3F:
2303  case 0x40:
2304  case 0x41:
2305  case 0x42:
2306  case 0x43:
2307  case 0x44:
2308  case 0x45:
2309  case 0x46:
2310  case 0x47:
2311  case 0x48:
2312  case 0x49:
2313  case 0x4A:
2314  case 0x4B:
2315  case 0x4C:
2316  case 0x4D:
2317  case 0x4E:
2318  case 0x4F:
2319  case 0x50:
2320  case 0x51:
2321  case 0x52:
2322  case 0x53:
2323  case 0x54:
2324  case 0x55:
2325  case 0x56:
2326  case 0x57:
2327  case 0x58:
2328  case 0x59:
2329  case 0x5A:
2330  case 0x5B:
2331  case 0x5D:
2332  case 0x5E:
2333  case 0x5F:
2334  case 0x60:
2335  case 0x61:
2336  case 0x62:
2337  case 0x63:
2338  case 0x64:
2339  case 0x65:
2340  case 0x66:
2341  case 0x67:
2342  case 0x68:
2343  case 0x69:
2344  case 0x6A:
2345  case 0x6B:
2346  case 0x6C:
2347  case 0x6D:
2348  case 0x6E:
2349  case 0x6F:
2350  case 0x70:
2351  case 0x71:
2352  case 0x72:
2353  case 0x73:
2354  case 0x74:
2355  case 0x75:
2356  case 0x76:
2357  case 0x77:
2358  case 0x78:
2359  case 0x79:
2360  case 0x7A:
2361  case 0x7B:
2362  case 0x7C:
2363  case 0x7D:
2364  case 0x7E:
2365  case 0x7F:
2366  {
2367  add(current);
2368  break;
2369  }
2370 
2371  // U+0080..U+07FF: bytes C2..DF 80..BF
2372  case 0xC2:
2373  case 0xC3:
2374  case 0xC4:
2375  case 0xC5:
2376  case 0xC6:
2377  case 0xC7:
2378  case 0xC8:
2379  case 0xC9:
2380  case 0xCA:
2381  case 0xCB:
2382  case 0xCC:
2383  case 0xCD:
2384  case 0xCE:
2385  case 0xCF:
2386  case 0xD0:
2387  case 0xD1:
2388  case 0xD2:
2389  case 0xD3:
2390  case 0xD4:
2391  case 0xD5:
2392  case 0xD6:
2393  case 0xD7:
2394  case 0xD8:
2395  case 0xD9:
2396  case 0xDA:
2397  case 0xDB:
2398  case 0xDC:
2399  case 0xDD:
2400  case 0xDE:
2401  case 0xDF:
2402  {
2403  if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
2404  {
2405  return token_type::parse_error;
2406  }
2407  break;
2408  }
2409 
2410  // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
2411  case 0xE0:
2412  {
2413  if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
2414  {
2415  return token_type::parse_error;
2416  }
2417  break;
2418  }
2419 
2420  // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
2421  // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
2422  case 0xE1:
2423  case 0xE2:
2424  case 0xE3:
2425  case 0xE4:
2426  case 0xE5:
2427  case 0xE6:
2428  case 0xE7:
2429  case 0xE8:
2430  case 0xE9:
2431  case 0xEA:
2432  case 0xEB:
2433  case 0xEC:
2434  case 0xEE:
2435  case 0xEF:
2436  {
2437  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
2438  {
2439  return token_type::parse_error;
2440  }
2441  break;
2442  }
2443 
2444  // U+D000..U+D7FF: bytes ED 80..9F 80..BF
2445  case 0xED:
2446  {
2447  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
2448  {
2449  return token_type::parse_error;
2450  }
2451  break;
2452  }
2453 
2454  // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
2455  case 0xF0:
2456  {
2457  if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
2458  {
2459  return token_type::parse_error;
2460  }
2461  break;
2462  }
2463 
2464  // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
2465  case 0xF1:
2466  case 0xF2:
2467  case 0xF3:
2468  {
2469  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
2470  {
2471  return token_type::parse_error;
2472  }
2473  break;
2474  }
2475 
2476  // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
2477  case 0xF4:
2478  {
2479  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
2480  {
2481  return token_type::parse_error;
2482  }
2483  break;
2484  }
2485 
2486  // remaining bytes (80..C1 and F5..FF) are ill-formed
2487  default:
2488  {
2489  error_message = "invalid string: ill-formed UTF-8 byte";
2490  return token_type::parse_error;
2491  }
2492  }
2493  }
2494  }
2495 
2496  static void strtof(float& f, const char* str, char** endptr) noexcept
2497  {
2498  f = std::strtof(str, endptr);
2499  }
2500 
2501  static void strtof(double& f, const char* str, char** endptr) noexcept
2502  {
2503  f = std::strtod(str, endptr);
2504  }
2505 
2506  static void strtof(long double& f, const char* str, char** endptr) noexcept
2507  {
2508  f = std::strtold(str, endptr);
2509  }
2510 
2551  token_type scan_number()
2552  {
2553  // reset token_buffer to store the number's bytes
2554  reset();
2555 
2556  // the type of the parsed number; initially set to unsigned; will be
2557  // changed if minus sign, decimal point or exponent is read
2558  token_type number_type = token_type::value_unsigned;
2559 
2560  // state (init): we just found out we need to scan a number
2561  switch (current)
2562  {
2563  case '-':
2564  {
2565  add(current);
2566  goto scan_number_minus;
2567  }
2568 
2569  case '0':
2570  {
2571  add(current);
2572  goto scan_number_zero;
2573  }
2574 
2575  case '1':
2576  case '2':
2577  case '3':
2578  case '4':
2579  case '5':
2580  case '6':
2581  case '7':
2582  case '8':
2583  case '9':
2584  {
2585  add(current);
2586  goto scan_number_any1;
2587  }
2588 
2589  default:
2590  {
2591  // all other characters are rejected outside scan_number()
2592  assert(false); // LCOV_EXCL_LINE
2593  }
2594  }
2595 
2596 scan_number_minus:
2597  // state: we just parsed a leading minus sign
2598  number_type = token_type::value_integer;
2599  switch (get())
2600  {
2601  case '0':
2602  {
2603  add(current);
2604  goto scan_number_zero;
2605  }
2606 
2607  case '1':
2608  case '2':
2609  case '3':
2610  case '4':
2611  case '5':
2612  case '6':
2613  case '7':
2614  case '8':
2615  case '9':
2616  {
2617  add(current);
2618  goto scan_number_any1;
2619  }
2620 
2621  default:
2622  {
2623  error_message = "invalid number; expected digit after '-'";
2624  return token_type::parse_error;
2625  }
2626  }
2627 
2628 scan_number_zero:
2629  // state: we just parse a zero (maybe with a leading minus sign)
2630  switch (get())
2631  {
2632  case '.':
2633  {
2634  add(decimal_point_char);
2635  goto scan_number_decimal1;
2636  }
2637 
2638  case 'e':
2639  case 'E':
2640  {
2641  add(current);
2642  goto scan_number_exponent;
2643  }
2644 
2645  default:
2646  goto scan_number_done;
2647  }
2648 
2649 scan_number_any1:
2650  // state: we just parsed a number 0-9 (maybe with a leading minus sign)
2651  switch (get())
2652  {
2653  case '0':
2654  case '1':
2655  case '2':
2656  case '3':
2657  case '4':
2658  case '5':
2659  case '6':
2660  case '7':
2661  case '8':
2662  case '9':
2663  {
2664  add(current);
2665  goto scan_number_any1;
2666  }
2667 
2668  case '.':
2669  {
2670  add(decimal_point_char);
2671  goto scan_number_decimal1;
2672  }
2673 
2674  case 'e':
2675  case 'E':
2676  {
2677  add(current);
2678  goto scan_number_exponent;
2679  }
2680 
2681  default:
2682  goto scan_number_done;
2683  }
2684 
2685 scan_number_decimal1:
2686  // state: we just parsed a decimal point
2687  number_type = token_type::value_float;
2688  switch (get())
2689  {
2690  case '0':
2691  case '1':
2692  case '2':
2693  case '3':
2694  case '4':
2695  case '5':
2696  case '6':
2697  case '7':
2698  case '8':
2699  case '9':
2700  {
2701  add(current);
2702  goto scan_number_decimal2;
2703  }
2704 
2705  default:
2706  {
2707  error_message = "invalid number; expected digit after '.'";
2708  return token_type::parse_error;
2709  }
2710  }
2711 
2712 scan_number_decimal2:
2713  // we just parsed at least one number after a decimal point
2714  switch (get())
2715  {
2716  case '0':
2717  case '1':
2718  case '2':
2719  case '3':
2720  case '4':
2721  case '5':
2722  case '6':
2723  case '7':
2724  case '8':
2725  case '9':
2726  {
2727  add(current);
2728  goto scan_number_decimal2;
2729  }
2730 
2731  case 'e':
2732  case 'E':
2733  {
2734  add(current);
2735  goto scan_number_exponent;
2736  }
2737 
2738  default:
2739  goto scan_number_done;
2740  }
2741 
2742 scan_number_exponent:
2743  // we just parsed an exponent
2744  number_type = token_type::value_float;
2745  switch (get())
2746  {
2747  case '+':
2748  case '-':
2749  {
2750  add(current);
2751  goto scan_number_sign;
2752  }
2753 
2754  case '0':
2755  case '1':
2756  case '2':
2757  case '3':
2758  case '4':
2759  case '5':
2760  case '6':
2761  case '7':
2762  case '8':
2763  case '9':
2764  {
2765  add(current);
2766  goto scan_number_any2;
2767  }
2768 
2769  default:
2770  {
2771  error_message =
2772  "invalid number; expected '+', '-', or digit after exponent";
2773  return token_type::parse_error;
2774  }
2775  }
2776 
2777 scan_number_sign:
2778  // we just parsed an exponent sign
2779  switch (get())
2780  {
2781  case '0':
2782  case '1':
2783  case '2':
2784  case '3':
2785  case '4':
2786  case '5':
2787  case '6':
2788  case '7':
2789  case '8':
2790  case '9':
2791  {
2792  add(current);
2793  goto scan_number_any2;
2794  }
2795 
2796  default:
2797  {
2798  error_message = "invalid number; expected digit after exponent sign";
2799  return token_type::parse_error;
2800  }
2801  }
2802 
2803 scan_number_any2:
2804  // we just parsed a number after the exponent or exponent sign
2805  switch (get())
2806  {
2807  case '0':
2808  case '1':
2809  case '2':
2810  case '3':
2811  case '4':
2812  case '5':
2813  case '6':
2814  case '7':
2815  case '8':
2816  case '9':
2817  {
2818  add(current);
2819  goto scan_number_any2;
2820  }
2821 
2822  default:
2823  goto scan_number_done;
2824  }
2825 
2826 scan_number_done:
2827  // unget the character after the number (we only read it to know that
2828  // we are done scanning a number)
2829  unget();
2830 
2831  char* endptr = nullptr;
2832  errno = 0;
2833 
2834  // try to parse integers first and fall back to floats
2835  if (number_type == token_type::value_unsigned)
2836  {
2837  const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
2838 
2839  // we checked the number format before
2840  assert(endptr == token_buffer.data() + token_buffer.size());
2841 
2842  if (errno == 0)
2843  {
2844  value_unsigned = static_cast<number_unsigned_t>(x);
2845  if (value_unsigned == x)
2846  {
2847  return token_type::value_unsigned;
2848  }
2849  }
2850  }
2851  else if (number_type == token_type::value_integer)
2852  {
2853  const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
2854 
2855  // we checked the number format before
2856  assert(endptr == token_buffer.data() + token_buffer.size());
2857 
2858  if (errno == 0)
2859  {
2860  value_integer = static_cast<number_integer_t>(x);
2861  if (value_integer == x)
2862  {
2863  return token_type::value_integer;
2864  }
2865  }
2866  }
2867 
2868  // this code is reached if we parse a floating-point number or if an
2869  // integer conversion above failed
2870  strtof(value_float, token_buffer.data(), &endptr);
2871 
2872  // we checked the number format before
2873  assert(endptr == token_buffer.data() + token_buffer.size());
2874 
2875  return token_type::value_float;
2876  }
2877 
2883  token_type scan_literal(const char* literal_text, const std::size_t length,
2884  token_type return_type)
2885  {
2886  assert(current == literal_text[0]);
2887  for (std::size_t i = 1; i < length; ++i)
2888  {
2889  if (JSON_UNLIKELY(get() != literal_text[i]))
2890  {
2891  error_message = "invalid literal";
2892  return token_type::parse_error;
2893  }
2894  }
2895  return return_type;
2896  }
2897 
2899  // input management
2901 
2903  void reset() noexcept
2904  {
2905  token_buffer.clear();
2906  token_string.clear();
2907  token_string.push_back(std::char_traits<char>::to_char_type(current));
2908  }
2909 
2910  /*
2911  @brief get next character from the input
2912 
2913  This function provides the interface to the used input adapter. It does
2914  not throw in case the input reached EOF, but returns a
2915  `std::char_traits<char>::eof()` in that case. Stores the scanned characters
2916  for use in error messages.
2917 
2918  @return character read from the input
2919  */
2920  std::char_traits<char>::int_type get()
2921  {
2922  ++chars_read;
2923  current = ia->get_character();
2924  if (JSON_LIKELY(current != std::char_traits<char>::eof()))
2925  {
2926  token_string.push_back(std::char_traits<char>::to_char_type(current));
2927  }
2928  return current;
2929  }
2930 
2932  void unget()
2933  {
2934  --chars_read;
2935  if (JSON_LIKELY(current != std::char_traits<char>::eof()))
2936  {
2937  ia->unget_character();
2938  assert(token_string.size() != 0);
2939  token_string.pop_back();
2940  }
2941  }
2942 
2944  void add(int c)
2945  {
2946  token_buffer.push_back(std::char_traits<char>::to_char_type(c));
2947  }
2948 
2949  public:
2951  // value getters
2953 
2955  constexpr number_integer_t get_number_integer() const noexcept
2956  {
2957  return value_integer;
2958  }
2959 
2961  constexpr number_unsigned_t get_number_unsigned() const noexcept
2962  {
2963  return value_unsigned;
2964  }
2965 
2967  constexpr number_float_t get_number_float() const noexcept
2968  {
2969  return value_float;
2970  }
2971 
2973  string_t&& move_string()
2974  {
2975  return std::move(token_buffer);
2976  }
2977 
2979  // diagnostics
2981 
2983  constexpr std::size_t get_position() const noexcept
2984  {
2985  return chars_read;
2986  }
2987 
2992  {
2993  // escape control characters
2994  std::string result;
2995  for (const auto c : token_string)
2996  {
2997  if ('\x00' <= c and c <= '\x1F')
2998  {
2999  // escape control characters
3000  std::stringstream ss;
3001  ss << "<U+" << std::setw(4) << std::uppercase << std::setfill('0')
3002  << std::hex << static_cast<int>(c) << ">";
3003  result += ss.str();
3004  }
3005  else
3006  {
3007  // add character as is
3008  result.push_back(c);
3009  }
3010  }
3011 
3012  return result;
3013  }
3014 
3016  constexpr const char* get_error_message() const noexcept
3017  {
3018  return error_message;
3019  }
3020 
3022  // actual scanner
3024 
3025  token_type scan()
3026  {
3027  // read next character and ignore whitespace
3028  do
3029  {
3030  get();
3031  }
3032  while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
3033 
3034  switch (current)
3035  {
3036  // structural characters
3037  case '[':
3038  return token_type::begin_array;
3039  case ']':
3040  return token_type::end_array;
3041  case '{':
3042  return token_type::begin_object;
3043  case '}':
3044  return token_type::end_object;
3045  case ':':
3046  return token_type::name_separator;
3047  case ',':
3048  return token_type::value_separator;
3049 
3050  // literals
3051  case 't':
3052  return scan_literal("true", 4, token_type::literal_true);
3053  case 'f':
3054  return scan_literal("false", 5, token_type::literal_false);
3055  case 'n':
3056  return scan_literal("null", 4, token_type::literal_null);
3057 
3058  // string
3059  case '\"':
3060  return scan_string();
3061 
3062  // number
3063  case '-':
3064  case '0':
3065  case '1':
3066  case '2':
3067  case '3':
3068  case '4':
3069  case '5':
3070  case '6':
3071  case '7':
3072  case '8':
3073  case '9':
3074  return scan_number();
3075 
3076  // end of input (the null byte is needed when parsing from
3077  // string literals)
3078  case '\0':
3079  case std::char_traits<char>::eof():
3080  return token_type::end_of_input;
3081 
3082  // error
3083  default:
3084  error_message = "invalid literal";
3085  return token_type::parse_error;
3086  }
3087  }
3088 
3089  private:
3091  detail::input_adapter_t ia = nullptr;
3092 
3094  std::char_traits<char>::int_type current = std::char_traits<char>::eof();
3095 
3097  std::size_t chars_read = 0;
3098 
3100  std::vector<char> token_string {};
3101 
3103  string_t token_buffer {};
3104 
3106  const char* error_message = "";
3107 
3108  // number values
3109  number_integer_t value_integer = 0;
3110  number_unsigned_t value_unsigned = 0;
3111  number_float_t value_float = 0;
3112 
3114  const char decimal_point_char = '.';
3115 };
3116 }
3117 }
3118 
3119 // #include <nlohmann/detail/input/parser.hpp>
3120 
3121 
3122 #include <cassert> // assert
3123 #include <cmath> // isfinite
3124 #include <cstdint> // uint8_t
3125 #include <functional> // function
3126 #include <string> // string
3127 #include <utility> // move
3128 
3129 // #include <nlohmann/detail/exceptions.hpp>
3130 
3131 // #include <nlohmann/detail/macro_scope.hpp>
3132 
3133 // #include <nlohmann/detail/input/input_adapters.hpp>
3134 
3135 // #include <nlohmann/detail/input/lexer.hpp>
3136 
3137 // #include <nlohmann/detail/value_t.hpp>
3138 
3139 
3140 namespace nlohmann
3141 {
3142 namespace detail
3143 {
3145 // parser //
3147 
3153 template<typename BasicJsonType>
3154 class parser
3155 {
3156  using number_integer_t = typename BasicJsonType::number_integer_t;
3157  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
3158  using number_float_t = typename BasicJsonType::number_float_t;
3159  using string_t = typename BasicJsonType::string_t;
3160  using lexer_t = lexer<BasicJsonType>;
3161  using token_type = typename lexer_t::token_type;
3162 
3163  public:
3164  enum class parse_event_t : uint8_t
3165  {
3167  object_start,
3169  object_end,
3171  array_start,
3173  array_end,
3175  key,
3177  value
3178  };
3179 
3180  using parser_callback_t =
3181  std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
3182 
3185  const parser_callback_t cb = nullptr,
3186  const bool allow_exceptions_ = true)
3187  : callback(cb), m_lexer(adapter), allow_exceptions(allow_exceptions_)
3188  {}
3189 
3200  void parse(const bool strict, BasicJsonType& result)
3201  {
3202  // read first token
3203  get_token();
3204 
3205  parse_internal(true, result);
3206  result.assert_invariant();
3207 
3208  // in strict mode, input must be completely read
3209  if (strict)
3210  {
3211  get_token();
3212  expect(token_type::end_of_input);
3213  }
3214 
3215  // in case of an error, return discarded value
3216  if (errored)
3217  {
3218  result = value_t::discarded;
3219  return;
3220  }
3221 
3222  // set top-level value to null if it was discarded by the callback
3223  // function
3224  if (result.is_discarded())
3225  {
3226  result = nullptr;
3227  }
3228  }
3229 
3236  bool accept(const bool strict = true)
3237  {
3238  // read first token
3239  get_token();
3240 
3241  if (not accept_internal())
3242  {
3243  return false;
3244  }
3245 
3246  // strict => last token must be EOF
3247  return not strict or (get_token() == token_type::end_of_input);
3248  }
3249 
3250  private:
3257  void parse_internal(bool keep, BasicJsonType& result)
3258  {
3259  // never parse after a parse error was detected
3260  assert(not errored);
3261 
3262  // start with a discarded value
3263  if (not result.is_discarded())
3264  {
3265  result.m_value.destroy(result.m_type);
3266  result.m_type = value_t::discarded;
3267  }
3268 
3269  switch (last_token)
3270  {
3271  case token_type::begin_object:
3272  {
3273  if (keep)
3274  {
3275  if (callback)
3276  {
3277  keep = callback(depth++, parse_event_t::object_start, result);
3278  }
3279 
3280  if (not callback or keep)
3281  {
3282  // explicitly set result to object to cope with {}
3283  result.m_type = value_t::object;
3284  result.m_value = value_t::object;
3285  }
3286  }
3287 
3288  // read next token
3289  get_token();
3290 
3291  // closing } -> we are done
3292  if (last_token == token_type::end_object)
3293  {
3294  if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
3295  {
3296  result.m_value.destroy(result.m_type);
3297  result.m_type = value_t::discarded;
3298  }
3299  break;
3300  }
3301 
3302  // parse values
3303  string_t key;
3304  BasicJsonType value;
3305  while (true)
3306  {
3307  // store key
3308  if (not expect(token_type::value_string))
3309  {
3310  return;
3311  }
3312  key = m_lexer.move_string();
3313 
3314  bool keep_tag = false;
3315  if (keep)
3316  {
3317  if (callback)
3318  {
3319  BasicJsonType k(key);
3320  keep_tag = callback(depth, parse_event_t::key, k);
3321  }
3322  else
3323  {
3324  keep_tag = true;
3325  }
3326  }
3327 
3328  // parse separator (:)
3329  get_token();
3330  if (not expect(token_type::name_separator))
3331  {
3332  return;
3333  }
3334 
3335  // parse and add value
3336  get_token();
3337  value.m_value.destroy(value.m_type);
3338  value.m_type = value_t::discarded;
3339  parse_internal(keep, value);
3340 
3341  if (JSON_UNLIKELY(errored))
3342  {
3343  return;
3344  }
3345 
3346  if (keep and keep_tag and not value.is_discarded())
3347  {
3348  result.m_value.object->emplace(std::move(key), std::move(value));
3349  }
3350 
3351  // comma -> next value
3352  get_token();
3353  if (last_token == token_type::value_separator)
3354  {
3355  get_token();
3356  continue;
3357  }
3358 
3359  // closing }
3360  if (not expect(token_type::end_object))
3361  {
3362  return;
3363  }
3364  break;
3365  }
3366 
3367  if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
3368  {
3369  result.m_value.destroy(result.m_type);
3370  result.m_type = value_t::discarded;
3371  }
3372  break;
3373  }
3374 
3375  case token_type::begin_array:
3376  {
3377  if (keep)
3378  {
3379  if (callback)
3380  {
3381  keep = callback(depth++, parse_event_t::array_start, result);
3382  }
3383 
3384  if (not callback or keep)
3385  {
3386  // explicitly set result to array to cope with []
3387  result.m_type = value_t::array;
3388  result.m_value = value_t::array;
3389  }
3390  }
3391 
3392  // read next token
3393  get_token();
3394 
3395  // closing ] -> we are done
3396  if (last_token == token_type::end_array)
3397  {
3398  if (callback and not callback(--depth, parse_event_t::array_end, result))
3399  {
3400  result.m_value.destroy(result.m_type);
3401  result.m_type = value_t::discarded;
3402  }
3403  break;
3404  }
3405 
3406  // parse values
3407  BasicJsonType value;
3408  while (true)
3409  {
3410  // parse value
3411  value.m_value.destroy(value.m_type);
3412  value.m_type = value_t::discarded;
3413  parse_internal(keep, value);
3414 
3415  if (JSON_UNLIKELY(errored))
3416  {
3417  return;
3418  }
3419 
3420  if (keep and not value.is_discarded())
3421  {
3422  result.m_value.array->push_back(std::move(value));
3423  }
3424 
3425  // comma -> next value
3426  get_token();
3427  if (last_token == token_type::value_separator)
3428  {
3429  get_token();
3430  continue;
3431  }
3432 
3433  // closing ]
3434  if (not expect(token_type::end_array))
3435  {
3436  return;
3437  }
3438  break;
3439  }
3440 
3441  if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
3442  {
3443  result.m_value.destroy(result.m_type);
3444  result.m_type = value_t::discarded;
3445  }
3446  break;
3447  }
3448 
3449  case token_type::literal_null:
3450  {
3451  result.m_type = value_t::null;
3452  break;
3453  }
3454 
3455  case token_type::value_string:
3456  {
3457  result.m_type = value_t::string;
3458  result.m_value = m_lexer.move_string();
3459  break;
3460  }
3461 
3462  case token_type::literal_true:
3463  {
3464  result.m_type = value_t::boolean;
3465  result.m_value = true;
3466  break;
3467  }
3468 
3469  case token_type::literal_false:
3470  {
3471  result.m_type = value_t::boolean;
3472  result.m_value = false;
3473  break;
3474  }
3475 
3476  case token_type::value_unsigned:
3477  {
3478  result.m_type = value_t::number_unsigned;
3479  result.m_value = m_lexer.get_number_unsigned();
3480  break;
3481  }
3482 
3483  case token_type::value_integer:
3484  {
3485  result.m_type = value_t::number_integer;
3486  result.m_value = m_lexer.get_number_integer();
3487  break;
3488  }
3489 
3490  case token_type::value_float:
3491  {
3492  result.m_type = value_t::number_float;
3493  result.m_value = m_lexer.get_number_float();
3494 
3495  // throw in case of infinity or NAN
3496  if (JSON_UNLIKELY(not std::isfinite(result.m_value.number_float)))
3497  {
3498  if (allow_exceptions)
3499  {
3500  JSON_THROW(out_of_range::create(406, "number overflow parsing '" +
3501  m_lexer.get_token_string() + "'"));
3502  }
3503  expect(token_type::uninitialized);
3504  }
3505  break;
3506  }
3507 
3508  case token_type::parse_error:
3509  {
3510  // using "uninitialized" to avoid "expected" message
3511  if (not expect(token_type::uninitialized))
3512  {
3513  return;
3514  }
3515  break; // LCOV_EXCL_LINE
3516  }
3517 
3518  default:
3519  {
3520  // the last token was unexpected; we expected a value
3521  if (not expect(token_type::literal_or_value))
3522  {
3523  return;
3524  }
3525  break; // LCOV_EXCL_LINE
3526  }
3527  }
3528 
3529  if (keep and callback and not callback(depth, parse_event_t::value, result))
3530  {
3531  result.m_value.destroy(result.m_type);
3532  result.m_type = value_t::discarded;
3533  }
3534  }
3535 
3546  bool accept_internal()
3547  {
3548  switch (last_token)
3549  {
3550  case token_type::begin_object:
3551  {
3552  // read next token
3553  get_token();
3554 
3555  // closing } -> we are done
3556  if (last_token == token_type::end_object)
3557  {
3558  return true;
3559  }
3560 
3561  // parse values
3562  while (true)
3563  {
3564  // parse key
3565  if (last_token != token_type::value_string)
3566  {
3567  return false;
3568  }
3569 
3570  // parse separator (:)
3571  get_token();
3572  if (last_token != token_type::name_separator)
3573  {
3574  return false;
3575  }
3576 
3577  // parse value
3578  get_token();
3579  if (not accept_internal())
3580  {
3581  return false;
3582  }
3583 
3584  // comma -> next value
3585  get_token();
3586  if (last_token == token_type::value_separator)
3587  {
3588  get_token();
3589  continue;
3590  }
3591 
3592  // closing }
3593  return (last_token == token_type::end_object);
3594  }
3595  }
3596 
3597  case token_type::begin_array:
3598  {
3599  // read next token
3600  get_token();
3601 
3602  // closing ] -> we are done
3603  if (last_token == token_type::end_array)
3604  {
3605  return true;
3606  }
3607 
3608  // parse values
3609  while (true)
3610  {
3611  // parse value
3612  if (not accept_internal())
3613  {
3614  return false;
3615  }
3616 
3617  // comma -> next value
3618  get_token();
3619  if (last_token == token_type::value_separator)
3620  {
3621  get_token();
3622  continue;
3623  }
3624 
3625  // closing ]
3626  return (last_token == token_type::end_array);
3627  }
3628  }
3629 
3630  case token_type::value_float:
3631  {
3632  // reject infinity or NAN
3633  return std::isfinite(m_lexer.get_number_float());
3634  }
3635 
3636  case token_type::literal_false:
3637  case token_type::literal_null:
3638  case token_type::literal_true:
3639  case token_type::value_integer:
3640  case token_type::value_string:
3641  case token_type::value_unsigned:
3642  return true;
3643 
3644  default: // the last token was unexpected
3645  return false;
3646  }
3647  }
3648 
3650  token_type get_token()
3651  {
3652  return (last_token = m_lexer.scan());
3653  }
3654 
3658  bool expect(token_type t)
3659  {
3660  if (JSON_UNLIKELY(t != last_token))
3661  {
3662  errored = true;
3663  expected = t;
3664  if (allow_exceptions)
3665  {
3666  throw_exception();
3667  }
3668  else
3669  {
3670  return false;
3671  }
3672  }
3673 
3674  return true;
3675  }
3676 
3677  [[noreturn]] void throw_exception() const
3678  {
3679  std::string error_msg = "syntax error - ";
3680  if (last_token == token_type::parse_error)
3681  {
3682  error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
3683  m_lexer.get_token_string() + "'";
3684  }
3685  else
3686  {
3687  error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
3688  }
3689 
3690  if (expected != token_type::uninitialized)
3691  {
3692  error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
3693  }
3694 
3695  JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg));
3696  }
3697 
3698  private:
3700  int depth = 0;
3702  const parser_callback_t callback = nullptr;
3704  token_type last_token = token_type::uninitialized;
3706  lexer_t m_lexer;
3708  bool errored = false;
3710  token_type expected = token_type::uninitialized;
3712  const bool allow_exceptions = true;
3713 };
3714 }
3715 }
3716 
3717 // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
3718 
3719 
3720 #include <cstddef> // ptrdiff_t
3721 #include <limits> // numeric_limits
3722 
3723 namespace nlohmann
3724 {
3725 namespace detail
3726 {
3727 /*
3728 @brief an iterator for primitive JSON types
3729 
3730 This class models an iterator for primitive JSON types (boolean, number,
3731 string). It's only purpose is to allow the iterator/const_iterator classes
3732 to "iterate" over primitive values. Internally, the iterator is modeled by
3733 a `difference_type` variable. Value begin_value (`0`) models the begin,
3734 end_value (`1`) models past the end.
3735 */
3737 {
3738  private:
3739  using difference_type = std::ptrdiff_t;
3740  static constexpr difference_type begin_value = 0;
3741  static constexpr difference_type end_value = begin_value + 1;
3742 
3744  difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
3745 
3746  public:
3747  constexpr difference_type get_value() const noexcept
3748  {
3749  return m_it;
3750  }
3751 
3753  void set_begin() noexcept
3754  {
3755  m_it = begin_value;
3756  }
3757 
3759  void set_end() noexcept
3760  {
3761  m_it = end_value;
3762  }
3763 
3765  constexpr bool is_begin() const noexcept
3766  {
3767  return m_it == begin_value;
3768  }
3769 
3771  constexpr bool is_end() const noexcept
3772  {
3773  return m_it == end_value;
3774  }
3775 
3776  friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3777  {
3778  return lhs.m_it == rhs.m_it;
3779  }
3780 
3781  friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3782  {
3783  return lhs.m_it < rhs.m_it;
3784  }
3785 
3786  primitive_iterator_t operator+(difference_type n) noexcept
3787  {
3788  auto result = *this;
3789  result += n;
3790  return result;
3791  }
3792 
3793  friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3794  {
3795  return lhs.m_it - rhs.m_it;
3796  }
3797 
3798  primitive_iterator_t& operator++() noexcept
3799  {
3800  ++m_it;
3801  return *this;
3802  }
3803 
3804  primitive_iterator_t const operator++(int) noexcept
3805  {
3806  auto result = *this;
3807  m_it++;
3808  return result;
3809  }
3810 
3811  primitive_iterator_t& operator--() noexcept
3812  {
3813  --m_it;
3814  return *this;
3815  }
3816 
3817  primitive_iterator_t const operator--(int) noexcept
3818  {
3819  auto result = *this;
3820  m_it--;
3821  return result;
3822  }
3823 
3824  primitive_iterator_t& operator+=(difference_type n) noexcept
3825  {
3826  m_it += n;
3827  return *this;
3828  }
3829 
3830  primitive_iterator_t& operator-=(difference_type n) noexcept
3831  {
3832  m_it -= n;
3833  return *this;
3834  }
3835 };
3836 }
3837 }
3838 
3839 // #include <nlohmann/detail/iterators/internal_iterator.hpp>
3840 
3841 
3842 // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
3843 
3844 
3845 namespace nlohmann
3846 {
3847 namespace detail
3848 {
3855 template<typename BasicJsonType> struct internal_iterator
3856 {
3858  typename BasicJsonType::object_t::iterator object_iterator {};
3860  typename BasicJsonType::array_t::iterator array_iterator {};
3862  primitive_iterator_t primitive_iterator {};
3863 };
3864 }
3865 }
3866 
3867 // #include <nlohmann/detail/iterators/iter_impl.hpp>
3868 
3869 
3870 #include <ciso646> // not
3871 #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
3872 #include <type_traits> // conditional, is_const, remove_const
3873 
3874 // #include <nlohmann/detail/exceptions.hpp>
3875 
3876 // #include <nlohmann/detail/iterators/internal_iterator.hpp>
3877 
3878 // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
3879 
3880 // #include <nlohmann/detail/macro_scope.hpp>
3881 
3882 // #include <nlohmann/detail/meta.hpp>
3883 
3884 // #include <nlohmann/detail/value_t.hpp>
3885 
3886 
3887 namespace nlohmann
3888 {
3889 namespace detail
3890 {
3891 // forward declare, to be able to friend it later on
3892 template<typename IteratorType> class iteration_proxy;
3893 
3914 template<typename BasicJsonType>
3916 {
3918  friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
3919  friend BasicJsonType;
3921 
3922  using object_t = typename BasicJsonType::object_t;
3923  using array_t = typename BasicJsonType::array_t;
3924  // make sure BasicJsonType is basic_json or const basic_json
3925  static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
3926  "iter_impl only accepts (const) basic_json");
3927 
3928  public:
3929 
3935  using iterator_category = std::bidirectional_iterator_tag;
3936 
3938  using value_type = typename BasicJsonType::value_type;
3940  using difference_type = typename BasicJsonType::difference_type;
3942  using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
3943  typename BasicJsonType::const_pointer,
3944  typename BasicJsonType::pointer>::type;
3946  using reference =
3947  typename std::conditional<std::is_const<BasicJsonType>::value,
3948  typename BasicJsonType::const_reference,
3949  typename BasicJsonType::reference>::type;
3950 
3952  iter_impl() = default;
3953 
3960  explicit iter_impl(pointer object) noexcept : m_object(object)
3961  {
3962  assert(m_object != nullptr);
3963 
3964  switch (m_object->m_type)
3965  {
3966  case value_t::object:
3967  {
3968  m_it.object_iterator = typename object_t::iterator();
3969  break;
3970  }
3971 
3972  case value_t::array:
3973  {
3974  m_it.array_iterator = typename array_t::iterator();
3975  break;
3976  }
3977 
3978  default:
3979  {
3980  m_it.primitive_iterator = primitive_iterator_t();
3981  break;
3982  }
3983  }
3984  }
3985 
4000  iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
4001  : m_object(other.m_object), m_it(other.m_it) {}
4002 
4009  iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
4010  {
4011  m_object = other.m_object;
4012  m_it = other.m_it;
4013  return *this;
4014  }
4015 
4016  private:
4021  void set_begin() noexcept
4022  {
4023  assert(m_object != nullptr);
4024 
4025  switch (m_object->m_type)
4026  {
4027  case value_t::object:
4028  {
4029  m_it.object_iterator = m_object->m_value.object->begin();
4030  break;
4031  }
4032 
4033  case value_t::array:
4034  {
4035  m_it.array_iterator = m_object->m_value.array->begin();
4036  break;
4037  }
4038 
4039  case value_t::null:
4040  {
4041  // set to end so begin()==end() is true: null is empty
4042  m_it.primitive_iterator.set_end();
4043  break;
4044  }
4045 
4046  default:
4047  {
4048  m_it.primitive_iterator.set_begin();
4049  break;
4050  }
4051  }
4052  }
4053 
4058  void set_end() noexcept
4059  {
4060  assert(m_object != nullptr);
4061 
4062  switch (m_object->m_type)
4063  {
4064  case value_t::object:
4065  {
4066  m_it.object_iterator = m_object->m_value.object->end();
4067  break;
4068  }
4069 
4070  case value_t::array:
4071  {
4072  m_it.array_iterator = m_object->m_value.array->end();
4073  break;
4074  }
4075 
4076  default:
4077  {
4078  m_it.primitive_iterator.set_end();
4079  break;
4080  }
4081  }
4082  }
4083 
4084  public:
4090  {
4091  assert(m_object != nullptr);
4092 
4093  switch (m_object->m_type)
4094  {
4095  case value_t::object:
4096  {
4097  assert(m_it.object_iterator != m_object->m_value.object->end());
4098  return m_it.object_iterator->second;
4099  }
4100 
4101  case value_t::array:
4102  {
4103  assert(m_it.array_iterator != m_object->m_value.array->end());
4104  return *m_it.array_iterator;
4105  }
4106 
4107  case value_t::null:
4108  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4109 
4110  default:
4111  {
4112  if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
4113  {
4114  return *m_object;
4115  }
4116 
4117  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4118  }
4119  }
4120  }
4121 
4127  {
4128  assert(m_object != nullptr);
4129 
4130  switch (m_object->m_type)
4131  {
4132  case value_t::object:
4133  {
4134  assert(m_it.object_iterator != m_object->m_value.object->end());
4135  return &(m_it.object_iterator->second);
4136  }
4137 
4138  case value_t::array:
4139  {
4140  assert(m_it.array_iterator != m_object->m_value.array->end());
4141  return &*m_it.array_iterator;
4142  }
4143 
4144  default:
4145  {
4146  if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
4147  {
4148  return m_object;
4149  }
4150 
4151  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4152  }
4153  }
4154  }
4155 
4161  {
4162  auto result = *this;
4163  ++(*this);
4164  return result;
4165  }
4166 
4172  {
4173  assert(m_object != nullptr);
4174 
4175  switch (m_object->m_type)
4176  {
4177  case value_t::object:
4178  {
4179  std::advance(m_it.object_iterator, 1);
4180  break;
4181  }
4182 
4183  case value_t::array:
4184  {
4185  std::advance(m_it.array_iterator, 1);
4186  break;
4187  }
4188 
4189  default:
4190  {
4191  ++m_it.primitive_iterator;
4192  break;
4193  }
4194  }
4195 
4196  return *this;
4197  }
4198 
4204  {
4205  auto result = *this;
4206  --(*this);
4207  return result;
4208  }
4209 
4215  {
4216  assert(m_object != nullptr);
4217 
4218  switch (m_object->m_type)
4219  {
4220  case value_t::object:
4221  {
4222  std::advance(m_it.object_iterator, -1);
4223  break;
4224  }
4225 
4226  case value_t::array:
4227  {
4228  std::advance(m_it.array_iterator, -1);
4229  break;
4230  }
4231 
4232  default:
4233  {
4234  --m_it.primitive_iterator;
4235  break;
4236  }
4237  }
4238 
4239  return *this;
4240  }
4241 
4246  bool operator==(const iter_impl& other) const
4247  {
4248  // if objects are not the same, the comparison is undefined
4249  if (JSON_UNLIKELY(m_object != other.m_object))
4250  {
4251  JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
4252  }
4253 
4254  assert(m_object != nullptr);
4255 
4256  switch (m_object->m_type)
4257  {
4258  case value_t::object:
4259  return (m_it.object_iterator == other.m_it.object_iterator);
4260 
4261  case value_t::array:
4262  return (m_it.array_iterator == other.m_it.array_iterator);
4263 
4264  default:
4265  return (m_it.primitive_iterator == other.m_it.primitive_iterator);
4266  }
4267  }
4268 
4273  bool operator!=(const iter_impl& other) const
4274  {
4275  return not operator==(other);
4276  }
4277 
4282  bool operator<(const iter_impl& other) const
4283  {
4284  // if objects are not the same, the comparison is undefined
4285  if (JSON_UNLIKELY(m_object != other.m_object))
4286  {
4287  JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
4288  }
4289 
4290  assert(m_object != nullptr);
4291 
4292  switch (m_object->m_type)
4293  {
4294  case value_t::object:
4295  JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
4296 
4297  case value_t::array:
4298  return (m_it.array_iterator < other.m_it.array_iterator);
4299 
4300  default:
4301  return (m_it.primitive_iterator < other.m_it.primitive_iterator);
4302  }
4303  }
4304 
4309  bool operator<=(const iter_impl& other) const
4310  {
4311  return not other.operator < (*this);
4312  }
4313 
4318  bool operator>(const iter_impl& other) const
4319  {
4320  return not operator<=(other);
4321  }
4322 
4327  bool operator>=(const iter_impl& other) const
4328  {
4329  return not operator<(other);
4330  }
4331 
4337  {
4338  assert(m_object != nullptr);
4339 
4340  switch (m_object->m_type)
4341  {
4342  case value_t::object:
4343  JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
4344 
4345  case value_t::array:
4346  {
4347  std::advance(m_it.array_iterator, i);
4348  break;
4349  }
4350 
4351  default:
4352  {
4353  m_it.primitive_iterator += i;
4354  break;
4355  }
4356  }
4357 
4358  return *this;
4359  }
4360 
4366  {
4367  return operator+=(-i);
4368  }
4369 
4375  {
4376  auto result = *this;
4377  result += i;
4378  return result;
4379  }
4380 
4386  {
4387  auto result = it;
4388  result += i;
4389  return result;
4390  }
4391 
4397  {
4398  auto result = *this;
4399  result -= i;
4400  return result;
4401  }
4402 
4408  {
4409  assert(m_object != nullptr);
4410 
4411  switch (m_object->m_type)
4412  {
4413  case value_t::object:
4414  JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
4415 
4416  case value_t::array:
4417  return m_it.array_iterator - other.m_it.array_iterator;
4418 
4419  default:
4420  return m_it.primitive_iterator - other.m_it.primitive_iterator;
4421  }
4422  }
4423 
4429  {
4430  assert(m_object != nullptr);
4431 
4432  switch (m_object->m_type)
4433  {
4434  case value_t::object:
4435  JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
4436 
4437  case value_t::array:
4438  return *std::next(m_it.array_iterator, n);
4439 
4440  case value_t::null:
4441  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4442 
4443  default:
4444  {
4445  if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
4446  {
4447  return *m_object;
4448  }
4449 
4450  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4451  }
4452  }
4453  }
4454 
4459  typename object_t::key_type key() const
4460  {
4461  assert(m_object != nullptr);
4462 
4463  if (JSON_LIKELY(m_object->is_object()))
4464  {
4465  return m_it.object_iterator->first;
4466  }
4467 
4468  JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
4469  }
4470 
4476  {
4477  return operator*();
4478  }
4479 
4480  private:
4482  pointer m_object = nullptr;
4485 };
4486 }
4487 }
4488 
4489 // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
4490 
4491 
4492 #include <cstddef> // size_t
4493 #include <string> // string, to_string
4494 
4495 // #include <nlohmann/detail/value_t.hpp>
4496 
4497 
4498 namespace nlohmann
4499 {
4500 namespace detail
4501 {
4503 template<typename IteratorType> class iteration_proxy
4504 {
4505  private:
4507  class iteration_proxy_internal
4508  {
4509  private:
4511  IteratorType anchor;
4513  std::size_t array_index = 0;
4514 
4515  public:
4516  explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {}
4517 
4519  iteration_proxy_internal& operator*()
4520  {
4521  return *this;
4522  }
4523 
4525  iteration_proxy_internal& operator++()
4526  {
4527  ++anchor;
4528  ++array_index;
4529 
4530  return *this;
4531  }
4532 
4534  bool operator!=(const iteration_proxy_internal& o) const noexcept
4535  {
4536  return anchor != o.anchor;
4537  }
4538 
4540  std::string key() const
4541  {
4542  assert(anchor.m_object != nullptr);
4543 
4544  switch (anchor.m_object->type())
4545  {
4546  // use integer array index as key
4547  case value_t::array:
4548  return std::to_string(array_index);
4549 
4550  // use key from the object
4551  case value_t::object:
4552  return anchor.key();
4553 
4554  // use an empty key for all primitive types
4555  default:
4556  return "";
4557  }
4558  }
4559 
4561  typename IteratorType::reference value() const
4562  {
4563  return anchor.value();
4564  }
4565  };
4566 
4568  typename IteratorType::reference container;
4569 
4570  public:
4572  explicit iteration_proxy(typename IteratorType::reference cont) noexcept
4573  : container(cont) {}
4574 
4576  iteration_proxy_internal begin() noexcept
4577  {
4578  return iteration_proxy_internal(container.begin());
4579  }
4580 
4582  iteration_proxy_internal end() noexcept
4583  {
4584  return iteration_proxy_internal(container.end());
4585  }
4586 };
4587 }
4588 }
4589 
4590 // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
4591 
4592 
4593 #include <cstddef> // ptrdiff_t
4594 #include <iterator> // reverse_iterator
4595 #include <utility> // declval
4596 
4597 namespace nlohmann
4598 {
4599 namespace detail
4600 {
4602 // reverse_iterator //
4604 
4623 template<typename Base>
4624 class json_reverse_iterator : public std::reverse_iterator<Base>
4625 {
4626  public:
4627  using difference_type = std::ptrdiff_t;
4629  using base_iterator = std::reverse_iterator<Base>;
4631  using reference = typename Base::reference;
4632 
4634  json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
4635  : base_iterator(it) {}
4636 
4639 
4642  {
4643  return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
4644  }
4645 
4648  {
4649  return static_cast<json_reverse_iterator&>(base_iterator::operator++());
4650  }
4651 
4654  {
4655  return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
4656  }
4657 
4660  {
4661  return static_cast<json_reverse_iterator&>(base_iterator::operator--());
4662  }
4663 
4665  json_reverse_iterator& operator+=(difference_type i)
4666  {
4667  return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
4668  }
4669 
4671  json_reverse_iterator operator+(difference_type i) const
4672  {
4673  return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
4674  }
4675 
4677  json_reverse_iterator operator-(difference_type i) const
4678  {
4679  return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
4680  }
4681 
4683  difference_type operator-(const json_reverse_iterator& other) const
4684  {
4685  return base_iterator(*this) - base_iterator(other);
4686  }
4687 
4689  reference operator[](difference_type n) const
4690  {
4691  return *(this->operator+(n));
4692  }
4693 
4695  auto key() const -> decltype(std::declval<Base>().key())
4696  {
4697  auto it = --this->base();
4698  return it.key();
4699  }
4700 
4703  {
4704  auto it = --this->base();
4705  return it.operator * ();
4706  }
4707 };
4708 }
4709 }
4710 
4711 // #include <nlohmann/detail/output/output_adapters.hpp>
4712 
4713 
4714 #include <algorithm> // copy
4715 #include <cstddef> // size_t
4716 #include <ios> // streamsize
4717 #include <iterator> // back_inserter
4718 #include <memory> // shared_ptr, make_shared
4719 #include <ostream> // basic_ostream
4720 #include <string> // basic_string
4721 #include <vector> // vector
4722 
4723 namespace nlohmann
4724 {
4725 namespace detail
4726 {
4728 template<typename CharType> struct output_adapter_protocol
4729 {
4730  virtual void write_character(CharType c) = 0;
4731  virtual void write_characters(const CharType* s, std::size_t length) = 0;
4732  virtual ~output_adapter_protocol() = default;
4733 };
4734 
4736 template<typename CharType>
4737 using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
4738 
4740 template<typename CharType>
4742 {
4743  public:
4744  explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {}
4745 
4746  void write_character(CharType c) override
4747  {
4748  v.push_back(c);
4749  }
4750 
4751  void write_characters(const CharType* s, std::size_t length) override
4752  {
4753  std::copy(s, s + length, std::back_inserter(v));
4754  }
4755 
4756  private:
4757  std::vector<CharType>& v;
4758 };
4759 
4761 template<typename CharType>
4763 {
4764  public:
4765  explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {}
4766 
4767  void write_character(CharType c) override
4768  {
4769  stream.put(c);
4770  }
4771 
4772  void write_characters(const CharType* s, std::size_t length) override
4773  {
4774  stream.write(s, static_cast<std::streamsize>(length));
4775  }
4776 
4777  private:
4778  std::basic_ostream<CharType>& stream;
4779 };
4780 
4782 template<typename CharType, typename StringType = std::basic_string<CharType>>
4784 {
4785  public:
4786  explicit output_string_adapter(StringType& s) : str(s) {}
4787 
4788  void write_character(CharType c) override
4789  {
4790  str.push_back(c);
4791  }
4792 
4793  void write_characters(const CharType* s, std::size_t length) override
4794  {
4795  str.append(s, length);
4796  }
4797 
4798  private:
4799  StringType& str;
4800 };
4801 
4802 template<typename CharType, typename StringType = std::basic_string<CharType>>
4804 {
4805  public:
4806  output_adapter(std::vector<CharType>& vec)
4807  : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
4808 
4809  output_adapter(std::basic_ostream<CharType>& s)
4810  : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
4811 
4812  output_adapter(StringType& s)
4813  : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
4814 
4815  operator output_adapter_t<CharType>()
4816  {
4817  return oa;
4818  }
4819 
4820  private:
4821  output_adapter_t<CharType> oa = nullptr;
4822 };
4823 }
4824 }
4825 
4826 // #include <nlohmann/detail/input/binary_reader.hpp>
4827 
4828 
4829 #include <algorithm> // generate_n
4830 #include <array> // array
4831 #include <cassert> // assert
4832 #include <cmath> // ldexp
4833 #include <cstddef> // size_t
4834 #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
4835 #include <cstring> // memcpy
4836 #include <iomanip> // setw, setfill
4837 #include <ios> // hex
4838 #include <iterator> // back_inserter
4839 #include <limits> // numeric_limits
4840 #include <sstream> // stringstream
4841 #include <string> // char_traits, string
4842 #include <utility> // make_pair, move
4843 
4844 // #include <nlohmann/detail/input/input_adapters.hpp>
4845 
4846 // #include <nlohmann/detail/exceptions.hpp>
4847 
4848 // #include <nlohmann/detail/macro_scope.hpp>
4849 
4850 // #include <nlohmann/detail/value_t.hpp>
4851 
4852 
4853 namespace nlohmann
4854 {
4855 namespace detail
4856 {
4858 // binary reader //
4860 
4864 template<typename BasicJsonType>
4866 {
4867  using number_integer_t = typename BasicJsonType::number_integer_t;
4868  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
4869  using string_t = typename BasicJsonType::string_t;
4870 
4871  public:
4877  explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
4878  {
4879  assert(ia);
4880  }
4881 
4892  BasicJsonType parse_cbor(const bool strict)
4893  {
4894  const auto res = parse_cbor_internal();
4895  if (strict)
4896  {
4897  get();
4898  expect_eof();
4899  }
4900  return res;
4901  }
4902 
4913  BasicJsonType parse_msgpack(const bool strict)
4914  {
4915  const auto res = parse_msgpack_internal();
4916  if (strict)
4917  {
4918  get();
4919  expect_eof();
4920  }
4921  return res;
4922  }
4923 
4934  BasicJsonType parse_ubjson(const bool strict)
4935  {
4936  const auto res = parse_ubjson_internal();
4937  if (strict)
4938  {
4939  get_ignore_noop();
4940  expect_eof();
4941  }
4942  return res;
4943  }
4944 
4952  static constexpr bool little_endianess(int num = 1) noexcept
4953  {
4954  return (*reinterpret_cast<char*>(&num) == 1);
4955  }
4956 
4957  private:
4963  BasicJsonType parse_cbor_internal(const bool get_char = true)
4964  {
4965  switch (get_char ? get() : current)
4966  {
4967  // EOF
4968  case std::char_traits<char>::eof():
4969  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
4970 
4971  // Integer 0x00..0x17 (0..23)
4972  case 0x00:
4973  case 0x01:
4974  case 0x02:
4975  case 0x03:
4976  case 0x04:
4977  case 0x05:
4978  case 0x06:
4979  case 0x07:
4980  case 0x08:
4981  case 0x09:
4982  case 0x0A:
4983  case 0x0B:
4984  case 0x0C:
4985  case 0x0D:
4986  case 0x0E:
4987  case 0x0F:
4988  case 0x10:
4989  case 0x11:
4990  case 0x12:
4991  case 0x13:
4992  case 0x14:
4993  case 0x15:
4994  case 0x16:
4995  case 0x17:
4996  return static_cast<number_unsigned_t>(current);
4997 
4998  case 0x18: // Unsigned integer (one-byte uint8_t follows)
4999  return get_number<uint8_t>();
5000 
5001  case 0x19: // Unsigned integer (two-byte uint16_t follows)
5002  return get_number<uint16_t>();
5003 
5004  case 0x1A: // Unsigned integer (four-byte uint32_t follows)
5005  return get_number<uint32_t>();
5006 
5007  case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
5008  return get_number<uint64_t>();
5009 
5010  // Negative integer -1-0x00..-1-0x17 (-1..-24)
5011  case 0x20:
5012  case 0x21:
5013  case 0x22:
5014  case 0x23:
5015  case 0x24:
5016  case 0x25:
5017  case 0x26:
5018  case 0x27:
5019  case 0x28:
5020  case 0x29:
5021  case 0x2A:
5022  case 0x2B:
5023  case 0x2C:
5024  case 0x2D:
5025  case 0x2E:
5026  case 0x2F:
5027  case 0x30:
5028  case 0x31:
5029  case 0x32:
5030  case 0x33:
5031  case 0x34:
5032  case 0x35:
5033  case 0x36:
5034  case 0x37:
5035  return static_cast<int8_t>(0x20 - 1 - current);
5036 
5037  case 0x38: // Negative integer (one-byte uint8_t follows)
5038  {
5039  return static_cast<number_integer_t>(-1) - get_number<uint8_t>();
5040  }
5041 
5042  case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
5043  {
5044  return static_cast<number_integer_t>(-1) - get_number<uint16_t>();
5045  }
5046 
5047  case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
5048  {
5049  return static_cast<number_integer_t>(-1) - get_number<uint32_t>();
5050  }
5051 
5052  case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
5053  {
5054  return static_cast<number_integer_t>(-1) -
5055  static_cast<number_integer_t>(get_number<uint64_t>());
5056  }
5057 
5058  // UTF-8 string (0x00..0x17 bytes follow)
5059  case 0x60:
5060  case 0x61:
5061  case 0x62:
5062  case 0x63:
5063  case 0x64:
5064  case 0x65:
5065  case 0x66:
5066  case 0x67:
5067  case 0x68:
5068  case 0x69:
5069  case 0x6A:
5070  case 0x6B:
5071  case 0x6C:
5072  case 0x6D:
5073  case 0x6E:
5074  case 0x6F:
5075  case 0x70:
5076  case 0x71:
5077  case 0x72:
5078  case 0x73:
5079  case 0x74:
5080  case 0x75:
5081  case 0x76:
5082  case 0x77:
5083  case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
5084  case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
5085  case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
5086  case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
5087  case 0x7F: // UTF-8 string (indefinite length)
5088  {
5089  return get_cbor_string();
5090  }
5091 
5092  // array (0x00..0x17 data items follow)
5093  case 0x80:
5094  case 0x81:
5095  case 0x82:
5096  case 0x83:
5097  case 0x84:
5098  case 0x85:
5099  case 0x86:
5100  case 0x87:
5101  case 0x88:
5102  case 0x89:
5103  case 0x8A:
5104  case 0x8B:
5105  case 0x8C:
5106  case 0x8D:
5107  case 0x8E:
5108  case 0x8F:
5109  case 0x90:
5110  case 0x91:
5111  case 0x92:
5112  case 0x93:
5113  case 0x94:
5114  case 0x95:
5115  case 0x96:
5116  case 0x97:
5117  {
5118  return get_cbor_array(current & 0x1F);
5119  }
5120 
5121  case 0x98: // array (one-byte uint8_t for n follows)
5122  {
5123  return get_cbor_array(get_number<uint8_t>());
5124  }
5125 
5126  case 0x99: // array (two-byte uint16_t for n follow)
5127  {
5128  return get_cbor_array(get_number<uint16_t>());
5129  }
5130 
5131  case 0x9A: // array (four-byte uint32_t for n follow)
5132  {
5133  return get_cbor_array(get_number<uint32_t>());
5134  }
5135 
5136  case 0x9B: // array (eight-byte uint64_t for n follow)
5137  {
5138  return get_cbor_array(get_number<uint64_t>());
5139  }
5140 
5141  case 0x9F: // array (indefinite length)
5142  {
5143  BasicJsonType result = value_t::array;
5144  while (get() != 0xFF)
5145  {
5146  result.push_back(parse_cbor_internal(false));
5147  }
5148  return result;
5149  }
5150 
5151  // map (0x00..0x17 pairs of data items follow)
5152  case 0xA0:
5153  case 0xA1:
5154  case 0xA2:
5155  case 0xA3:
5156  case 0xA4:
5157  case 0xA5:
5158  case 0xA6:
5159  case 0xA7:
5160  case 0xA8:
5161  case 0xA9:
5162  case 0xAA:
5163  case 0xAB:
5164  case 0xAC:
5165  case 0xAD:
5166  case 0xAE:
5167  case 0xAF:
5168  case 0xB0:
5169  case 0xB1:
5170  case 0xB2:
5171  case 0xB3:
5172  case 0xB4:
5173  case 0xB5:
5174  case 0xB6:
5175  case 0xB7:
5176  {
5177  return get_cbor_object(current & 0x1F);
5178  }
5179 
5180  case 0xB8: // map (one-byte uint8_t for n follows)
5181  {
5182  return get_cbor_object(get_number<uint8_t>());
5183  }
5184 
5185  case 0xB9: // map (two-byte uint16_t for n follow)
5186  {
5187  return get_cbor_object(get_number<uint16_t>());
5188  }
5189 
5190  case 0xBA: // map (four-byte uint32_t for n follow)
5191  {
5192  return get_cbor_object(get_number<uint32_t>());
5193  }
5194 
5195  case 0xBB: // map (eight-byte uint64_t for n follow)
5196  {
5197  return get_cbor_object(get_number<uint64_t>());
5198  }
5199 
5200  case 0xBF: // map (indefinite length)
5201  {
5202  BasicJsonType result = value_t::object;
5203  while (get() != 0xFF)
5204  {
5205  auto key = get_cbor_string();
5206  result[key] = parse_cbor_internal();
5207  }
5208  return result;
5209  }
5210 
5211  case 0xF4: // false
5212  {
5213  return false;
5214  }
5215 
5216  case 0xF5: // true
5217  {
5218  return true;
5219  }
5220 
5221  case 0xF6: // null
5222  {
5223  return value_t::null;
5224  }
5225 
5226  case 0xF9: // Half-Precision Float (two-byte IEEE 754)
5227  {
5228  const int byte1 = get();
5229  unexpect_eof();
5230  const int byte2 = get();
5231  unexpect_eof();
5232 
5233  // code from RFC 7049, Appendix D, Figure 3:
5234  // As half-precision floating-point numbers were only added
5235  // to IEEE 754 in 2008, today's programming platforms often
5236  // still only have limited support for them. It is very
5237  // easy to include at least decoding support for them even
5238  // without such support. An example of a small decoder for
5239  // half-precision floating-point numbers in the C language
5240  // is shown in Fig. 3.
5241  const int half = (byte1 << 8) + byte2;
5242  const int exp = (half >> 10) & 0x1F;
5243  const int mant = half & 0x3FF;
5244  double val;
5245  if (exp == 0)
5246  {
5247  val = std::ldexp(mant, -24);
5248  }
5249  else if (exp != 31)
5250  {
5251  val = std::ldexp(mant + 1024, exp - 25);
5252  }
5253  else
5254  {
5255  val = (mant == 0) ? std::numeric_limits<double>::infinity()
5256  : std::numeric_limits<double>::quiet_NaN();
5257  }
5258  return (half & 0x8000) != 0 ? -val : val;
5259  }
5260 
5261  case 0xFA: // Single-Precision Float (four-byte IEEE 754)
5262  {
5263  return get_number<float>();
5264  }
5265 
5266  case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
5267  {
5268  return get_number<double>();
5269  }
5270 
5271  default: // anything else (0xFF is handled inside the other types)
5272  {
5273  std::stringstream ss;
5274  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5275  JSON_THROW(parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + ss.str()));
5276  }
5277  }
5278  }
5279 
5280  BasicJsonType parse_msgpack_internal()
5281  {
5282  switch (get())
5283  {
5284  // EOF
5285  case std::char_traits<char>::eof():
5286  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
5287 
5288  // positive fixint
5289  case 0x00:
5290  case 0x01:
5291  case 0x02:
5292  case 0x03:
5293  case 0x04:
5294  case 0x05:
5295  case 0x06:
5296  case 0x07:
5297  case 0x08:
5298  case 0x09:
5299  case 0x0A:
5300  case 0x0B:
5301  case 0x0C:
5302  case 0x0D:
5303  case 0x0E:
5304  case 0x0F:
5305  case 0x10:
5306  case 0x11:
5307  case 0x12:
5308  case 0x13:
5309  case 0x14:
5310  case 0x15:
5311  case 0x16:
5312  case 0x17:
5313  case 0x18:
5314  case 0x19:
5315  case 0x1A:
5316  case 0x1B:
5317  case 0x1C:
5318  case 0x1D:
5319  case 0x1E:
5320  case 0x1F:
5321  case 0x20:
5322  case 0x21:
5323  case 0x22:
5324  case 0x23:
5325  case 0x24:
5326  case 0x25:
5327  case 0x26:
5328  case 0x27:
5329  case 0x28:
5330  case 0x29:
5331  case 0x2A:
5332  case 0x2B:
5333  case 0x2C:
5334  case 0x2D:
5335  case 0x2E:
5336  case 0x2F:
5337  case 0x30:
5338  case 0x31:
5339  case 0x32:
5340  case 0x33:
5341  case 0x34:
5342  case 0x35:
5343  case 0x36:
5344  case 0x37:
5345  case 0x38:
5346  case 0x39:
5347  case 0x3A:
5348  case 0x3B:
5349  case 0x3C:
5350  case 0x3D:
5351  case 0x3E:
5352  case 0x3F:
5353  case 0x40:
5354  case 0x41:
5355  case 0x42:
5356  case 0x43:
5357  case 0x44:
5358  case 0x45:
5359  case 0x46:
5360  case 0x47:
5361  case 0x48:
5362  case 0x49:
5363  case 0x4A:
5364  case 0x4B:
5365  case 0x4C:
5366  case 0x4D:
5367  case 0x4E:
5368  case 0x4F:
5369  case 0x50:
5370  case 0x51:
5371  case 0x52:
5372  case 0x53:
5373  case 0x54:
5374  case 0x55:
5375  case 0x56:
5376  case 0x57:
5377  case 0x58:
5378  case 0x59:
5379  case 0x5A:
5380  case 0x5B:
5381  case 0x5C:
5382  case 0x5D:
5383  case 0x5E:
5384  case 0x5F:
5385  case 0x60:
5386  case 0x61:
5387  case 0x62:
5388  case 0x63:
5389  case 0x64:
5390  case 0x65:
5391  case 0x66:
5392  case 0x67:
5393  case 0x68:
5394  case 0x69:
5395  case 0x6A:
5396  case 0x6B:
5397  case 0x6C:
5398  case 0x6D:
5399  case 0x6E:
5400  case 0x6F:
5401  case 0x70:
5402  case 0x71:
5403  case 0x72:
5404  case 0x73:
5405  case 0x74:
5406  case 0x75:
5407  case 0x76:
5408  case 0x77:
5409  case 0x78:
5410  case 0x79:
5411  case 0x7A:
5412  case 0x7B:
5413  case 0x7C:
5414  case 0x7D:
5415  case 0x7E:
5416  case 0x7F:
5417  return static_cast<number_unsigned_t>(current);
5418 
5419  // fixmap
5420  case 0x80:
5421  case 0x81:
5422  case 0x82:
5423  case 0x83:
5424  case 0x84:
5425  case 0x85:
5426  case 0x86:
5427  case 0x87:
5428  case 0x88:
5429  case 0x89:
5430  case 0x8A:
5431  case 0x8B:
5432  case 0x8C:
5433  case 0x8D:
5434  case 0x8E:
5435  case 0x8F:
5436  {
5437  return get_msgpack_object(current & 0x0F);
5438  }
5439 
5440  // fixarray
5441  case 0x90:
5442  case 0x91:
5443  case 0x92:
5444  case 0x93:
5445  case 0x94:
5446  case 0x95:
5447  case 0x96:
5448  case 0x97:
5449  case 0x98:
5450  case 0x99:
5451  case 0x9A:
5452  case 0x9B:
5453  case 0x9C:
5454  case 0x9D:
5455  case 0x9E:
5456  case 0x9F:
5457  {
5458  return get_msgpack_array(current & 0x0F);
5459  }
5460 
5461  // fixstr
5462  case 0xA0:
5463  case 0xA1:
5464  case 0xA2:
5465  case 0xA3:
5466  case 0xA4:
5467  case 0xA5:
5468  case 0xA6:
5469  case 0xA7:
5470  case 0xA8:
5471  case 0xA9:
5472  case 0xAA:
5473  case 0xAB:
5474  case 0xAC:
5475  case 0xAD:
5476  case 0xAE:
5477  case 0xAF:
5478  case 0xB0:
5479  case 0xB1:
5480  case 0xB2:
5481  case 0xB3:
5482  case 0xB4:
5483  case 0xB5:
5484  case 0xB6:
5485  case 0xB7:
5486  case 0xB8:
5487  case 0xB9:
5488  case 0xBA:
5489  case 0xBB:
5490  case 0xBC:
5491  case 0xBD:
5492  case 0xBE:
5493  case 0xBF:
5494  return get_msgpack_string();
5495 
5496  case 0xC0: // nil
5497  return value_t::null;
5498 
5499  case 0xC2: // false
5500  return false;
5501 
5502  case 0xC3: // true
5503  return true;
5504 
5505  case 0xCA: // float 32
5506  return get_number<float>();
5507 
5508  case 0xCB: // float 64
5509  return get_number<double>();
5510 
5511  case 0xCC: // uint 8
5512  return get_number<uint8_t>();
5513 
5514  case 0xCD: // uint 16
5515  return get_number<uint16_t>();
5516 
5517  case 0xCE: // uint 32
5518  return get_number<uint32_t>();
5519 
5520  case 0xCF: // uint 64
5521  return get_number<uint64_t>();
5522 
5523  case 0xD0: // int 8
5524  return get_number<int8_t>();
5525 
5526  case 0xD1: // int 16
5527  return get_number<int16_t>();
5528 
5529  case 0xD2: // int 32
5530  return get_number<int32_t>();
5531 
5532  case 0xD3: // int 64
5533  return get_number<int64_t>();
5534 
5535  case 0xD9: // str 8
5536  case 0xDA: // str 16
5537  case 0xDB: // str 32
5538  return get_msgpack_string();
5539 
5540  case 0xDC: // array 16
5541  {
5542  return get_msgpack_array(get_number<uint16_t>());
5543  }
5544 
5545  case 0xDD: // array 32
5546  {
5547  return get_msgpack_array(get_number<uint32_t>());
5548  }
5549 
5550  case 0xDE: // map 16
5551  {
5552  return get_msgpack_object(get_number<uint16_t>());
5553  }
5554 
5555  case 0xDF: // map 32
5556  {
5557  return get_msgpack_object(get_number<uint32_t>());
5558  }
5559 
5560  // positive fixint
5561  case 0xE0:
5562  case 0xE1:
5563  case 0xE2:
5564  case 0xE3:
5565  case 0xE4:
5566  case 0xE5:
5567  case 0xE6:
5568  case 0xE7:
5569  case 0xE8:
5570  case 0xE9:
5571  case 0xEA:
5572  case 0xEB:
5573  case 0xEC:
5574  case 0xED:
5575  case 0xEE:
5576  case 0xEF:
5577  case 0xF0:
5578  case 0xF1:
5579  case 0xF2:
5580  case 0xF3:
5581  case 0xF4:
5582  case 0xF5:
5583  case 0xF6:
5584  case 0xF7:
5585  case 0xF8:
5586  case 0xF9:
5587  case 0xFA:
5588  case 0xFB:
5589  case 0xFC:
5590  case 0xFD:
5591  case 0xFE:
5592  case 0xFF:
5593  return static_cast<int8_t>(current);
5594 
5595  default: // anything else
5596  {
5597  std::stringstream ss;
5598  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5599  JSON_THROW(parse_error::create(112, chars_read,
5600  "error reading MessagePack; last byte: 0x" + ss.str()));
5601  }
5602  }
5603  }
5604 
5610  BasicJsonType parse_ubjson_internal(const bool get_char = true)
5611  {
5612  return get_ubjson_value(get_char ? get_ignore_noop() : current);
5613  }
5614 
5624  int get()
5625  {
5626  ++chars_read;
5627  return (current = ia->get_character());
5628  }
5629 
5633  int get_ignore_noop()
5634  {
5635  do
5636  {
5637  get();
5638  }
5639  while (current == 'N');
5640 
5641  return current;
5642  }
5643 
5644  /*
5645  @brief read a number from the input
5646 
5647  @tparam NumberType the type of the number
5648 
5649  @return number of type @a NumberType
5650 
5651  @note This function needs to respect the system's endianess, because
5652  bytes in CBOR and MessagePack are stored in network order (big
5653  endian) and therefore need reordering on little endian systems.
5654 
5655  @throw parse_error.110 if input has less than `sizeof(NumberType)` bytes
5656  */
5657  template<typename NumberType> NumberType get_number()
5658  {
5659  // step 1: read input into array with system's byte order
5660  std::array<uint8_t, sizeof(NumberType)> vec;
5661  for (std::size_t i = 0; i < sizeof(NumberType); ++i)
5662  {
5663  get();
5664  unexpect_eof();
5665 
5666  // reverse byte order prior to conversion if necessary
5667  if (is_little_endian)
5668  {
5669  vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);
5670  }
5671  else
5672  {
5673  vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE
5674  }
5675  }
5676 
5677  // step 2: convert array into number of type T and return
5678  NumberType result;
5679  std::memcpy(&result, vec.data(), sizeof(NumberType));
5680  return result;
5681  }
5682 
5696  template<typename NumberType>
5697  string_t get_string(const NumberType len)
5698  {
5699  string_t result;
5700  std::generate_n(std::back_inserter(result), len, [this]()
5701  {
5702  get();
5703  unexpect_eof();
5704  return static_cast<char>(current);
5705  });
5706  return result;
5707  }
5708 
5721  string_t get_cbor_string()
5722  {
5723  unexpect_eof();
5724 
5725  switch (current)
5726  {
5727  // UTF-8 string (0x00..0x17 bytes follow)
5728  case 0x60:
5729  case 0x61:
5730  case 0x62:
5731  case 0x63:
5732  case 0x64:
5733  case 0x65:
5734  case 0x66:
5735  case 0x67:
5736  case 0x68:
5737  case 0x69:
5738  case 0x6A:
5739  case 0x6B:
5740  case 0x6C:
5741  case 0x6D:
5742  case 0x6E:
5743  case 0x6F:
5744  case 0x70:
5745  case 0x71:
5746  case 0x72:
5747  case 0x73:
5748  case 0x74:
5749  case 0x75:
5750  case 0x76:
5751  case 0x77:
5752  {
5753  return get_string(current & 0x1F);
5754  }
5755 
5756  case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
5757  {
5758  return get_string(get_number<uint8_t>());
5759  }
5760 
5761  case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
5762  {
5763  return get_string(get_number<uint16_t>());
5764  }
5765 
5766  case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
5767  {
5768  return get_string(get_number<uint32_t>());
5769  }
5770 
5771  case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
5772  {
5773  return get_string(get_number<uint64_t>());
5774  }
5775 
5776  case 0x7F: // UTF-8 string (indefinite length)
5777  {
5778  string_t result;
5779  while (get() != 0xFF)
5780  {
5781  result.append(get_cbor_string());
5782  }
5783  return result;
5784  }
5785 
5786  default:
5787  {
5788  std::stringstream ss;
5789  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5790  JSON_THROW(parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + ss.str()));
5791  }
5792  }
5793  }
5794 
5795  template<typename NumberType>
5796  BasicJsonType get_cbor_array(const NumberType len)
5797  {
5798  BasicJsonType result = value_t::array;
5799  std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
5800  {
5801  return parse_cbor_internal();
5802  });
5803  return result;
5804  }
5805 
5806  template<typename NumberType>
5807  BasicJsonType get_cbor_object(const NumberType len)
5808  {
5809  BasicJsonType result = value_t::object;
5810  std::generate_n(std::inserter(*result.m_value.object,
5811  result.m_value.object->end()),
5812  len, [this]()
5813  {
5814  get();
5815  auto key = get_cbor_string();
5816  auto val = parse_cbor_internal();
5817  return std::make_pair(std::move(key), std::move(val));
5818  });
5819  return result;
5820  }
5821 
5833  string_t get_msgpack_string()
5834  {
5835  unexpect_eof();
5836 
5837  switch (current)
5838  {
5839  // fixstr
5840  case 0xA0:
5841  case 0xA1:
5842  case 0xA2:
5843  case 0xA3:
5844  case 0xA4:
5845  case 0xA5:
5846  case 0xA6:
5847  case 0xA7:
5848  case 0xA8:
5849  case 0xA9:
5850  case 0xAA:
5851  case 0xAB:
5852  case 0xAC:
5853  case 0xAD:
5854  case 0xAE:
5855  case 0xAF:
5856  case 0xB0:
5857  case 0xB1:
5858  case 0xB2:
5859  case 0xB3:
5860  case 0xB4:
5861  case 0xB5:
5862  case 0xB6:
5863  case 0xB7:
5864  case 0xB8:
5865  case 0xB9:
5866  case 0xBA:
5867  case 0xBB:
5868  case 0xBC:
5869  case 0xBD:
5870  case 0xBE:
5871  case 0xBF:
5872  {
5873  return get_string(current & 0x1F);
5874  }
5875 
5876  case 0xD9: // str 8
5877  {
5878  return get_string(get_number<uint8_t>());
5879  }
5880 
5881  case 0xDA: // str 16
5882  {
5883  return get_string(get_number<uint16_t>());
5884  }
5885 
5886  case 0xDB: // str 32
5887  {
5888  return get_string(get_number<uint32_t>());
5889  }
5890 
5891  default:
5892  {
5893  std::stringstream ss;
5894  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5895  JSON_THROW(parse_error::create(113, chars_read,
5896  "expected a MessagePack string; last byte: 0x" + ss.str()));
5897  }
5898  }
5899  }
5900 
5901  template<typename NumberType>
5902  BasicJsonType get_msgpack_array(const NumberType len)
5903  {
5904  BasicJsonType result = value_t::array;
5905  std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
5906  {
5907  return parse_msgpack_internal();
5908  });
5909  return result;
5910  }
5911 
5912  template<typename NumberType>
5913  BasicJsonType get_msgpack_object(const NumberType len)
5914  {
5915  BasicJsonType result = value_t::object;
5916  std::generate_n(std::inserter(*result.m_value.object,
5917  result.m_value.object->end()),
5918  len, [this]()
5919  {
5920  get();
5921  auto key = get_msgpack_string();
5922  auto val = parse_msgpack_internal();
5923  return std::make_pair(std::move(key), std::move(val));
5924  });
5925  return result;
5926  }
5927 
5944  string_t get_ubjson_string(const bool get_char = true)
5945  {
5946  if (get_char)
5947  {
5948  get(); // TODO: may we ignore N here?
5949  }
5950 
5951  unexpect_eof();
5952 
5953  switch (current)
5954  {
5955  case 'U':
5956  return get_string(get_number<uint8_t>());
5957  case 'i':
5958  return get_string(get_number<int8_t>());
5959  case 'I':
5960  return get_string(get_number<int16_t>());
5961  case 'l':
5962  return get_string(get_number<int32_t>());
5963  case 'L':
5964  return get_string(get_number<int64_t>());
5965  default:
5966  std::stringstream ss;
5967  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5968  JSON_THROW(parse_error::create(113, chars_read,
5969  "expected a UBJSON string; last byte: 0x" + ss.str()));
5970  }
5971  }
5972 
5981  std::pair<std::size_t, int> get_ubjson_size_type()
5982  {
5983  std::size_t sz = string_t::npos;
5984  int tc = 0;
5985 
5986  get_ignore_noop();
5987 
5988  if (current == '$')
5989  {
5990  tc = get(); // must not ignore 'N', because 'N' maybe the type
5991  unexpect_eof();
5992 
5993  get_ignore_noop();
5994  if (current != '#')
5995  {
5996  std::stringstream ss;
5997  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5998  JSON_THROW(parse_error::create(112, chars_read,
5999  "expected '#' after UBJSON type information; last byte: 0x" + ss.str()));
6000  }
6001  sz = parse_ubjson_internal();
6002  }
6003  else if (current == '#')
6004  {
6005  sz = parse_ubjson_internal();
6006  }
6007 
6008  return std::make_pair(sz, tc);
6009  }
6010 
6011  BasicJsonType get_ubjson_value(const int prefix)
6012  {
6013  switch (prefix)
6014  {
6015  case std::char_traits<char>::eof(): // EOF
6016  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
6017 
6018  case 'T': // true
6019  return true;
6020  case 'F': // false
6021  return false;
6022 
6023  case 'Z': // null
6024  return nullptr;
6025 
6026  case 'U':
6027  return get_number<uint8_t>();
6028  case 'i':
6029  return get_number<int8_t>();
6030  case 'I':
6031  return get_number<int16_t>();
6032  case 'l':
6033  return get_number<int32_t>();
6034  case 'L':
6035  return get_number<int64_t>();
6036  case 'd':
6037  return get_number<float>();
6038  case 'D':
6039  return get_number<double>();
6040 
6041  case 'C': // char
6042  {
6043  get();
6044  unexpect_eof();
6045  if (JSON_UNLIKELY(current > 127))
6046  {
6047  std::stringstream ss;
6048  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
6049  JSON_THROW(parse_error::create(113, chars_read,
6050  "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + ss.str()));
6051  }
6052  return string_t(1, static_cast<char>(current));
6053  }
6054 
6055  case 'S': // string
6056  return get_ubjson_string();
6057 
6058  case '[': // array
6059  return get_ubjson_array();
6060 
6061  case '{': // object
6062  return get_ubjson_object();
6063 
6064  default: // anything else
6065  std::stringstream ss;
6066  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
6067  JSON_THROW(parse_error::create(112, chars_read,
6068  "error reading UBJSON; last byte: 0x" + ss.str()));
6069  }
6070  }
6071 
6072  BasicJsonType get_ubjson_array()
6073  {
6074  BasicJsonType result = value_t::array;
6075  const auto size_and_type = get_ubjson_size_type();
6076 
6077  if (size_and_type.first != string_t::npos)
6078  {
6079  if (JSON_UNLIKELY(size_and_type.first > result.max_size()))
6080  {
6081  JSON_THROW(out_of_range::create(408,
6082  "excessive array size: " + std::to_string(size_and_type.first)));
6083  }
6084 
6085  if (size_and_type.second != 0)
6086  {
6087  if (size_and_type.second != 'N')
6088  {
6089  std::generate_n(std::back_inserter(*result.m_value.array),
6090  size_and_type.first, [this, size_and_type]()
6091  {
6092  return get_ubjson_value(size_and_type.second);
6093  });
6094  }
6095  }
6096  else
6097  {
6098  std::generate_n(std::back_inserter(*result.m_value.array),
6099  size_and_type.first, [this]()
6100  {
6101  return parse_ubjson_internal();
6102  });
6103  }
6104  }
6105  else
6106  {
6107  while (current != ']')
6108  {
6109  result.push_back(parse_ubjson_internal(false));
6110  get_ignore_noop();
6111  }
6112  }
6113 
6114  return result;
6115  }
6116 
6117  BasicJsonType get_ubjson_object()
6118  {
6119  BasicJsonType result = value_t::object;
6120  const auto size_and_type = get_ubjson_size_type();
6121 
6122  if (size_and_type.first != string_t::npos)
6123  {
6124  if (JSON_UNLIKELY(size_and_type.first > result.max_size()))
6125  {
6126  JSON_THROW(out_of_range::create(408,
6127  "excessive object size: " + std::to_string(size_and_type.first)));
6128  }
6129 
6130  if (size_and_type.second != 0)
6131  {
6132  std::generate_n(std::inserter(*result.m_value.object,
6133  result.m_value.object->end()),
6134  size_and_type.first, [this, size_and_type]()
6135  {
6136  auto key = get_ubjson_string();
6137  auto val = get_ubjson_value(size_and_type.second);
6138  return std::make_pair(std::move(key), std::move(val));
6139  });
6140  }
6141  else
6142  {
6143  std::generate_n(std::inserter(*result.m_value.object,
6144  result.m_value.object->end()),
6145  size_and_type.first, [this]()
6146  {
6147  auto key = get_ubjson_string();
6148  auto val = parse_ubjson_internal();
6149  return std::make_pair(std::move(key), std::move(val));
6150  });
6151  }
6152  }
6153  else
6154  {
6155  while (current != '}')
6156  {
6157  auto key = get_ubjson_string(false);
6158  result[std::move(key)] = parse_ubjson_internal();
6159  get_ignore_noop();
6160  }
6161  }
6162 
6163  return result;
6164  }
6165 
6170  void expect_eof() const
6171  {
6172  if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
6173  {
6174  JSON_THROW(parse_error::create(110, chars_read, "expected end of input"));
6175  }
6176  }
6177 
6182  void unexpect_eof() const
6183  {
6184  if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
6185  {
6186  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
6187  }
6188  }
6189 
6190  private:
6192  input_adapter_t ia = nullptr;
6193 
6195  int current = std::char_traits<char>::eof();
6196 
6198  std::size_t chars_read = 0;
6199 
6201  const bool is_little_endian = little_endianess();
6202 };
6203 }
6204 }
6205 
6206 // #include <nlohmann/detail/output/binary_writer.hpp>
6207 
6208 
6209 #include <algorithm> // reverse
6210 #include <array> // array
6211 #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
6212 #include <cstring> // memcpy
6213 #include <limits> // numeric_limits
6214 
6215 // #include <nlohmann/detail/input/binary_reader.hpp>
6216 
6217 // #include <nlohmann/detail/output/output_adapters.hpp>
6218 
6219 
6220 namespace nlohmann
6221 {
6222 namespace detail
6223 {
6225 // binary writer //
6227 
6231 template<typename BasicJsonType, typename CharType>
6233 {
6234  public:
6240  explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
6241  {
6242  assert(oa);
6243  }
6244 
6248  void write_cbor(const BasicJsonType& j)
6249  {
6250  switch (j.type())
6251  {
6252  case value_t::null:
6253  {
6254  oa->write_character(static_cast<CharType>(0xF6));
6255  break;
6256  }
6257 
6258  case value_t::boolean:
6259  {
6260  oa->write_character(j.m_value.boolean
6261  ? static_cast<CharType>(0xF5)
6262  : static_cast<CharType>(0xF4));
6263  break;
6264  }
6265 
6267  {
6268  if (j.m_value.number_integer >= 0)
6269  {
6270  // CBOR does not differentiate between positive signed
6271  // integers and unsigned integers. Therefore, we used the
6272  // code from the value_t::number_unsigned case here.
6273  if (j.m_value.number_integer <= 0x17)
6274  {
6275  write_number(static_cast<uint8_t>(j.m_value.number_integer));
6276  }
6277  else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
6278  {
6279  oa->write_character(static_cast<CharType>(0x18));
6280  write_number(static_cast<uint8_t>(j.m_value.number_integer));
6281  }
6282  else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
6283  {
6284  oa->write_character(static_cast<CharType>(0x19));
6285  write_number(static_cast<uint16_t>(j.m_value.number_integer));
6286  }
6287  else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
6288  {
6289  oa->write_character(static_cast<CharType>(0x1A));
6290  write_number(static_cast<uint32_t>(j.m_value.number_integer));
6291  }
6292  else
6293  {
6294  oa->write_character(static_cast<CharType>(0x1B));
6295  write_number(static_cast<uint64_t>(j.m_value.number_integer));
6296  }
6297  }
6298  else
6299  {
6300  // The conversions below encode the sign in the first
6301  // byte, and the value is converted to a positive number.
6302  const auto positive_number = -1 - j.m_value.number_integer;
6303  if (j.m_value.number_integer >= -24)
6304  {
6305  write_number(static_cast<uint8_t>(0x20 + positive_number));
6306  }
6307  else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
6308  {
6309  oa->write_character(static_cast<CharType>(0x38));
6310  write_number(static_cast<uint8_t>(positive_number));
6311  }
6312  else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
6313  {
6314  oa->write_character(static_cast<CharType>(0x39));
6315  write_number(static_cast<uint16_t>(positive_number));
6316  }
6317  else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
6318  {
6319  oa->write_character(static_cast<CharType>(0x3A));
6320  write_number(static_cast<uint32_t>(positive_number));
6321  }
6322  else
6323  {
6324  oa->write_character(static_cast<CharType>(0x3B));
6325  write_number(static_cast<uint64_t>(positive_number));
6326  }
6327  }
6328  break;
6329  }
6330 
6332  {
6333  if (j.m_value.number_unsigned <= 0x17)
6334  {
6335  write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
6336  }
6337  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
6338  {
6339  oa->write_character(static_cast<CharType>(0x18));
6340  write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
6341  }
6342  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
6343  {
6344  oa->write_character(static_cast<CharType>(0x19));
6345  write_number(static_cast<uint16_t>(j.m_value.number_unsigned));
6346  }
6347  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
6348  {
6349  oa->write_character(static_cast<CharType>(0x1A));
6350  write_number(static_cast<uint32_t>(j.m_value.number_unsigned));
6351  }
6352  else
6353  {
6354  oa->write_character(static_cast<CharType>(0x1B));
6355  write_number(static_cast<uint64_t>(j.m_value.number_unsigned));
6356  }
6357  break;
6358  }
6359 
6360  case value_t::number_float: // Double-Precision Float
6361  {
6362  oa->write_character(static_cast<CharType>(0xFB));
6363  write_number(j.m_value.number_float);
6364  break;
6365  }
6366 
6367  case value_t::string:
6368  {
6369  // step 1: write control byte and the string length
6370  const auto N = j.m_value.string->size();
6371  if (N <= 0x17)
6372  {
6373  write_number(static_cast<uint8_t>(0x60 + N));
6374  }
6375  else if (N <= (std::numeric_limits<uint8_t>::max)())
6376  {
6377  oa->write_character(static_cast<CharType>(0x78));
6378  write_number(static_cast<uint8_t>(N));
6379  }
6380  else if (N <= (std::numeric_limits<uint16_t>::max)())
6381  {
6382  oa->write_character(static_cast<CharType>(0x79));
6383  write_number(static_cast<uint16_t>(N));
6384  }
6385  else if (N <= (std::numeric_limits<uint32_t>::max)())
6386  {
6387  oa->write_character(static_cast<CharType>(0x7A));
6388  write_number(static_cast<uint32_t>(N));
6389  }
6390  // LCOV_EXCL_START
6391  else if (N <= (std::numeric_limits<uint64_t>::max)())
6392  {
6393  oa->write_character(static_cast<CharType>(0x7B));
6394  write_number(static_cast<uint64_t>(N));
6395  }
6396  // LCOV_EXCL_STOP
6397 
6398  // step 2: write the string
6399  oa->write_characters(
6400  reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
6401  j.m_value.string->size());
6402  break;
6403  }
6404 
6405  case value_t::array:
6406  {
6407  // step 1: write control byte and the array size
6408  const auto N = j.m_value.array->size();
6409  if (N <= 0x17)
6410  {
6411  write_number(static_cast<uint8_t>(0x80 + N));
6412  }
6413  else if (N <= (std::numeric_limits<uint8_t>::max)())
6414  {
6415  oa->write_character(static_cast<CharType>(0x98));
6416  write_number(static_cast<uint8_t>(N));
6417  }
6418  else if (N <= (std::numeric_limits<uint16_t>::max)())
6419  {
6420  oa->write_character(static_cast<CharType>(0x99));
6421  write_number(static_cast<uint16_t>(N));
6422  }
6423  else if (N <= (std::numeric_limits<uint32_t>::max)())
6424  {
6425  oa->write_character(static_cast<CharType>(0x9A));
6426  write_number(static_cast<uint32_t>(N));
6427  }
6428  // LCOV_EXCL_START
6429  else if (N <= (std::numeric_limits<uint64_t>::max)())
6430  {
6431  oa->write_character(static_cast<CharType>(0x9B));
6432  write_number(static_cast<uint64_t>(N));
6433  }
6434  // LCOV_EXCL_STOP
6435 
6436  // step 2: write each element
6437  for (const auto& el : *j.m_value.array)
6438  {
6439  write_cbor(el);
6440  }
6441  break;
6442  }
6443 
6444  case value_t::object:
6445  {
6446  // step 1: write control byte and the object size
6447  const auto N = j.m_value.object->size();
6448  if (N <= 0x17)
6449  {
6450  write_number(static_cast<uint8_t>(0xA0 + N));
6451  }
6452  else if (N <= (std::numeric_limits<uint8_t>::max)())
6453  {
6454  oa->write_character(static_cast<CharType>(0xB8));
6455  write_number(static_cast<uint8_t>(N));
6456  }
6457  else if (N <= (std::numeric_limits<uint16_t>::max)())
6458  {
6459  oa->write_character(static_cast<CharType>(0xB9));
6460  write_number(static_cast<uint16_t>(N));
6461  }
6462  else if (N <= (std::numeric_limits<uint32_t>::max)())
6463  {
6464  oa->write_character(static_cast<CharType>(0xBA));
6465  write_number(static_cast<uint32_t>(N));
6466  }
6467  // LCOV_EXCL_START
6468  else if (N <= (std::numeric_limits<uint64_t>::max)())
6469  {
6470  oa->write_character(static_cast<CharType>(0xBB));
6471  write_number(static_cast<uint64_t>(N));
6472  }
6473  // LCOV_EXCL_STOP
6474 
6475  // step 2: write each element
6476  for (const auto& el : *j.m_value.object)
6477  {
6478  write_cbor(el.first);
6479  write_cbor(el.second);
6480  }
6481  break;
6482  }
6483 
6484  default:
6485  break;
6486  }
6487  }
6488 
6492  void write_msgpack(const BasicJsonType& j)
6493  {
6494  switch (j.type())
6495  {
6496  case value_t::null: // nil
6497  {
6498  oa->write_character(static_cast<CharType>(0xC0));
6499  break;
6500  }
6501 
6502  case value_t::boolean: // true and false
6503  {
6504  oa->write_character(j.m_value.boolean
6505  ? static_cast<CharType>(0xC3)
6506  : static_cast<CharType>(0xC2));
6507  break;
6508  }
6509 
6511  {
6512  if (j.m_value.number_integer >= 0)
6513  {
6514  // MessagePack does not differentiate between positive
6515  // signed integers and unsigned integers. Therefore, we used
6516  // the code from the value_t::number_unsigned case here.
6517  if (j.m_value.number_unsigned < 128)
6518  {
6519  // positive fixnum
6520  write_number(static_cast<uint8_t>(j.m_value.number_integer));
6521  }
6522  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
6523  {
6524  // uint 8
6525  oa->write_character(static_cast<CharType>(0xCC));
6526  write_number(static_cast<uint8_t>(j.m_value.number_integer));
6527  }
6528  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
6529  {
6530  // uint 16
6531  oa->write_character(static_cast<CharType>(0xCD));
6532  write_number(static_cast<uint16_t>(j.m_value.number_integer));
6533  }
6534  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
6535  {
6536  // uint 32
6537  oa->write_character(static_cast<CharType>(0xCE));
6538  write_number(static_cast<uint32_t>(j.m_value.number_integer));
6539  }
6540  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
6541  {
6542  // uint 64
6543  oa->write_character(static_cast<CharType>(0xCF));
6544  write_number(static_cast<uint64_t>(j.m_value.number_integer));
6545  }
6546  }
6547  else
6548  {
6549  if (j.m_value.number_integer >= -32)
6550  {
6551  // negative fixnum
6552  write_number(static_cast<int8_t>(j.m_value.number_integer));
6553  }
6554  else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and
6555  j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
6556  {
6557  // int 8
6558  oa->write_character(static_cast<CharType>(0xD0));
6559  write_number(static_cast<int8_t>(j.m_value.number_integer));
6560  }
6561  else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and
6562  j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
6563  {
6564  // int 16
6565  oa->write_character(static_cast<CharType>(0xD1));
6566  write_number(static_cast<int16_t>(j.m_value.number_integer));
6567  }
6568  else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and
6569  j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
6570  {
6571  // int 32
6572  oa->write_character(static_cast<CharType>(0xD2));
6573  write_number(static_cast<int32_t>(j.m_value.number_integer));
6574  }
6575  else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and
6576  j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
6577  {
6578  // int 64
6579  oa->write_character(static_cast<CharType>(0xD3));
6580  write_number(static_cast<int64_t>(j.m_value.number_integer));
6581  }
6582  }
6583  break;
6584  }
6585 
6587  {
6588  if (j.m_value.number_unsigned < 128)
6589  {
6590  // positive fixnum
6591  write_number(static_cast<uint8_t>(j.m_value.number_integer));
6592  }
6593  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
6594  {
6595  // uint 8
6596  oa->write_character(static_cast<CharType>(0xCC));
6597  write_number(static_cast<uint8_t>(j.m_value.number_integer));
6598  }
6599  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
6600  {
6601  // uint 16
6602  oa->write_character(static_cast<CharType>(0xCD));
6603  write_number(static_cast<uint16_t>(j.m_value.number_integer));
6604  }
6605  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
6606  {
6607  // uint 32
6608  oa->write_character(static_cast<CharType>(0xCE));
6609  write_number(static_cast<uint32_t>(j.m_value.number_integer));
6610  }
6611  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
6612  {
6613  // uint 64
6614  oa->write_character(static_cast<CharType>(0xCF));
6615  write_number(static_cast<uint64_t>(j.m_value.number_integer));
6616  }
6617  break;
6618  }
6619 
6620  case value_t::number_float: // float 64
6621  {
6622  oa->write_character(static_cast<CharType>(0xCB));
6623  write_number(j.m_value.number_float);
6624  break;
6625  }
6626 
6627  case value_t::string:
6628  {
6629  // step 1: write control byte and the string length
6630  const auto N = j.m_value.string->size();
6631  if (N <= 31)
6632  {
6633  // fixstr
6634  write_number(static_cast<uint8_t>(0xA0 | N));
6635  }
6636  else if (N <= (std::numeric_limits<uint8_t>::max)())
6637  {
6638  // str 8
6639  oa->write_character(static_cast<CharType>(0xD9));
6640  write_number(static_cast<uint8_t>(N));
6641  }
6642  else if (N <= (std::numeric_limits<uint16_t>::max)())
6643  {
6644  // str 16
6645  oa->write_character(static_cast<CharType>(0xDA));
6646  write_number(static_cast<uint16_t>(N));
6647  }
6648  else if (N <= (std::numeric_limits<uint32_t>::max)())
6649  {
6650  // str 32
6651  oa->write_character(static_cast<CharType>(0xDB));
6652  write_number(static_cast<uint32_t>(N));
6653  }
6654 
6655  // step 2: write the string
6656  oa->write_characters(
6657  reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
6658  j.m_value.string->size());
6659  break;
6660  }
6661 
6662  case value_t::array:
6663  {
6664  // step 1: write control byte and the array size
6665  const auto N = j.m_value.array->size();
6666  if (N <= 15)
6667  {
6668  // fixarray
6669  write_number(static_cast<uint8_t>(0x90 | N));
6670  }
6671  else if (N <= (std::numeric_limits<uint16_t>::max)())
6672  {
6673  // array 16
6674  oa->write_character(static_cast<CharType>(0xDC));
6675  write_number(static_cast<uint16_t>(N));
6676  }
6677  else if (N <= (std::numeric_limits<uint32_t>::max)())
6678  {
6679  // array 32
6680  oa->write_character(static_cast<CharType>(0xDD));
6681  write_number(static_cast<uint32_t>(N));
6682  }
6683 
6684  // step 2: write each element
6685  for (const auto& el : *j.m_value.array)
6686  {
6687  write_msgpack(el);
6688  }
6689  break;
6690  }
6691 
6692  case value_t::object:
6693  {
6694  // step 1: write control byte and the object size
6695  const auto N = j.m_value.object->size();
6696  if (N <= 15)
6697  {
6698  // fixmap
6699  write_number(static_cast<uint8_t>(0x80 | (N & 0xF)));
6700  }
6701  else if (N <= (std::numeric_limits<uint16_t>::max)())
6702  {
6703  // map 16
6704  oa->write_character(static_cast<CharType>(0xDE));
6705  write_number(static_cast<uint16_t>(N));
6706  }
6707  else if (N <= (std::numeric_limits<uint32_t>::max)())
6708  {
6709  // map 32
6710  oa->write_character(static_cast<CharType>(0xDF));
6711  write_number(static_cast<uint32_t>(N));
6712  }
6713 
6714  // step 2: write each element
6715  for (const auto& el : *j.m_value.object)
6716  {
6717  write_msgpack(el.first);
6718  write_msgpack(el.second);
6719  }
6720  break;
6721  }
6722 
6723  default:
6724  break;
6725  }
6726  }
6727 
6734  void write_ubjson(const BasicJsonType& j, const bool use_count,
6735  const bool use_type, const bool add_prefix = true)
6736  {
6737  switch (j.type())
6738  {
6739  case value_t::null:
6740  {
6741  if (add_prefix)
6742  {
6743  oa->write_character(static_cast<CharType>('Z'));
6744  }
6745  break;
6746  }
6747 
6748  case value_t::boolean:
6749  {
6750  if (add_prefix)
6751  oa->write_character(j.m_value.boolean
6752  ? static_cast<CharType>('T')
6753  : static_cast<CharType>('F'));
6754  break;
6755  }
6756 
6758  {
6759  write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
6760  break;
6761  }
6762 
6764  {
6765  write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
6766  break;
6767  }
6768 
6769  case value_t::number_float:
6770  {
6771  write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
6772  break;
6773  }
6774 
6775  case value_t::string:
6776  {
6777  if (add_prefix)
6778  {
6779  oa->write_character(static_cast<CharType>('S'));
6780  }
6781  write_number_with_ubjson_prefix(j.m_value.string->size(), true);
6782  oa->write_characters(
6783  reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
6784  j.m_value.string->size());
6785  break;
6786  }
6787 
6788  case value_t::array:
6789  {
6790  if (add_prefix)
6791  {
6792  oa->write_character(static_cast<CharType>('['));
6793  }
6794 
6795  bool prefix_required = true;
6796  if (use_type and not j.m_value.array->empty())
6797  {
6798  assert(use_count);
6799  const char first_prefix = ubjson_prefix(j.front());
6800  const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
6801  [this, first_prefix](const BasicJsonType & v)
6802  {
6803  return ubjson_prefix(v) == first_prefix;
6804  });
6805 
6806  if (same_prefix)
6807  {
6808  prefix_required = false;
6809  oa->write_character(static_cast<CharType>('$'));
6810  oa->write_character(static_cast<CharType>(first_prefix));
6811  }
6812  }
6813 
6814  if (use_count)
6815  {
6816  oa->write_character(static_cast<CharType>('#'));
6817  write_number_with_ubjson_prefix(j.m_value.array->size(), true);
6818  }
6819 
6820  for (const auto& el : *j.m_value.array)
6821  {
6822  write_ubjson(el, use_count, use_type, prefix_required);
6823  }
6824 
6825  if (not use_count)
6826  {
6827  oa->write_character(static_cast<CharType>(']'));
6828  }
6829 
6830  break;
6831  }
6832 
6833  case value_t::object:
6834  {
6835  if (add_prefix)
6836  {
6837  oa->write_character(static_cast<CharType>('{'));
6838  }
6839 
6840  bool prefix_required = true;
6841  if (use_type and not j.m_value.object->empty())
6842  {
6843  assert(use_count);
6844  const char first_prefix = ubjson_prefix(j.front());
6845  const bool same_prefix = std::all_of(j.begin(), j.end(),
6846  [this, first_prefix](const BasicJsonType & v)
6847  {
6848  return ubjson_prefix(v) == first_prefix;
6849  });
6850 
6851  if (same_prefix)
6852  {
6853  prefix_required = false;
6854  oa->write_character(static_cast<CharType>('$'));
6855  oa->write_character(static_cast<CharType>(first_prefix));
6856  }
6857  }
6858 
6859  if (use_count)
6860  {
6861  oa->write_character(static_cast<CharType>('#'));
6862  write_number_with_ubjson_prefix(j.m_value.object->size(), true);
6863  }
6864 
6865  for (const auto& el : *j.m_value.object)
6866  {
6867  write_number_with_ubjson_prefix(el.first.size(), true);
6868  oa->write_characters(
6869  reinterpret_cast<const CharType*>(el.first.c_str()),
6870  el.first.size());
6871  write_ubjson(el.second, use_count, use_type, prefix_required);
6872  }
6873 
6874  if (not use_count)
6875  {
6876  oa->write_character(static_cast<CharType>('}'));
6877  }
6878 
6879  break;
6880  }
6881 
6882  default:
6883  break;
6884  }
6885  }
6886 
6887  private:
6888  /*
6889  @brief write a number to output input
6890 
6891  @param[in] n number of type @a NumberType
6892  @tparam NumberType the type of the number
6893 
6894  @note This function needs to respect the system's endianess, because bytes
6895  in CBOR, MessagePack, and UBJSON are stored in network order (big
6896  endian) and therefore need reordering on little endian systems.
6897  */
6898  template<typename NumberType>
6899  void write_number(const NumberType n)
6900  {
6901  // step 1: write number to array of length NumberType
6902  std::array<CharType, sizeof(NumberType)> vec;
6903  std::memcpy(vec.data(), &n, sizeof(NumberType));
6904 
6905  // step 2: write array to output (with possible reordering)
6906  if (is_little_endian)
6907  {
6908  // reverse byte order prior to conversion if necessary
6909  std::reverse(vec.begin(), vec.end());
6910  }
6911 
6912  oa->write_characters(vec.data(), sizeof(NumberType));
6913  }
6914 
6915  // UBJSON: write number (floating point)
6916  template<typename NumberType, typename std::enable_if<
6917  std::is_floating_point<NumberType>::value, int>::type = 0>
6918  void write_number_with_ubjson_prefix(const NumberType n,
6919  const bool add_prefix)
6920  {
6921  if (add_prefix)
6922  {
6923  oa->write_character(static_cast<CharType>('D')); // float64
6924  }
6925  write_number(n);
6926  }
6927 
6928  // UBJSON: write number (unsigned integer)
6929  template<typename NumberType, typename std::enable_if<
6930  std::is_unsigned<NumberType>::value, int>::type = 0>
6931  void write_number_with_ubjson_prefix(const NumberType n,
6932  const bool add_prefix)
6933  {
6934  if (n <= static_cast<uint64_t>((std::numeric_limits<int8_t>::max)()))
6935  {
6936  if (add_prefix)
6937  {
6938  oa->write_character(static_cast<CharType>('i')); // int8
6939  }
6940  write_number(static_cast<uint8_t>(n));
6941  }
6942  else if (n <= (std::numeric_limits<uint8_t>::max)())
6943  {
6944  if (add_prefix)
6945  {
6946  oa->write_character(static_cast<CharType>('U')); // uint8
6947  }
6948  write_number(static_cast<uint8_t>(n));
6949  }
6950  else if (n <= static_cast<uint64_t>((std::numeric_limits<int16_t>::max)()))
6951  {
6952  if (add_prefix)
6953  {
6954  oa->write_character(static_cast<CharType>('I')); // int16
6955  }
6956  write_number(static_cast<int16_t>(n));
6957  }
6958  else if (n <= static_cast<uint64_t>((std::numeric_limits<int32_t>::max)()))
6959  {
6960  if (add_prefix)
6961  {
6962  oa->write_character(static_cast<CharType>('l')); // int32
6963  }
6964  write_number(static_cast<int32_t>(n));
6965  }
6966  else if (n <= static_cast<uint64_t>((std::numeric_limits<int64_t>::max)()))
6967  {
6968  if (add_prefix)
6969  {
6970  oa->write_character(static_cast<CharType>('L')); // int64
6971  }
6972  write_number(static_cast<int64_t>(n));
6973  }
6974  else
6975  {
6976  JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n)));
6977  }
6978  }
6979 
6980  // UBJSON: write number (signed integer)
6981  template<typename NumberType, typename std::enable_if<
6982  std::is_signed<NumberType>::value and
6983  not std::is_floating_point<NumberType>::value, int>::type = 0>
6984  void write_number_with_ubjson_prefix(const NumberType n,
6985  const bool add_prefix)
6986  {
6987  if ((std::numeric_limits<int8_t>::min)() <= n and n <= (std::numeric_limits<int8_t>::max)())
6988  {
6989  if (add_prefix)
6990  {
6991  oa->write_character(static_cast<CharType>('i')); // int8
6992  }
6993  write_number(static_cast<int8_t>(n));
6994  }
6995  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)()))
6996  {
6997  if (add_prefix)
6998  {
6999  oa->write_character(static_cast<CharType>('U')); // uint8
7000  }
7001  write_number(static_cast<uint8_t>(n));
7002  }
7003  else if ((std::numeric_limits<int16_t>::min)() <= n and n <= (std::numeric_limits<int16_t>::max)())
7004  {
7005  if (add_prefix)
7006  {
7007  oa->write_character(static_cast<CharType>('I')); // int16
7008  }
7009  write_number(static_cast<int16_t>(n));
7010  }
7011  else if ((std::numeric_limits<int32_t>::min)() <= n and n <= (std::numeric_limits<int32_t>::max)())
7012  {
7013  if (add_prefix)
7014  {
7015  oa->write_character(static_cast<CharType>('l')); // int32
7016  }
7017  write_number(static_cast<int32_t>(n));
7018  }
7019  else if ((std::numeric_limits<int64_t>::min)() <= n and n <= (std::numeric_limits<int64_t>::max)())
7020  {
7021  if (add_prefix)
7022  {
7023  oa->write_character(static_cast<CharType>('L')); // int64
7024  }
7025  write_number(static_cast<int64_t>(n));
7026  }
7027  // LCOV_EXCL_START
7028  else
7029  {
7030  JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n)));
7031  }
7032  // LCOV_EXCL_STOP
7033  }
7034 
7044  char ubjson_prefix(const BasicJsonType& j) const noexcept
7045  {
7046  switch (j.type())
7047  {
7048  case value_t::null:
7049  return 'Z';
7050 
7051  case value_t::boolean:
7052  return j.m_value.boolean ? 'T' : 'F';
7053 
7055  {
7056  if ((std::numeric_limits<int8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
7057  {
7058  return 'i';
7059  }
7060  else if ((std::numeric_limits<uint8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
7061  {
7062  return 'U';
7063  }
7064  else if ((std::numeric_limits<int16_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
7065  {
7066  return 'I';
7067  }
7068  else if ((std::numeric_limits<int32_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
7069  {
7070  return 'l';
7071  }
7072  else // no check and assume int64_t (see note above)
7073  {
7074  return 'L';
7075  }
7076  }
7077 
7079  {
7080  if (j.m_value.number_unsigned <= (std::numeric_limits<int8_t>::max)())
7081  {
7082  return 'i';
7083  }
7084  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
7085  {
7086  return 'U';
7087  }
7088  else if (j.m_value.number_unsigned <= (std::numeric_limits<int16_t>::max)())
7089  {
7090  return 'I';
7091  }
7092  else if (j.m_value.number_unsigned <= (std::numeric_limits<int32_t>::max)())
7093  {
7094  return 'l';
7095  }
7096  else // no check and assume int64_t (see note above)
7097  {
7098  return 'L';
7099  }
7100  }
7101 
7102  case value_t::number_float:
7103  return 'D';
7104 
7105  case value_t::string:
7106  return 'S';
7107 
7108  case value_t::array:
7109  return '[';
7110 
7111  case value_t::object:
7112  return '{';
7113 
7114  default: // discarded values
7115  return 'N';
7116  }
7117  }
7118 
7119  private:
7121  const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
7122 
7124  output_adapter_t<CharType> oa = nullptr;
7125 };
7126 }
7127 }
7128 
7129 // #include <nlohmann/detail/output/serializer.hpp>
7130 
7131 
7132 #include <algorithm> // reverse, remove, fill, find, none_of
7133 #include <array> // array
7134 #include <cassert> // assert
7135 #include <ciso646> // and, or
7136 #include <clocale> // localeconv, lconv
7137 #include <cmath> // labs, isfinite, isnan, signbit
7138 #include <cstddef> // size_t, ptrdiff_t
7139 #include <cstdint> // uint8_t
7140 #include <cstdio> // snprintf
7141 #include <iomanip> // setfill
7142 #include <iterator> // next
7143 #include <limits> // numeric_limits
7144 #include <string> // string
7145 #include <sstream> // stringstream
7146 #include <type_traits> // is_same
7147 
7148 // #include <nlohmann/detail/exceptions.hpp>
7149 
7150 // #include <nlohmann/detail/conversions/to_chars.hpp>
7151 
7152 
7153 #include <cassert> // assert
7154 #include <ciso646> // or, and, not
7155 #include <cmath> // signbit, isfinite
7156 #include <cstdint> // intN_t, uintN_t
7157 #include <cstring> // memcpy, memmove
7158 
7159 namespace nlohmann
7160 {
7161 namespace detail
7162 {
7163 
7183 namespace dtoa_impl
7184 {
7185 
7186 template <typename Target, typename Source>
7187 Target reinterpret_bits(const Source source)
7188 {
7189  static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
7190 
7191  Target target;
7192  std::memcpy(&target, &source, sizeof(Source));
7193  return target;
7194 }
7195 
7196 struct diyfp // f * 2^e
7197 {
7198  static constexpr int kPrecision = 64; // = q
7199 
7200  uint64_t f;
7201  int e;
7202 
7203  constexpr diyfp() noexcept : f(0), e(0) {}
7204  constexpr diyfp(uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
7205 
7210  static diyfp sub(const diyfp& x, const diyfp& y) noexcept
7211  {
7212  assert(x.e == y.e);
7213  assert(x.f >= y.f);
7214 
7215  return diyfp(x.f - y.f, x.e);
7216  }
7217 
7222  static diyfp mul(const diyfp& x, const diyfp& y) noexcept
7223  {
7224  static_assert(kPrecision == 64, "internal error");
7225 
7226  // Computes:
7227  // f = round((x.f * y.f) / 2^q)
7228  // e = x.e + y.e + q
7229 
7230  // Emulate the 64-bit * 64-bit multiplication:
7231  //
7232  // p = u * v
7233  // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
7234  // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
7235  // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
7236  // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
7237  // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
7238  // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
7239  // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
7240  //
7241  // (Since Q might be larger than 2^32 - 1)
7242  //
7243  // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
7244  //
7245  // (Q_hi + H does not overflow a 64-bit int)
7246  //
7247  // = p_lo + 2^64 p_hi
7248 
7249  const uint64_t u_lo = x.f & 0xFFFFFFFF;
7250  const uint64_t u_hi = x.f >> 32;
7251  const uint64_t v_lo = y.f & 0xFFFFFFFF;
7252  const uint64_t v_hi = y.f >> 32;
7253 
7254  const uint64_t p0 = u_lo * v_lo;
7255  const uint64_t p1 = u_lo * v_hi;
7256  const uint64_t p2 = u_hi * v_lo;
7257  const uint64_t p3 = u_hi * v_hi;
7258 
7259  const uint64_t p0_hi = p0 >> 32;
7260  const uint64_t p1_lo = p1 & 0xFFFFFFFF;
7261  const uint64_t p1_hi = p1 >> 32;
7262  const uint64_t p2_lo = p2 & 0xFFFFFFFF;
7263  const uint64_t p2_hi = p2 >> 32;
7264 
7265  uint64_t Q = p0_hi + p1_lo + p2_lo;
7266 
7267  // The full product might now be computed as
7268  //
7269  // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
7270  // p_lo = p0_lo + (Q << 32)
7271  //
7272  // But in this particular case here, the full p_lo is not required.
7273  // Effectively we only need to add the highest bit in p_lo to p_hi (and
7274  // Q_hi + 1 does not overflow).
7275 
7276  Q += uint64_t{1} << (64 - 32 - 1); // round, ties up
7277 
7278  const uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32);
7279 
7280  return diyfp(h, x.e + y.e + 64);
7281  }
7282 
7287  static diyfp normalize(diyfp x) noexcept
7288  {
7289  assert(x.f != 0);
7290 
7291  while ((x.f >> 63) == 0)
7292  {
7293  x.f <<= 1;
7294  x.e--;
7295  }
7296 
7297  return x;
7298  }
7299 
7304  static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
7305  {
7306  const int delta = x.e - target_exponent;
7307 
7308  assert(delta >= 0);
7309  assert(((x.f << delta) >> delta) == x.f);
7310 
7311  return diyfp(x.f << delta, target_exponent);
7312  }
7313 };
7314 
7316 {
7317  diyfp w;
7318  diyfp minus;
7319  diyfp plus;
7320 };
7321 
7328 template <typename FloatType>
7330 {
7331  assert(std::isfinite(value));
7332  assert(value > 0);
7333 
7334  // Convert the IEEE representation into a diyfp.
7335  //
7336  // If v is denormal:
7337  // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
7338  // If v is normalized:
7339  // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
7340 
7341  static_assert(std::numeric_limits<FloatType>::is_iec559,
7342  "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
7343 
7344  constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
7345  constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
7346  constexpr int kMinExp = 1 - kBias;
7347  constexpr uint64_t kHiddenBit = uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
7348 
7349  using bits_type = typename std::conditional< kPrecision == 24, uint32_t, uint64_t >::type;
7350 
7351  const uint64_t bits = reinterpret_bits<bits_type>(value);
7352  const uint64_t E = bits >> (kPrecision - 1);
7353  const uint64_t F = bits & (kHiddenBit - 1);
7354 
7355  const bool is_denormal = (E == 0);
7356  const diyfp v = is_denormal
7357  ? diyfp(F, kMinExp)
7358  : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
7359 
7360  // Compute the boundaries m- and m+ of the floating-point value
7361  // v = f * 2^e.
7362  //
7363  // Determine v- and v+, the floating-point predecessor and successor if v,
7364  // respectively.
7365  //
7366  // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
7367  // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
7368  //
7369  // v+ = v + 2^e
7370  //
7371  // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
7372  // between m- and m+ round to v, regardless of how the input rounding
7373  // algorithm breaks ties.
7374  //
7375  // ---+-------------+-------------+-------------+-------------+--- (A)
7376  // v- m- v m+ v+
7377  //
7378  // -----------------+------+------+-------------+-------------+--- (B)
7379  // v- m- v m+ v+
7380 
7381  const bool lower_boundary_is_closer = (F == 0 and E > 1);
7382  const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
7383  const diyfp m_minus = lower_boundary_is_closer
7384  ? diyfp(4 * v.f - 1, v.e - 2) // (B)
7385  : diyfp(2 * v.f - 1, v.e - 1); // (A)
7386 
7387  // Determine the normalized w+ = m+.
7388  const diyfp w_plus = diyfp::normalize(m_plus);
7389 
7390  // Determine w- = m- such that e_(w-) = e_(w+).
7391  const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
7392 
7393  return {diyfp::normalize(v), w_minus, w_plus};
7394 }
7395 
7396 // Given normalized diyfp w, Grisu needs to find a (normalized) cached
7397 // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
7398 // within a certain range [alpha, gamma] (Definition 3.2 from [1])
7399 //
7400 // alpha <= e = e_c + e_w + q <= gamma
7401 //
7402 // or
7403 //
7404 // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
7405 // <= f_c * f_w * 2^gamma
7406 //
7407 // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
7408 //
7409 // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
7410 //
7411 // or
7412 //
7413 // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
7414 //
7415 // The choice of (alpha,gamma) determines the size of the table and the form of
7416 // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
7417 // in practice:
7418 //
7419 // The idea is to cut the number c * w = f * 2^e into two parts, which can be
7420 // processed independently: An integral part p1, and a fractional part p2:
7421 //
7422 // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
7423 // = (f div 2^-e) + (f mod 2^-e) * 2^e
7424 // = p1 + p2 * 2^e
7425 //
7426 // The conversion of p1 into decimal form requires a series of divisions and
7427 // modulos by (a power of) 10. These operations are faster for 32-bit than for
7428 // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
7429 // achieved by choosing
7430 //
7431 // -e >= 32 or e <= -32 := gamma
7432 //
7433 // In order to convert the fractional part
7434 //
7435 // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
7436 //
7437 // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
7438 // d[-i] are extracted in order:
7439 //
7440 // (10 * p2) div 2^-e = d[-1]
7441 // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
7442 //
7443 // The multiplication by 10 must not overflow. It is sufficient to choose
7444 //
7445 // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
7446 //
7447 // Since p2 = f mod 2^-e < 2^-e,
7448 //
7449 // -e <= 60 or e >= -60 := alpha
7450 
7451 constexpr int kAlpha = -60;
7452 constexpr int kGamma = -32;
7453 
7454 struct cached_power // c = f * 2^e ~= 10^k
7455 {
7456  uint64_t f;
7457  int e;
7458  int k;
7459 };
7460 
7469 {
7470  // Now
7471  //
7472  // alpha <= e_c + e + q <= gamma (1)
7473  // ==> f_c * 2^alpha <= c * 2^e * 2^q
7474  //
7475  // and since the c's are normalized, 2^(q-1) <= f_c,
7476  //
7477  // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
7478  // ==> 2^(alpha - e - 1) <= c
7479  //
7480  // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as
7481  //
7482  // k = ceil( log_10( 2^(alpha - e - 1) ) )
7483  // = ceil( (alpha - e - 1) * log_10(2) )
7484  //
7485  // From the paper:
7486  // "In theory the result of the procedure could be wrong since c is rounded,
7487  // and the computation itself is approximated [...]. In practice, however,
7488  // this simple function is sufficient."
7489  //
7490  // For IEEE double precision floating-point numbers converted into
7491  // normalized diyfp's w = f * 2^e, with q = 64,
7492  //
7493  // e >= -1022 (min IEEE exponent)
7494  // -52 (p - 1)
7495  // -52 (p - 1, possibly normalize denormal IEEE numbers)
7496  // -11 (normalize the diyfp)
7497  // = -1137
7498  //
7499  // and
7500  //
7501  // e <= +1023 (max IEEE exponent)
7502  // -52 (p - 1)
7503  // -11 (normalize the diyfp)
7504  // = 960
7505  //
7506  // This binary exponent range [-1137,960] results in a decimal exponent
7507  // range [-307,324]. One does not need to store a cached power for each
7508  // k in this range. For each such k it suffices to find a cached power
7509  // such that the exponent of the product lies in [alpha,gamma].
7510  // This implies that the difference of the decimal exponents of adjacent
7511  // table entries must be less than or equal to
7512  //
7513  // floor( (gamma - alpha) * log_10(2) ) = 8.
7514  //
7515  // (A smaller distance gamma-alpha would require a larger table.)
7516 
7517  // NB:
7518  // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
7519 
7520  constexpr int kCachedPowersSize = 79;
7521  constexpr int kCachedPowersMinDecExp = -300;
7522  constexpr int kCachedPowersDecStep = 8;
7523 
7524  static constexpr cached_power kCachedPowers[] =
7525  {
7526  { 0xAB70FE17C79AC6CA, -1060, -300 },
7527  { 0xFF77B1FCBEBCDC4F, -1034, -292 },
7528  { 0xBE5691EF416BD60C, -1007, -284 },
7529  { 0x8DD01FAD907FFC3C, -980, -276 },
7530  { 0xD3515C2831559A83, -954, -268 },
7531  { 0x9D71AC8FADA6C9B5, -927, -260 },
7532  { 0xEA9C227723EE8BCB, -901, -252 },
7533  { 0xAECC49914078536D, -874, -244 },
7534  { 0x823C12795DB6CE57, -847, -236 },
7535  { 0xC21094364DFB5637, -821, -228 },
7536  { 0x9096EA6F3848984F, -794, -220 },
7537  { 0xD77485CB25823AC7, -768, -212 },
7538  { 0xA086CFCD97BF97F4, -741, -204 },
7539  { 0xEF340A98172AACE5, -715, -196 },
7540  { 0xB23867FB2A35B28E, -688, -188 },
7541  { 0x84C8D4DFD2C63F3B, -661, -180 },
7542  { 0xC5DD44271AD3CDBA, -635, -172 },
7543  { 0x936B9FCEBB25C996, -608, -164 },
7544  { 0xDBAC6C247D62A584, -582, -156 },
7545  { 0xA3AB66580D5FDAF6, -555, -148 },
7546  { 0xF3E2F893DEC3F126, -529, -140 },
7547  { 0xB5B5ADA8AAFF80B8, -502, -132 },
7548  { 0x87625F056C7C4A8B, -475, -124 },
7549  { 0xC9BCFF6034C13053, -449, -116 },
7550  { 0x964E858C91BA2655, -422, -108 },
7551  { 0xDFF9772470297EBD, -396, -100 },
7552  { 0xA6DFBD9FB8E5B88F, -369, -92 },
7553  { 0xF8A95FCF88747D94, -343, -84 },
7554  { 0xB94470938FA89BCF, -316, -76 },
7555  { 0x8A08F0F8BF0F156B, -289, -68 },
7556  { 0xCDB02555653131B6, -263, -60 },
7557  { 0x993FE2C6D07B7FAC, -236, -52 },
7558  { 0xE45C10C42A2B3B06, -210, -44 },
7559  { 0xAA242499697392D3, -183, -36 },
7560  { 0xFD87B5F28300CA0E, -157, -28 },
7561  { 0xBCE5086492111AEB, -130, -20 },
7562  { 0x8CBCCC096F5088CC, -103, -12 },
7563  { 0xD1B71758E219652C, -77, -4 },
7564  { 0x9C40000000000000, -50, 4 },
7565  { 0xE8D4A51000000000, -24, 12 },
7566  { 0xAD78EBC5AC620000, 3, 20 },
7567  { 0x813F3978F8940984, 30, 28 },
7568  { 0xC097CE7BC90715B3, 56, 36 },
7569  { 0x8F7E32CE7BEA5C70, 83, 44 },
7570  { 0xD5D238A4ABE98068, 109, 52 },
7571  { 0x9F4F2726179A2245, 136, 60 },
7572  { 0xED63A231D4C4FB27, 162, 68 },
7573  { 0xB0DE65388CC8ADA8, 189, 76 },
7574  { 0x83C7088E1AAB65DB, 216, 84 },
7575  { 0xC45D1DF942711D9A, 242, 92 },
7576  { 0x924D692CA61BE758, 269, 100 },
7577  { 0xDA01EE641A708DEA, 295, 108 },
7578  { 0xA26DA3999AEF774A, 322, 116 },
7579  { 0xF209787BB47D6B85, 348, 124 },
7580  { 0xB454E4A179DD1877, 375, 132 },
7581  { 0x865B86925B9BC5C2, 402, 140 },
7582  { 0xC83553C5C8965D3D, 428, 148 },
7583  { 0x952AB45CFA97A0B3, 455, 156 },
7584  { 0xDE469FBD99A05FE3, 481, 164 },
7585  { 0xA59BC234DB398C25, 508, 172 },
7586  { 0xF6C69A72A3989F5C, 534, 180 },
7587  { 0xB7DCBF5354E9BECE, 561, 188 },
7588  { 0x88FCF317F22241E2, 588, 196 },
7589  { 0xCC20CE9BD35C78A5, 614, 204 },
7590  { 0x98165AF37B2153DF, 641, 212 },
7591  { 0xE2A0B5DC971F303A, 667, 220 },
7592  { 0xA8D9D1535CE3B396, 694, 228 },
7593  { 0xFB9B7CD9A4A7443C, 720, 236 },
7594  { 0xBB764C4CA7A44410, 747, 244 },
7595  { 0x8BAB8EEFB6409C1A, 774, 252 },
7596  { 0xD01FEF10A657842C, 800, 260 },
7597  { 0x9B10A4E5E9913129, 827, 268 },
7598  { 0xE7109BFBA19C0C9D, 853, 276 },
7599  { 0xAC2820D9623BF429, 880, 284 },
7600  { 0x80444B5E7AA7CF85, 907, 292 },
7601  { 0xBF21E44003ACDD2D, 933, 300 },
7602  { 0x8E679C2F5E44FF8F, 960, 308 },
7603  { 0xD433179D9C8CB841, 986, 316 },
7604  { 0x9E19DB92B4E31BA9, 1013, 324 },
7605  };
7606 
7607  // This computation gives exactly the same results for k as
7608  // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
7609  // for |e| <= 1500, but doesn't require floating-point operations.
7610  // NB: log_10(2) ~= 78913 / 2^18
7611  assert(e >= -1500);
7612  assert(e <= 1500);
7613  const int f = kAlpha - e - 1;
7614  const int k = (f * 78913) / (1 << 18) + (f > 0);
7615 
7616  const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
7617  assert(index >= 0);
7618  assert(index < kCachedPowersSize);
7619  static_cast<void>(kCachedPowersSize); // Fix warning.
7620 
7621  const cached_power cached = kCachedPowers[index];
7622  assert(kAlpha <= cached.e + e + 64);
7623  assert(kGamma >= cached.e + e + 64);
7624 
7625  return cached;
7626 }
7627 
7632 inline int find_largest_pow10(const uint32_t n, uint32_t& pow10)
7633 {
7634  // LCOV_EXCL_START
7635  if (n >= 1000000000)
7636  {
7637  pow10 = 1000000000;
7638  return 10;
7639  }
7640  // LCOV_EXCL_STOP
7641  else if (n >= 100000000)
7642  {
7643  pow10 = 100000000;
7644  return 9;
7645  }
7646  else if (n >= 10000000)
7647  {
7648  pow10 = 10000000;
7649  return 8;
7650  }
7651  else if (n >= 1000000)
7652  {
7653  pow10 = 1000000;
7654  return 7;
7655  }
7656  else if (n >= 100000)
7657  {
7658  pow10 = 100000;
7659  return 6;
7660  }
7661  else if (n >= 10000)
7662  {
7663  pow10 = 10000;
7664  return 5;
7665  }
7666  else if (n >= 1000)
7667  {
7668  pow10 = 1000;
7669  return 4;
7670  }
7671  else if (n >= 100)
7672  {
7673  pow10 = 100;
7674  return 3;
7675  }
7676  else if (n >= 10)
7677  {
7678  pow10 = 10;
7679  return 2;
7680  }
7681  else
7682  {
7683  pow10 = 1;
7684  return 1;
7685  }
7686 }
7687 
7688 inline void grisu2_round(char* buf, int len, uint64_t dist, uint64_t delta,
7689  uint64_t rest, uint64_t ten_k)
7690 {
7691  assert(len >= 1);
7692  assert(dist <= delta);
7693  assert(rest <= delta);
7694  assert(ten_k > 0);
7695 
7696  // <--------------------------- delta ---->
7697  // <---- dist --------->
7698  // --------------[------------------+-------------------]--------------
7699  // M- w M+
7700  //
7701  // ten_k
7702  // <------>
7703  // <---- rest ---->
7704  // --------------[------------------+----+--------------]--------------
7705  // w V
7706  // = buf * 10^k
7707  //
7708  // ten_k represents a unit-in-the-last-place in the decimal representation
7709  // stored in buf.
7710  // Decrement buf by ten_k while this takes buf closer to w.
7711 
7712  // The tests are written in this order to avoid overflow in unsigned
7713  // integer arithmetic.
7714 
7715  while (rest < dist
7716  and delta - rest >= ten_k
7717  and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
7718  {
7719  assert(buf[len - 1] != '0');
7720  buf[len - 1]--;
7721  rest += ten_k;
7722  }
7723 }
7724 
7729 inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
7730  diyfp M_minus, diyfp w, diyfp M_plus)
7731 {
7732  static_assert(kAlpha >= -60, "internal error");
7733  static_assert(kGamma <= -32, "internal error");
7734 
7735  // Generates the digits (and the exponent) of a decimal floating-point
7736  // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
7737  // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
7738  //
7739  // <--------------------------- delta ---->
7740  // <---- dist --------->
7741  // --------------[------------------+-------------------]--------------
7742  // M- w M+
7743  //
7744  // Grisu2 generates the digits of M+ from left to right and stops as soon as
7745  // V is in [M-,M+].
7746 
7747  assert(M_plus.e >= kAlpha);
7748  assert(M_plus.e <= kGamma);
7749 
7750  uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
7751  uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
7752 
7753  // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
7754  //
7755  // M+ = f * 2^e
7756  // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
7757  // = ((p1 ) * 2^-e + (p2 )) * 2^e
7758  // = p1 + p2 * 2^e
7759 
7760  const diyfp one(uint64_t{1} << -M_plus.e, M_plus.e);
7761 
7762  uint32_t p1 = static_cast<uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)
7763  uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
7764 
7765  // 1)
7766  //
7767  // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
7768 
7769  assert(p1 > 0);
7770 
7771  uint32_t pow10;
7772  const int k = find_largest_pow10(p1, pow10);
7773 
7774  // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
7775  //
7776  // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
7777  // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
7778  //
7779  // M+ = p1 + p2 * 2^e
7780  // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
7781  // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
7782  // = d[k-1] * 10^(k-1) + ( rest) * 2^e
7783  //
7784  // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
7785  //
7786  // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
7787  //
7788  // but stop as soon as
7789  //
7790  // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
7791 
7792  int n = k;
7793  while (n > 0)
7794  {
7795  // Invariants:
7796  // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
7797  // pow10 = 10^(n-1) <= p1 < 10^n
7798  //
7799  const uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
7800  const uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
7801  //
7802  // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
7803  // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
7804  //
7805  assert(d <= 9);
7806  buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
7807  //
7808  // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
7809  //
7810  p1 = r;
7811  n--;
7812  //
7813  // M+ = buffer * 10^n + (p1 + p2 * 2^e)
7814  // pow10 = 10^n
7815  //
7816 
7817  // Now check if enough digits have been generated.
7818  // Compute
7819  //
7820  // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
7821  //
7822  // Note:
7823  // Since rest and delta share the same exponent e, it suffices to
7824  // compare the significands.
7825  const uint64_t rest = (uint64_t{p1} << -one.e) + p2;
7826  if (rest <= delta)
7827  {
7828  // V = buffer * 10^n, with M- <= V <= M+.
7829 
7830  decimal_exponent += n;
7831 
7832  // We may now just stop. But instead look if the buffer could be
7833  // decremented to bring V closer to w.
7834  //
7835  // pow10 = 10^n is now 1 ulp in the decimal representation V.
7836  // The rounding procedure works with diyfp's with an implicit
7837  // exponent of e.
7838  //
7839  // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
7840  //
7841  const uint64_t ten_n = uint64_t{pow10} << -one.e;
7842  grisu2_round(buffer, length, dist, delta, rest, ten_n);
7843 
7844  return;
7845  }
7846 
7847  pow10 /= 10;
7848  //
7849  // pow10 = 10^(n-1) <= p1 < 10^n
7850  // Invariants restored.
7851  }
7852 
7853  // 2)
7854  //
7855  // The digits of the integral part have been generated:
7856  //
7857  // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
7858  // = buffer + p2 * 2^e
7859  //
7860  // Now generate the digits of the fractional part p2 * 2^e.
7861  //
7862  // Note:
7863  // No decimal point is generated: the exponent is adjusted instead.
7864  //
7865  // p2 actually represents the fraction
7866  //
7867  // p2 * 2^e
7868  // = p2 / 2^-e
7869  // = d[-1] / 10^1 + d[-2] / 10^2 + ...
7870  //
7871  // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
7872  //
7873  // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
7874  // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
7875  //
7876  // using
7877  //
7878  // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
7879  // = ( d) * 2^-e + ( r)
7880  //
7881  // or
7882  // 10^m * p2 * 2^e = d + r * 2^e
7883  //
7884  // i.e.
7885  //
7886  // M+ = buffer + p2 * 2^e
7887  // = buffer + 10^-m * (d + r * 2^e)
7888  // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
7889  //
7890  // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
7891 
7892  assert(p2 > delta);
7893 
7894  int m = 0;
7895  for (;;)
7896  {
7897  // Invariant:
7898  // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
7899  // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
7900  // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
7901  // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
7902  //
7903  assert(p2 <= UINT64_MAX / 10);
7904  p2 *= 10;
7905  const uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
7906  const uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
7907  //
7908  // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
7909  // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
7910  // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
7911  //
7912  assert(d <= 9);
7913  buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
7914  //
7915  // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
7916  //
7917  p2 = r;
7918  m++;
7919  //
7920  // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
7921  // Invariant restored.
7922 
7923  // Check if enough digits have been generated.
7924  //
7925  // 10^-m * p2 * 2^e <= delta * 2^e
7926  // p2 * 2^e <= 10^m * delta * 2^e
7927  // p2 <= 10^m * delta
7928  delta *= 10;
7929  dist *= 10;
7930  if (p2 <= delta)
7931  {
7932  break;
7933  }
7934  }
7935 
7936  // V = buffer * 10^-m, with M- <= V <= M+.
7937 
7938  decimal_exponent -= m;
7939 
7940  // 1 ulp in the decimal representation is now 10^-m.
7941  // Since delta and dist are now scaled by 10^m, we need to do the
7942  // same with ulp in order to keep the units in sync.
7943  //
7944  // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
7945  //
7946  const uint64_t ten_m = one.f;
7947  grisu2_round(buffer, length, dist, delta, p2, ten_m);
7948 
7949  // By construction this algorithm generates the shortest possible decimal
7950  // number (Loitsch, Theorem 6.2) which rounds back to w.
7951  // For an input number of precision p, at least
7952  //
7953  // N = 1 + ceil(p * log_10(2))
7954  //
7955  // decimal digits are sufficient to identify all binary floating-point
7956  // numbers (Matula, "In-and-Out conversions").
7957  // This implies that the algorithm does not produce more than N decimal
7958  // digits.
7959  //
7960  // N = 17 for p = 53 (IEEE double precision)
7961  // N = 9 for p = 24 (IEEE single precision)
7962 }
7963 
7969 inline void grisu2(char* buf, int& len, int& decimal_exponent,
7970  diyfp m_minus, diyfp v, diyfp m_plus)
7971 {
7972  assert(m_plus.e == m_minus.e);
7973  assert(m_plus.e == v.e);
7974 
7975  // --------(-----------------------+-----------------------)-------- (A)
7976  // m- v m+
7977  //
7978  // --------------------(-----------+-----------------------)-------- (B)
7979  // m- v m+
7980  //
7981  // First scale v (and m- and m+) such that the exponent is in the range
7982  // [alpha, gamma].
7983