Mercurial > embed
comparison json/json.hpp @ 65:6aeb91259841
json: upgrade to 3.1.2, closes #884
author | David Demelier <markand@malikania.fr> |
---|---|
date | Fri, 13 Jul 2018 12:53:06 +0200 |
parents | bb0a02962544 |
children |
comparison
equal
deleted
inserted
replaced
64:58ade32642d6 | 65:6aeb91259841 |
---|---|
1 /* | 1 /* |
2 __ _____ _____ _____ | 2 __ _____ _____ _____ |
3 __| | __| | | | JSON for Modern C++ | 3 __| | __| | | | JSON for Modern C++ |
4 | | |__ | | | | | | version 2.1.1 | 4 | | |__ | | | | | | version 3.1.2 |
5 |_____|_____|_____|_|___| https://github.com/nlohmann/json | 5 |_____|_____|_____|_|___| https://github.com/nlohmann/json |
6 | 6 |
7 Licensed under the MIT License <http://opensource.org/licenses/MIT>. | 7 Licensed under the MIT License <http://opensource.org/licenses/MIT>. |
8 Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>. | 8 Copyright (c) 2013-2018 Niels Lohmann <http://nlohmann.me>. |
9 | 9 |
10 Permission is hereby granted, free of charge, to any person obtaining a copy | 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 | 11 of this software and associated documentation files (the "Software"), to deal |
12 in the Software without restriction, including without limitation the rights | 12 in the Software without restriction, including without limitation the rights |
13 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | 13 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
27 */ | 27 */ |
28 | 28 |
29 #ifndef NLOHMANN_JSON_HPP | 29 #ifndef NLOHMANN_JSON_HPP |
30 #define NLOHMANN_JSON_HPP | 30 #define NLOHMANN_JSON_HPP |
31 | 31 |
32 #include <algorithm> // all_of, copy, fill, find, for_each, none_of, remove, reverse, transform | 32 #define NLOHMANN_JSON_VERSION_MAJOR 3 |
33 #include <array> // array | 33 #define NLOHMANN_JSON_VERSION_MINOR 1 |
34 #define NLOHMANN_JSON_VERSION_PATCH 2 | |
35 | |
36 #include <algorithm> // all_of, find, for_each | |
34 #include <cassert> // assert | 37 #include <cassert> // assert |
35 #include <cctype> // isdigit | |
36 #include <ciso646> // and, not, or | 38 #include <ciso646> // and, not, or |
37 #include <cmath> // isfinite, labs, ldexp, signbit | |
38 #include <cstddef> // nullptr_t, ptrdiff_t, size_t | 39 #include <cstddef> // nullptr_t, ptrdiff_t, size_t |
40 #include <functional> // hash, less | |
41 #include <initializer_list> // initializer_list | |
42 #include <iosfwd> // istream, ostream | |
43 #include <iterator> // iterator_traits, random_access_iterator_tag | |
44 #include <numeric> // accumulate | |
45 #include <string> // string, stoi, to_string | |
46 #include <utility> // declval, forward, move, pair, swap | |
47 | |
48 // #include <nlohmann/json_fwd.hpp> | |
49 #ifndef NLOHMANN_JSON_FWD_HPP | |
50 #define NLOHMANN_JSON_FWD_HPP | |
51 | |
39 #include <cstdint> // int64_t, uint64_t | 52 #include <cstdint> // int64_t, uint64_t |
40 #include <cstdlib> // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull | |
41 #include <cstring> // strlen | |
42 #include <forward_list> // forward_list | |
43 #include <functional> // function, hash, less | |
44 #include <initializer_list> // initializer_list | |
45 #include <iomanip> // setw | |
46 #include <iostream> // istream, ostream | |
47 #include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator | |
48 #include <limits> // numeric_limits | |
49 #include <locale> // locale | |
50 #include <map> // map | 53 #include <map> // map |
51 #include <memory> // addressof, allocator, allocator_traits, unique_ptr | 54 #include <memory> // allocator |
52 #include <numeric> // accumulate | 55 #include <string> // string |
53 #include <sstream> // stringstream | |
54 #include <stdexcept> // domain_error, invalid_argument, out_of_range | |
55 #include <string> // getline, stoi, string, to_string | |
56 #include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type | |
57 #include <utility> // declval, forward, make_pair, move, pair, swap | |
58 #include <vector> // vector | 56 #include <vector> // vector |
57 | |
58 /*! | |
59 @brief namespace for Niels Lohmann | |
60 @see https://github.com/nlohmann | |
61 @since version 1.0.0 | |
62 */ | |
63 namespace nlohmann | |
64 { | |
65 /*! | |
66 @brief default JSONSerializer template argument | |
67 | |
68 This serializer ignores the template arguments and uses ADL | |
69 ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl)) | |
70 for serialization. | |
71 */ | |
72 template<typename = void, typename = void> | |
73 struct adl_serializer; | |
74 | |
75 template<template<typename U, typename V, typename... Args> class ObjectType = | |
76 std::map, | |
77 template<typename U, typename... Args> class ArrayType = std::vector, | |
78 class StringType = std::string, class BooleanType = bool, | |
79 class NumberIntegerType = std::int64_t, | |
80 class NumberUnsignedType = std::uint64_t, | |
81 class NumberFloatType = double, | |
82 template<typename U> class AllocatorType = std::allocator, | |
83 template<typename T, typename SFINAE = void> class JSONSerializer = | |
84 adl_serializer> | |
85 class basic_json; | |
86 | |
87 /*! | |
88 @brief JSON Pointer | |
89 | |
90 A JSON pointer defines a string syntax for identifying a specific value | |
91 within a JSON document. It can be used with functions `at` and | |
92 `operator[]`. Furthermore, JSON pointers are the base for JSON patches. | |
93 | |
94 @sa [RFC 6901](https://tools.ietf.org/html/rfc6901) | |
95 | |
96 @since version 2.0.0 | |
97 */ | |
98 template<typename BasicJsonType> | |
99 class json_pointer; | |
100 | |
101 /*! | |
102 @brief default JSON class | |
103 | |
104 This type is the default specialization of the @ref basic_json class which | |
105 uses the standard template types. | |
106 | |
107 @since version 1.0.0 | |
108 */ | |
109 using json = basic_json<>; | |
110 } | |
111 | |
112 #endif | |
113 | |
114 // #include <nlohmann/detail/macro_scope.hpp> | |
115 | |
116 | |
117 // This file contains all internal macro definitions | |
118 // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them | |
59 | 119 |
60 // exclude unsupported compilers | 120 // exclude unsupported compilers |
61 #if defined(__clang__) | 121 #if defined(__clang__) |
62 #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 | 122 #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 |
63 #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" | 123 #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" |
64 #endif | 124 #endif |
65 #elif defined(__GNUC__) | 125 #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) |
66 #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900 | 126 #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900 |
67 #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" | 127 #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" |
68 #endif | 128 #endif |
69 #endif | 129 #endif |
70 | 130 |
88 #else | 148 #else |
89 #define JSON_DEPRECATED | 149 #define JSON_DEPRECATED |
90 #endif | 150 #endif |
91 | 151 |
92 // allow to disable exceptions | 152 // allow to disable exceptions |
93 #if not defined(JSON_NOEXCEPTION) || defined(__EXCEPTIONS) | 153 #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) |
94 #define JSON_THROW(exception) throw exception | 154 #define JSON_THROW(exception) throw exception |
95 #define JSON_TRY try | 155 #define JSON_TRY try |
96 #define JSON_CATCH(exception) catch(exception) | 156 #define JSON_CATCH(exception) catch(exception) |
97 #else | 157 #else |
98 #define JSON_THROW(exception) std::abort() | 158 #define JSON_THROW(exception) std::abort() |
99 #define JSON_TRY if(true) | 159 #define JSON_TRY if(true) |
100 #define JSON_CATCH(exception) if(false) | 160 #define JSON_CATCH(exception) if(false) |
101 #endif | 161 #endif |
102 | 162 |
103 /*! | 163 // override exception macros |
104 @brief namespace for Niels Lohmann | 164 #if defined(JSON_THROW_USER) |
105 @see https://github.com/nlohmann | 165 #undef JSON_THROW |
106 @since version 1.0.0 | 166 #define JSON_THROW JSON_THROW_USER |
107 */ | 167 #endif |
108 namespace nlohmann | 168 #if defined(JSON_TRY_USER) |
109 { | 169 #undef JSON_TRY |
110 | 170 #define JSON_TRY JSON_TRY_USER |
111 /*! | 171 #endif |
112 @brief unnamed namespace with internal helper functions | 172 #if defined(JSON_CATCH_USER) |
113 | 173 #undef JSON_CATCH |
114 This namespace collects some functions that could not be defined inside the | 174 #define JSON_CATCH JSON_CATCH_USER |
115 @ref basic_json class. | 175 #endif |
116 | 176 |
117 @since version 2.1.0 | 177 // manual branch prediction |
118 */ | 178 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) |
119 namespace detail | 179 #define JSON_LIKELY(x) __builtin_expect(!!(x), 1) |
120 { | 180 #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0) |
121 /////////////////////////// | 181 #else |
122 // JSON type enumeration // | 182 #define JSON_LIKELY(x) x |
123 /////////////////////////// | 183 #define JSON_UNLIKELY(x) x |
124 | 184 #endif |
125 /*! | 185 |
126 @brief the JSON type enumeration | 186 // C++ language standard detection |
127 | 187 #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 |
128 This enumeration collects the different JSON types. It is internally used to | 188 #define JSON_HAS_CPP_17 |
129 distinguish the stored values, and the functions @ref basic_json::is_null(), | 189 #define JSON_HAS_CPP_14 |
130 @ref basic_json::is_object(), @ref basic_json::is_array(), | 190 #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) |
131 @ref basic_json::is_string(), @ref basic_json::is_boolean(), | 191 #define JSON_HAS_CPP_14 |
132 @ref basic_json::is_number() (with @ref basic_json::is_number_integer(), | 192 #endif |
133 @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), | 193 |
134 @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and | 194 // Ugly macros to avoid uglier copy-paste when specializing basic_json. They |
135 @ref basic_json::is_structured() rely on it. | 195 // may be removed in the future once the class is split. |
136 | 196 |
137 @note There are three enumeration entries (number_integer, number_unsigned, and | 197 #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ |
138 number_float), because the library distinguishes these three types for numbers: | 198 template<template<typename, typename, typename...> class ObjectType, \ |
139 @ref basic_json::number_unsigned_t is used for unsigned integers, | 199 template<typename, typename...> class ArrayType, \ |
140 @ref basic_json::number_integer_t is used for signed integers, and | 200 class StringType, class BooleanType, class NumberIntegerType, \ |
141 @ref basic_json::number_float_t is used for floating-point numbers or to | 201 class NumberUnsignedType, class NumberFloatType, \ |
142 approximate integers which do not fit in the limits of their respective type. | 202 template<typename> class AllocatorType, \ |
143 | 203 template<typename, typename = void> class JSONSerializer> |
144 @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON | 204 |
145 value with the default value for a given type | 205 #define NLOHMANN_BASIC_JSON_TPL \ |
146 | 206 basic_json<ObjectType, ArrayType, StringType, BooleanType, \ |
147 @since version 1.0.0 | 207 NumberIntegerType, NumberUnsignedType, NumberFloatType, \ |
148 */ | 208 AllocatorType, JSONSerializer> |
149 enum class value_t : uint8_t | |
150 { | |
151 null, ///< null value | |
152 object, ///< object (unordered set of name/value pairs) | |
153 array, ///< array (ordered collection of values) | |
154 string, ///< string value | |
155 boolean, ///< boolean value | |
156 number_integer, ///< number value (signed integer) | |
157 number_unsigned, ///< number value (unsigned integer) | |
158 number_float, ///< number value (floating-point) | |
159 discarded ///< discarded by the the parser callback function | |
160 }; | |
161 | |
162 /*! | |
163 @brief comparison operator for JSON types | |
164 | |
165 Returns an ordering that is similar to Python: | |
166 - order: null < boolean < number < object < array < string | |
167 - furthermore, each type is not smaller than itself | |
168 | |
169 @since version 1.0.0 | |
170 */ | |
171 inline bool operator<(const value_t lhs, const value_t rhs) noexcept | |
172 { | |
173 static constexpr std::array<uint8_t, 8> order = {{ | |
174 0, // null | |
175 3, // object | |
176 4, // array | |
177 5, // string | |
178 1, // boolean | |
179 2, // integer | |
180 2, // unsigned | |
181 2, // float | |
182 } | |
183 }; | |
184 | |
185 // discarded values are not comparable | |
186 if (lhs == value_t::discarded or rhs == value_t::discarded) | |
187 { | |
188 return false; | |
189 } | |
190 | |
191 return order[static_cast<std::size_t>(lhs)] < | |
192 order[static_cast<std::size_t>(rhs)]; | |
193 } | |
194 | |
195 | |
196 ///////////// | |
197 // helpers // | |
198 ///////////// | |
199 | |
200 // alias templates to reduce boilerplate | |
201 template<bool B, typename T = void> | |
202 using enable_if_t = typename std::enable_if<B, T>::type; | |
203 | |
204 template<typename T> | |
205 using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type; | |
206 | |
207 // taken from http://stackoverflow.com/a/26936864/266378 | |
208 template<typename T> | |
209 using is_unscoped_enum = | |
210 std::integral_constant<bool, std::is_convertible<T, int>::value and | |
211 std::is_enum<T>::value>; | |
212 | |
213 /* | |
214 Implementation of two C++17 constructs: conjunction, negation. This is needed | |
215 to avoid evaluating all the traits in a condition | |
216 | |
217 For example: not std::is_same<void, T>::value and has_value_type<T>::value | |
218 will not compile when T = void (on MSVC at least). Whereas | |
219 conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will | |
220 stop evaluating if negation<...>::value == false | |
221 | |
222 Please note that those constructs must be used with caution, since symbols can | |
223 become very long quickly (which can slow down compilation and cause MSVC | |
224 internal compiler errors). Only use it when you have to (see example ahead). | |
225 */ | |
226 template<class...> struct conjunction : std::true_type {}; | |
227 template<class B1> struct conjunction<B1> : B1 {}; | |
228 template<class B1, class... Bn> | |
229 struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {}; | |
230 | |
231 template<class B> struct negation : std::integral_constant < bool, !B::value > {}; | |
232 | |
233 // dispatch utility (taken from ranges-v3) | |
234 template<unsigned N> struct priority_tag : priority_tag < N - 1 > {}; | |
235 template<> struct priority_tag<0> {}; | |
236 | |
237 | |
238 ////////////////// | |
239 // constructors // | |
240 ////////////////// | |
241 | |
242 template<value_t> struct external_constructor; | |
243 | |
244 template<> | |
245 struct external_constructor<value_t::boolean> | |
246 { | |
247 template<typename BasicJsonType> | |
248 static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept | |
249 { | |
250 j.m_type = value_t::boolean; | |
251 j.m_value = b; | |
252 j.assert_invariant(); | |
253 } | |
254 }; | |
255 | |
256 template<> | |
257 struct external_constructor<value_t::string> | |
258 { | |
259 template<typename BasicJsonType> | |
260 static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) | |
261 { | |
262 j.m_type = value_t::string; | |
263 j.m_value = s; | |
264 j.assert_invariant(); | |
265 } | |
266 }; | |
267 | |
268 template<> | |
269 struct external_constructor<value_t::number_float> | |
270 { | |
271 template<typename BasicJsonType> | |
272 static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept | |
273 { | |
274 // replace infinity and NAN by null | |
275 if (not std::isfinite(val)) | |
276 { | |
277 j = BasicJsonType{}; | |
278 } | |
279 else | |
280 { | |
281 j.m_type = value_t::number_float; | |
282 j.m_value = val; | |
283 } | |
284 j.assert_invariant(); | |
285 } | |
286 }; | |
287 | |
288 template<> | |
289 struct external_constructor<value_t::number_unsigned> | |
290 { | |
291 template<typename BasicJsonType> | |
292 static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept | |
293 { | |
294 j.m_type = value_t::number_unsigned; | |
295 j.m_value = val; | |
296 j.assert_invariant(); | |
297 } | |
298 }; | |
299 | |
300 template<> | |
301 struct external_constructor<value_t::number_integer> | |
302 { | |
303 template<typename BasicJsonType> | |
304 static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept | |
305 { | |
306 j.m_type = value_t::number_integer; | |
307 j.m_value = val; | |
308 j.assert_invariant(); | |
309 } | |
310 }; | |
311 | |
312 template<> | |
313 struct external_constructor<value_t::array> | |
314 { | |
315 template<typename BasicJsonType> | |
316 static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) | |
317 { | |
318 j.m_type = value_t::array; | |
319 j.m_value = arr; | |
320 j.assert_invariant(); | |
321 } | |
322 | |
323 template<typename BasicJsonType, typename CompatibleArrayType, | |
324 enable_if_t<not std::is_same<CompatibleArrayType, | |
325 typename BasicJsonType::array_t>::value, | |
326 int> = 0> | |
327 static void construct(BasicJsonType& j, const CompatibleArrayType& arr) | |
328 { | |
329 using std::begin; | |
330 using std::end; | |
331 j.m_type = value_t::array; | |
332 j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr)); | |
333 j.assert_invariant(); | |
334 } | |
335 }; | |
336 | |
337 template<> | |
338 struct external_constructor<value_t::object> | |
339 { | |
340 template<typename BasicJsonType> | |
341 static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) | |
342 { | |
343 j.m_type = value_t::object; | |
344 j.m_value = obj; | |
345 j.assert_invariant(); | |
346 } | |
347 | |
348 template<typename BasicJsonType, typename CompatibleObjectType, | |
349 enable_if_t<not std::is_same<CompatibleObjectType, | |
350 typename BasicJsonType::object_t>::value, | |
351 int> = 0> | |
352 static void construct(BasicJsonType& j, const CompatibleObjectType& obj) | |
353 { | |
354 using std::begin; | |
355 using std::end; | |
356 | |
357 j.m_type = value_t::object; | |
358 j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj)); | |
359 j.assert_invariant(); | |
360 } | |
361 }; | |
362 | |
363 | |
364 //////////////////////// | |
365 // has_/is_ functions // | |
366 //////////////////////// | |
367 | 209 |
368 /*! | 210 /*! |
369 @brief Helper to determine whether there's a key_type for T. | 211 @brief Helper to determine whether there's a key_type for T. |
370 | 212 |
371 This helper is used to tell associative containers apart from other containers | 213 This helper is used to tell associative containers apart from other containers |
384 public: \ | 226 public: \ |
385 static constexpr bool value = \ | 227 static constexpr bool value = \ |
386 std::is_integral<decltype(detect(std::declval<T>()))>::value; \ | 228 std::is_integral<decltype(detect(std::declval<T>()))>::value; \ |
387 } | 229 } |
388 | 230 |
231 // #include <nlohmann/detail/meta.hpp> | |
232 | |
233 | |
234 #include <ciso646> // not | |
235 #include <cstddef> // size_t | |
236 #include <limits> // numeric_limits | |
237 #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type | |
238 #include <utility> // declval | |
239 | |
240 // #include <nlohmann/json_fwd.hpp> | |
241 | |
242 // #include <nlohmann/detail/macro_scope.hpp> | |
243 | |
244 | |
245 namespace nlohmann | |
246 { | |
247 /*! | |
248 @brief detail namespace with internal helper functions | |
249 | |
250 This namespace collects functions that should not be exposed, | |
251 implementations of some @ref basic_json methods, and meta-programming helpers. | |
252 | |
253 @since version 2.1.0 | |
254 */ | |
255 namespace detail | |
256 { | |
257 ///////////// | |
258 // helpers // | |
259 ///////////// | |
260 | |
261 template<typename> struct is_basic_json : std::false_type {}; | |
262 | |
263 NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
264 struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {}; | |
265 | |
266 // alias templates to reduce boilerplate | |
267 template<bool B, typename T = void> | |
268 using enable_if_t = typename std::enable_if<B, T>::type; | |
269 | |
270 template<typename T> | |
271 using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type; | |
272 | |
273 // implementation of C++14 index_sequence and affiliates | |
274 // source: https://stackoverflow.com/a/32223343 | |
275 template<std::size_t... Ints> | |
276 struct index_sequence | |
277 { | |
278 using type = index_sequence; | |
279 using value_type = std::size_t; | |
280 static constexpr std::size_t size() noexcept | |
281 { | |
282 return sizeof...(Ints); | |
283 } | |
284 }; | |
285 | |
286 template<class Sequence1, class Sequence2> | |
287 struct merge_and_renumber; | |
288 | |
289 template<std::size_t... I1, std::size_t... I2> | |
290 struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>> | |
291 : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; | |
292 | |
293 template<std::size_t N> | |
294 struct make_index_sequence | |
295 : merge_and_renumber < typename make_index_sequence < N / 2 >::type, | |
296 typename make_index_sequence < N - N / 2 >::type > {}; | |
297 | |
298 template<> struct make_index_sequence<0> : index_sequence<> {}; | |
299 template<> struct make_index_sequence<1> : index_sequence<0> {}; | |
300 | |
301 template<typename... Ts> | |
302 using index_sequence_for = make_index_sequence<sizeof...(Ts)>; | |
303 | |
304 /* | |
305 Implementation of two C++17 constructs: conjunction, negation. This is needed | |
306 to avoid evaluating all the traits in a condition | |
307 | |
308 For example: not std::is_same<void, T>::value and has_value_type<T>::value | |
309 will not compile when T = void (on MSVC at least). Whereas | |
310 conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will | |
311 stop evaluating if negation<...>::value == false | |
312 | |
313 Please note that those constructs must be used with caution, since symbols can | |
314 become very long quickly (which can slow down compilation and cause MSVC | |
315 internal compiler errors). Only use it when you have to (see example ahead). | |
316 */ | |
317 template<class...> struct conjunction : std::true_type {}; | |
318 template<class B1> struct conjunction<B1> : B1 {}; | |
319 template<class B1, class... Bn> | |
320 struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {}; | |
321 | |
322 template<class B> struct negation : std::integral_constant<bool, not B::value> {}; | |
323 | |
324 // dispatch utility (taken from ranges-v3) | |
325 template<unsigned N> struct priority_tag : priority_tag < N - 1 > {}; | |
326 template<> struct priority_tag<0> {}; | |
327 | |
328 //////////////////////// | |
329 // has_/is_ functions // | |
330 //////////////////////// | |
331 | |
332 // source: https://stackoverflow.com/a/37193089/4116453 | |
333 | |
334 template <typename T, typename = void> | |
335 struct is_complete_type : std::false_type {}; | |
336 | |
337 template <typename T> | |
338 struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {}; | |
339 | |
389 NLOHMANN_JSON_HAS_HELPER(mapped_type); | 340 NLOHMANN_JSON_HAS_HELPER(mapped_type); |
390 NLOHMANN_JSON_HAS_HELPER(key_type); | 341 NLOHMANN_JSON_HAS_HELPER(key_type); |
391 NLOHMANN_JSON_HAS_HELPER(value_type); | 342 NLOHMANN_JSON_HAS_HELPER(value_type); |
392 NLOHMANN_JSON_HAS_HELPER(iterator); | 343 NLOHMANN_JSON_HAS_HELPER(iterator); |
393 | 344 |
394 #undef NLOHMANN_JSON_HAS_HELPER | |
395 | |
396 | |
397 template<bool B, class RealType, class CompatibleObjectType> | 345 template<bool B, class RealType, class CompatibleObjectType> |
398 struct is_compatible_object_type_impl : std::false_type {}; | 346 struct is_compatible_object_type_impl : std::false_type {}; |
399 | 347 |
400 template<class RealType, class CompatibleObjectType> | 348 template<class RealType, class CompatibleObjectType> |
401 struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType> | 349 struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType> |
402 { | 350 { |
403 static constexpr auto value = | 351 static constexpr auto value = |
404 std::is_constructible<typename RealType::key_type, | 352 std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and |
405 typename CompatibleObjectType::key_type>::value and | 353 std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value; |
406 std::is_constructible<typename RealType::mapped_type, | |
407 typename CompatibleObjectType::mapped_type>::value; | |
408 }; | 354 }; |
409 | 355 |
410 template<class BasicJsonType, class CompatibleObjectType> | 356 template<class BasicJsonType, class CompatibleObjectType> |
411 struct is_compatible_object_type | 357 struct is_compatible_object_type |
412 { | 358 { |
421 struct is_basic_json_nested_type | 367 struct is_basic_json_nested_type |
422 { | 368 { |
423 static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or | 369 static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or |
424 std::is_same<T, typename BasicJsonType::const_iterator>::value or | 370 std::is_same<T, typename BasicJsonType::const_iterator>::value or |
425 std::is_same<T, typename BasicJsonType::reverse_iterator>::value or | 371 std::is_same<T, typename BasicJsonType::reverse_iterator>::value or |
426 std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value or | 372 std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value; |
427 std::is_same<T, typename BasicJsonType::json_pointer>::value; | |
428 }; | 373 }; |
429 | 374 |
430 template<class BasicJsonType, class CompatibleArrayType> | 375 template<class BasicJsonType, class CompatibleArrayType> |
431 struct is_compatible_array_type | 376 struct is_compatible_array_type |
432 { | 377 { |
450 // is there an assert somewhere on overflows? | 395 // is there an assert somewhere on overflows? |
451 using RealLimits = std::numeric_limits<RealIntegerType>; | 396 using RealLimits = std::numeric_limits<RealIntegerType>; |
452 using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>; | 397 using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>; |
453 | 398 |
454 static constexpr auto value = | 399 static constexpr auto value = |
455 std::is_constructible<RealIntegerType, | 400 std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and |
456 CompatibleNumberIntegerType>::value and | |
457 CompatibleLimits::is_integer and | 401 CompatibleLimits::is_integer and |
458 RealLimits::is_signed == CompatibleLimits::is_signed; | 402 RealLimits::is_signed == CompatibleLimits::is_signed; |
459 }; | 403 }; |
460 | 404 |
461 template<typename RealIntegerType, typename CompatibleNumberIntegerType> | 405 template<typename RealIntegerType, typename CompatibleNumberIntegerType> |
465 is_compatible_integer_type_impl < | 409 is_compatible_integer_type_impl < |
466 std::is_integral<CompatibleNumberIntegerType>::value and | 410 std::is_integral<CompatibleNumberIntegerType>::value and |
467 not std::is_same<bool, CompatibleNumberIntegerType>::value, | 411 not std::is_same<bool, CompatibleNumberIntegerType>::value, |
468 RealIntegerType, CompatibleNumberIntegerType > ::value; | 412 RealIntegerType, CompatibleNumberIntegerType > ::value; |
469 }; | 413 }; |
470 | |
471 | 414 |
472 // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists | 415 // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists |
473 template<typename BasicJsonType, typename T> | 416 template<typename BasicJsonType, typename T> |
474 struct has_from_json | 417 struct has_from_json |
475 { | 418 { |
516 public: | 459 public: |
517 static constexpr bool value = std::is_integral<decltype(detect( | 460 static constexpr bool value = std::is_integral<decltype(detect( |
518 std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value; | 461 std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value; |
519 }; | 462 }; |
520 | 463 |
521 | 464 template <typename BasicJsonType, typename CompatibleCompleteType> |
522 ///////////// | 465 struct is_compatible_complete_type |
523 // to_json // | |
524 ///////////// | |
525 | |
526 template<typename BasicJsonType, typename T, enable_if_t< | |
527 std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0> | |
528 void to_json(BasicJsonType& j, T b) noexcept | |
529 { | 466 { |
530 external_constructor<value_t::boolean>::construct(j, b); | 467 static constexpr bool value = |
468 not std::is_base_of<std::istream, CompatibleCompleteType>::value and | |
469 not is_basic_json<CompatibleCompleteType>::value and | |
470 not is_basic_json_nested_type<BasicJsonType, CompatibleCompleteType>::value and | |
471 has_to_json<BasicJsonType, CompatibleCompleteType>::value; | |
472 }; | |
473 | |
474 template <typename BasicJsonType, typename CompatibleType> | |
475 struct is_compatible_type | |
476 : conjunction<is_complete_type<CompatibleType>, | |
477 is_compatible_complete_type<BasicJsonType, CompatibleType>> | |
478 { | |
479 }; | |
480 | |
481 // taken from ranges-v3 | |
482 template<typename T> | |
483 struct static_const | |
484 { | |
485 static constexpr T value{}; | |
486 }; | |
487 | |
488 template<typename T> | |
489 constexpr T static_const<T>::value; | |
531 } | 490 } |
532 | 491 } |
533 template<typename BasicJsonType, typename CompatibleString, | 492 |
534 enable_if_t<std::is_constructible<typename BasicJsonType::string_t, | 493 // #include <nlohmann/detail/exceptions.hpp> |
535 CompatibleString>::value, int> = 0> | 494 |
536 void to_json(BasicJsonType& j, const CompatibleString& s) | 495 |
496 #include <exception> // exception | |
497 #include <stdexcept> // runtime_error | |
498 #include <string> // to_string | |
499 | |
500 namespace nlohmann | |
537 { | 501 { |
538 external_constructor<value_t::string>::construct(j, s); | 502 namespace detail |
503 { | |
504 //////////////// | |
505 // exceptions // | |
506 //////////////// | |
507 | |
508 /*! | |
509 @brief general exception of the @ref basic_json class | |
510 | |
511 This class is an extension of `std::exception` objects with a member @a id for | |
512 exception ids. It is used as the base class for all exceptions thrown by the | |
513 @ref basic_json class. This class can hence be used as "wildcard" to catch | |
514 exceptions. | |
515 | |
516 Subclasses: | |
517 - @ref parse_error for exceptions indicating a parse error | |
518 - @ref invalid_iterator for exceptions indicating errors with iterators | |
519 - @ref type_error for exceptions indicating executing a member function with | |
520 a wrong type | |
521 - @ref out_of_range for exceptions indicating access out of the defined range | |
522 - @ref other_error for exceptions indicating other library errors | |
523 | |
524 @internal | |
525 @note To have nothrow-copy-constructible exceptions, we internally use | |
526 `std::runtime_error` which can cope with arbitrary-length error messages. | |
527 Intermediate strings are built with static functions and then passed to | |
528 the actual constructor. | |
529 @endinternal | |
530 | |
531 @liveexample{The following code shows how arbitrary library exceptions can be | |
532 caught.,exception} | |
533 | |
534 @since version 3.0.0 | |
535 */ | |
536 class exception : public std::exception | |
537 { | |
538 public: | |
539 /// returns the explanatory string | |
540 const char* what() const noexcept override | |
541 { | |
542 return m.what(); | |
543 } | |
544 | |
545 /// the id of the exception | |
546 const int id; | |
547 | |
548 protected: | |
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: | |
557 /// an exception object as storage for error messages | |
558 std::runtime_error m; | |
559 }; | |
560 | |
561 /*! | |
562 @brief exception indicating a parse error | |
563 | |
564 This exception is thrown by the library when a parse error occurs. Parse errors | |
565 can occur during the deserialization of JSON text, CBOR, MessagePack, as well | |
566 as when using JSON Patch. | |
567 | |
568 Member @a byte holds the byte index of the last read character in the input | |
569 file. | |
570 | |
571 Exceptions have ids 1xx. | |
572 | |
573 name / id | example message | description | |
574 ------------------------------ | --------------- | ------------------------- | |
575 json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. | |
576 json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. | |
577 json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. | |
578 json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. | |
579 json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. | |
580 json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. | |
581 json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. | |
582 json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. | |
583 json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. | |
584 json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. | |
585 json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. | |
586 json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. | |
587 | |
588 @note For an input with n bytes, 1 is the index of the first character and n+1 | |
589 is the index of the terminating null byte or the end of file. This also | |
590 holds true when reading a byte vector (CBOR or MessagePack). | |
591 | |
592 @liveexample{The following code shows how a `parse_error` exception can be | |
593 caught.,parse_error} | |
594 | |
595 @sa @ref exception for the base class of the library exceptions | |
596 @sa @ref invalid_iterator for exceptions indicating errors with iterators | |
597 @sa @ref type_error for exceptions indicating executing a member function with | |
598 a wrong type | |
599 @sa @ref out_of_range for exceptions indicating access out of the defined range | |
600 @sa @ref other_error for exceptions indicating other library errors | |
601 | |
602 @since version 3.0.0 | |
603 */ | |
604 class parse_error : public exception | |
605 { | |
606 public: | |
607 /*! | |
608 @brief create a parse error exception | |
609 @param[in] id_ the id of the exception | |
610 @param[in] byte_ the byte index where the error occurred (or 0 if the | |
611 position cannot be determined) | |
612 @param[in] what_arg the explanatory string | |
613 @return parse_error object | |
614 */ | |
615 static parse_error create(int id_, std::size_t byte_, const std::string& what_arg) | |
616 { | |
617 std::string w = exception::name("parse_error", id_) + "parse error" + | |
618 (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") + | |
619 ": " + what_arg; | |
620 return parse_error(id_, byte_, w.c_str()); | |
621 } | |
622 | |
623 /*! | |
624 @brief byte index of the parse error | |
625 | |
626 The byte index of the last read character in the input file. | |
627 | |
628 @note For an input with n bytes, 1 is the index of the first character and | |
629 n+1 is the index of the terminating null byte or the end of file. | |
630 This also holds true when reading a byte vector (CBOR or MessagePack). | |
631 */ | |
632 const std::size_t byte; | |
633 | |
634 private: | |
635 parse_error(int id_, std::size_t byte_, const char* what_arg) | |
636 : exception(id_, what_arg), byte(byte_) {} | |
637 }; | |
638 | |
639 /*! | |
640 @brief exception indicating errors with iterators | |
641 | |
642 This exception is thrown if iterators passed to a library function do not match | |
643 the expected semantics. | |
644 | |
645 Exceptions have ids 2xx. | |
646 | |
647 name / id | example message | description | |
648 ----------------------------------- | --------------- | ------------------------- | |
649 json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. | |
650 json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. | |
651 json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. | |
652 json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. | |
653 json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. | |
654 json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. | |
655 json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. | |
656 json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. | |
657 json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. | |
658 json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. | |
659 json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. | |
660 json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. | |
661 json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. | |
662 json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). | |
663 | |
664 @liveexample{The following code shows how an `invalid_iterator` exception can be | |
665 caught.,invalid_iterator} | |
666 | |
667 @sa @ref exception for the base class of the library exceptions | |
668 @sa @ref parse_error for exceptions indicating a parse error | |
669 @sa @ref type_error for exceptions indicating executing a member function with | |
670 a wrong type | |
671 @sa @ref out_of_range for exceptions indicating access out of the defined range | |
672 @sa @ref other_error for exceptions indicating other library errors | |
673 | |
674 @since version 3.0.0 | |
675 */ | |
676 class invalid_iterator : public exception | |
677 { | |
678 public: | |
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 | |
690 /*! | |
691 @brief exception indicating executing a member function with a wrong type | |
692 | |
693 This exception is thrown in case of a type error; that is, a library function is | |
694 executed on a JSON value whose type does not match the expected semantics. | |
695 | |
696 Exceptions have ids 3xx. | |
697 | |
698 name / id | example message | description | |
699 ----------------------------- | --------------- | ------------------------- | |
700 json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. | |
701 json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. | |
702 json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&. | |
703 json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. | |
704 json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. | |
705 json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. | |
706 json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. | |
707 json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. | |
708 json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. | |
709 json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. | |
710 json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. | |
711 json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. | |
712 json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. | |
713 json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. | |
714 json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. | |
715 json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | | |
716 | |
717 @liveexample{The following code shows how a `type_error` exception can be | |
718 caught.,type_error} | |
719 | |
720 @sa @ref exception for the base class of the library exceptions | |
721 @sa @ref parse_error for exceptions indicating a parse error | |
722 @sa @ref invalid_iterator for exceptions indicating errors with iterators | |
723 @sa @ref out_of_range for exceptions indicating access out of the defined range | |
724 @sa @ref other_error for exceptions indicating other library errors | |
725 | |
726 @since version 3.0.0 | |
727 */ | |
728 class type_error : public exception | |
729 { | |
730 public: | |
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 | |
741 /*! | |
742 @brief exception indicating access out of the defined range | |
743 | |
744 This exception is thrown in case a library function is called on an input | |
745 parameter that exceeds the expected range, for instance in case of array | |
746 indices or nonexisting object keys. | |
747 | |
748 Exceptions have ids 4xx. | |
749 | |
750 name / id | example message | description | |
751 ------------------------------- | --------------- | ------------------------- | |
752 json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. | |
753 json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. | |
754 json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. | |
755 json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. | |
756 json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. | |
757 json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. | |
758 json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON only supports integers numbers up to 9223372036854775807. | | |
759 json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | | |
760 | |
761 @liveexample{The following code shows how an `out_of_range` exception can be | |
762 caught.,out_of_range} | |
763 | |
764 @sa @ref exception for the base class of the library exceptions | |
765 @sa @ref parse_error for exceptions indicating a parse error | |
766 @sa @ref invalid_iterator for exceptions indicating errors with iterators | |
767 @sa @ref type_error for exceptions indicating executing a member function with | |
768 a wrong type | |
769 @sa @ref other_error for exceptions indicating other library errors | |
770 | |
771 @since version 3.0.0 | |
772 */ | |
773 class out_of_range : public exception | |
774 { | |
775 public: | |
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 | |
786 /*! | |
787 @brief exception indicating other library errors | |
788 | |
789 This exception is thrown in case of errors that cannot be classified with the | |
790 other exception types. | |
791 | |
792 Exceptions have ids 5xx. | |
793 | |
794 name / id | example message | description | |
795 ------------------------------ | --------------- | ------------------------- | |
796 json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. | |
797 | |
798 @sa @ref exception for the base class of the library exceptions | |
799 @sa @ref parse_error for exceptions indicating a parse error | |
800 @sa @ref invalid_iterator for exceptions indicating errors with iterators | |
801 @sa @ref type_error for exceptions indicating executing a member function with | |
802 a wrong type | |
803 @sa @ref out_of_range for exceptions indicating access out of the defined range | |
804 | |
805 @liveexample{The following code shows how an `other_error` exception can be | |
806 caught.,other_error} | |
807 | |
808 @since version 3.0.0 | |
809 */ | |
810 class other_error : public exception | |
811 { | |
812 public: | |
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 }; | |
539 } | 822 } |
540 | 823 } |
541 template<typename BasicJsonType, typename FloatType, | 824 |
542 enable_if_t<std::is_floating_point<FloatType>::value, int> = 0> | 825 // #include <nlohmann/detail/value_t.hpp> |
543 void to_json(BasicJsonType& j, FloatType val) noexcept | 826 |
827 | |
828 #include <array> // array | |
829 #include <ciso646> // and | |
830 #include <cstddef> // size_t | |
831 #include <cstdint> // uint8_t | |
832 | |
833 namespace nlohmann | |
544 { | 834 { |
545 external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val)); | 835 namespace detail |
836 { | |
837 /////////////////////////// | |
838 // JSON type enumeration // | |
839 /////////////////////////// | |
840 | |
841 /*! | |
842 @brief the JSON type enumeration | |
843 | |
844 This enumeration collects the different JSON types. It is internally used to | |
845 distinguish the stored values, and the functions @ref basic_json::is_null(), | |
846 @ref basic_json::is_object(), @ref basic_json::is_array(), | |
847 @ref basic_json::is_string(), @ref basic_json::is_boolean(), | |
848 @ref basic_json::is_number() (with @ref basic_json::is_number_integer(), | |
849 @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), | |
850 @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and | |
851 @ref basic_json::is_structured() rely on it. | |
852 | |
853 @note There are three enumeration entries (number_integer, number_unsigned, and | |
854 number_float), because the library distinguishes these three types for numbers: | |
855 @ref basic_json::number_unsigned_t is used for unsigned integers, | |
856 @ref basic_json::number_integer_t is used for signed integers, and | |
857 @ref basic_json::number_float_t is used for floating-point numbers or to | |
858 approximate integers which do not fit in the limits of their respective type. | |
859 | |
860 @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON | |
861 value with the default value for a given type | |
862 | |
863 @since version 1.0.0 | |
864 */ | |
865 enum class value_t : std::uint8_t | |
866 { | |
867 null, ///< null value | |
868 object, ///< object (unordered set of name/value pairs) | |
869 array, ///< array (ordered collection of values) | |
870 string, ///< string value | |
871 boolean, ///< boolean value | |
872 number_integer, ///< number value (signed integer) | |
873 number_unsigned, ///< number value (unsigned integer) | |
874 number_float, ///< number value (floating-point) | |
875 discarded ///< discarded by the the parser callback function | |
876 }; | |
877 | |
878 /*! | |
879 @brief comparison operator for JSON types | |
880 | |
881 Returns an ordering that is similar to Python: | |
882 - order: null < boolean < number < object < array < string | |
883 - furthermore, each type is not smaller than itself | |
884 - discarded values are not comparable | |
885 | |
886 @since version 1.0.0 | |
887 */ | |
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]; | |
546 } | 899 } |
547 | 900 } |
548 template < | 901 } |
549 typename BasicJsonType, typename CompatibleNumberUnsignedType, | 902 |
550 enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, | 903 // #include <nlohmann/detail/conversions/from_json.hpp> |
551 CompatibleNumberUnsignedType>::value, int> = 0 > | 904 |
552 void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept | 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 | |
553 { | 927 { |
554 external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val)); | 928 namespace detail |
555 } | |
556 | |
557 template < | |
558 typename BasicJsonType, typename CompatibleNumberIntegerType, | |
559 enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, | |
560 CompatibleNumberIntegerType>::value, int> = 0 > | |
561 void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept | |
562 { | 929 { |
563 external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val)); | |
564 } | |
565 | |
566 template<typename BasicJsonType, typename UnscopedEnumType, | |
567 enable_if_t<is_unscoped_enum<UnscopedEnumType>::value, int> = 0> | |
568 void to_json(BasicJsonType& j, UnscopedEnumType e) noexcept | |
569 { | |
570 external_constructor<value_t::number_integer>::construct(j, e); | |
571 } | |
572 | |
573 template < | |
574 typename BasicJsonType, typename CompatibleArrayType, | |
575 enable_if_t < | |
576 is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or | |
577 std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, | |
578 int > = 0 > | |
579 void to_json(BasicJsonType& j, const CompatibleArrayType& arr) | |
580 { | |
581 external_constructor<value_t::array>::construct(j, arr); | |
582 } | |
583 | |
584 template < | |
585 typename BasicJsonType, typename CompatibleObjectType, | |
586 enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, | |
587 int> = 0 > | |
588 void to_json(BasicJsonType& j, const CompatibleObjectType& arr) | |
589 { | |
590 external_constructor<value_t::object>::construct(j, arr); | |
591 } | |
592 | |
593 | |
594 /////////////// | |
595 // from_json // | |
596 /////////////// | |
597 | |
598 // overloads for basic_json template parameters | 930 // overloads for basic_json template parameters |
599 template<typename BasicJsonType, typename ArithmeticType, | 931 template<typename BasicJsonType, typename ArithmeticType, |
600 enable_if_t<std::is_arithmetic<ArithmeticType>::value and | 932 enable_if_t<std::is_arithmetic<ArithmeticType>::value and |
601 not std::is_same<ArithmeticType, | 933 not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, |
602 typename BasicJsonType::boolean_t>::value, | |
603 int> = 0> | 934 int> = 0> |
604 void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) | 935 void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) |
605 { | 936 { |
606 switch (static_cast<value_t>(j)) | 937 switch (static_cast<value_t>(j)) |
607 { | 938 { |
608 case value_t::number_unsigned: | 939 case value_t::number_unsigned: |
609 { | 940 { |
610 val = static_cast<ArithmeticType>( | 941 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>()); |
611 *j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>()); | |
612 break; | 942 break; |
613 } | 943 } |
614 case value_t::number_integer: | 944 case value_t::number_integer: |
615 { | 945 { |
616 val = static_cast<ArithmeticType>( | 946 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); |
617 *j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); | |
618 break; | 947 break; |
619 } | 948 } |
620 case value_t::number_float: | 949 case value_t::number_float: |
621 { | 950 { |
622 val = static_cast<ArithmeticType>( | 951 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>()); |
623 *j.template get_ptr<const typename BasicJsonType::number_float_t*>()); | |
624 break; | 952 break; |
625 } | 953 } |
954 | |
626 default: | 955 default: |
627 { | 956 JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); |
628 JSON_THROW( | |
629 std::domain_error("type must be number, but is " + j.type_name())); | |
630 } | |
631 } | 957 } |
632 } | 958 } |
633 | 959 |
634 template<typename BasicJsonType> | 960 template<typename BasicJsonType> |
635 void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) | 961 void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) |
636 { | 962 { |
637 if (not j.is_boolean()) | 963 if (JSON_UNLIKELY(not j.is_boolean())) |
638 { | 964 { |
639 JSON_THROW(std::domain_error("type must be boolean, but is " + j.type_name())); | 965 JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()))); |
640 } | 966 } |
641 b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>(); | 967 b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>(); |
642 } | 968 } |
643 | 969 |
644 template<typename BasicJsonType> | 970 template<typename BasicJsonType> |
645 void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) | 971 void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) |
646 { | 972 { |
647 if (not j.is_string()) | 973 if (JSON_UNLIKELY(not j.is_string())) |
648 { | 974 { |
649 JSON_THROW(std::domain_error("type must be string, but is " + j.type_name())); | 975 JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()))); |
650 } | 976 } |
651 s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); | 977 s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); |
652 } | 978 } |
653 | 979 |
654 template<typename BasicJsonType> | 980 template<typename BasicJsonType> |
667 void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) | 993 void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) |
668 { | 994 { |
669 get_arithmetic_value(j, val); | 995 get_arithmetic_value(j, val); |
670 } | 996 } |
671 | 997 |
672 template<typename BasicJsonType, typename UnscopedEnumType, | 998 template<typename BasicJsonType, typename EnumType, |
673 enable_if_t<is_unscoped_enum<UnscopedEnumType>::value, int> = 0> | 999 enable_if_t<std::is_enum<EnumType>::value, int> = 0> |
674 void from_json(const BasicJsonType& j, UnscopedEnumType& e) | 1000 void from_json(const BasicJsonType& j, EnumType& e) |
675 { | 1001 { |
676 typename std::underlying_type<UnscopedEnumType>::type val; | 1002 typename std::underlying_type<EnumType>::type val; |
677 get_arithmetic_value(j, val); | 1003 get_arithmetic_value(j, val); |
678 e = static_cast<UnscopedEnumType>(val); | 1004 e = static_cast<EnumType>(val); |
679 } | 1005 } |
680 | 1006 |
681 template<typename BasicJsonType> | 1007 template<typename BasicJsonType> |
682 void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr) | 1008 void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr) |
683 { | 1009 { |
684 if (not j.is_array()) | 1010 if (JSON_UNLIKELY(not j.is_array())) |
685 { | 1011 { |
686 JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); | 1012 JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); |
687 } | 1013 } |
688 arr = *j.template get_ptr<const typename BasicJsonType::array_t*>(); | 1014 arr = *j.template get_ptr<const typename BasicJsonType::array_t*>(); |
689 } | 1015 } |
690 | 1016 |
691 // forward_list doesn't have an insert method | 1017 // forward_list doesn't have an insert method |
692 template<typename BasicJsonType, typename T, typename Allocator> | 1018 template<typename BasicJsonType, typename T, typename Allocator, |
1019 enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0> | |
693 void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l) | 1020 void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l) |
694 { | 1021 { |
695 // do not perform the check when user wants to retrieve jsons | 1022 if (JSON_UNLIKELY(not j.is_array())) |
696 // (except when it's null.. ?) | 1023 { |
697 if (j.is_null()) | 1024 JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); |
698 { | 1025 } |
699 JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); | 1026 std::transform(j.rbegin(), j.rend(), |
700 } | 1027 std::front_inserter(l), [](const BasicJsonType & i) |
701 if (not std::is_same<T, BasicJsonType>::value) | 1028 { |
702 { | 1029 return i.template get<T>(); |
703 if (not j.is_array()) | 1030 }); |
704 { | |
705 JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); | |
706 } | |
707 } | |
708 for (auto it = j.rbegin(), end = j.rend(); it != end; ++it) | |
709 { | |
710 l.push_front(it->template get<T>()); | |
711 } | |
712 } | 1031 } |
713 | 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 | |
714 template<typename BasicJsonType, typename CompatibleArrayType> | 1046 template<typename BasicJsonType, typename CompatibleArrayType> |
715 void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0>) | 1047 void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/) |
716 { | 1048 { |
717 using std::begin; | |
718 using std::end; | 1049 using std::end; |
719 | 1050 |
720 std::transform(j.begin(), j.end(), | 1051 std::transform(j.begin(), j.end(), |
721 std::inserter(arr, end(arr)), [](const BasicJsonType & i) | 1052 std::inserter(arr, end(arr)), [](const BasicJsonType & i) |
722 { | 1053 { |
725 return i.template get<typename CompatibleArrayType::value_type>(); | 1056 return i.template get<typename CompatibleArrayType::value_type>(); |
726 }); | 1057 }); |
727 } | 1058 } |
728 | 1059 |
729 template<typename BasicJsonType, typename CompatibleArrayType> | 1060 template<typename BasicJsonType, typename CompatibleArrayType> |
730 auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1>) | 1061 auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/) |
731 -> decltype( | 1062 -> decltype( |
732 arr.reserve(std::declval<typename CompatibleArrayType::size_type>()), | 1063 arr.reserve(std::declval<typename CompatibleArrayType::size_type>()), |
733 void()) | 1064 void()) |
734 { | 1065 { |
735 using std::begin; | |
736 using std::end; | 1066 using std::end; |
737 | 1067 |
738 arr.reserve(j.size()); | 1068 arr.reserve(j.size()); |
739 std::transform( | 1069 std::transform(j.begin(), j.end(), |
740 j.begin(), j.end(), std::inserter(arr, end(arr)), [](const BasicJsonType & i) | 1070 std::inserter(arr, end(arr)), [](const BasicJsonType & i) |
741 { | 1071 { |
742 // get<BasicJsonType>() returns *this, this won't call a from_json | 1072 // get<BasicJsonType>() returns *this, this won't call a from_json |
743 // method when value_type is BasicJsonType | 1073 // method when value_type is BasicJsonType |
744 return i.template get<typename CompatibleArrayType::value_type>(); | 1074 return i.template get<typename CompatibleArrayType::value_type>(); |
745 }); | 1075 }); |
746 } | 1076 } |
747 | 1077 |
748 template<typename BasicJsonType, typename CompatibleArrayType, | 1078 template<typename BasicJsonType, typename T, std::size_t N> |
749 enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and | 1079 void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/) |
750 not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0> | 1080 { |
1081 for (std::size_t i = 0; i < N; ++i) | |
1082 { | |
1083 arr[i] = j.at(i).template get<T>(); | |
1084 } | |
1085 } | |
1086 | |
1087 template < | |
1088 typename BasicJsonType, typename CompatibleArrayType, | |
1089 enable_if_t < | |
1090 is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and | |
1091 not std::is_same<typename BasicJsonType::array_t, | |
1092 CompatibleArrayType>::value and | |
1093 std::is_constructible < | |
1094 BasicJsonType, typename CompatibleArrayType::value_type >::value, | |
1095 int > = 0 > | |
751 void from_json(const BasicJsonType& j, CompatibleArrayType& arr) | 1096 void from_json(const BasicJsonType& j, CompatibleArrayType& arr) |
752 { | 1097 { |
753 if (j.is_null()) | 1098 if (JSON_UNLIKELY(not j.is_array())) |
754 { | 1099 { |
755 JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); | 1100 JSON_THROW(type_error::create(302, "type must be array, but is " + |
756 } | 1101 std::string(j.type_name()))); |
757 | 1102 } |
758 // when T == BasicJsonType, do not check if value_t is correct | 1103 |
759 if (not std::is_same<typename CompatibleArrayType::value_type, BasicJsonType>::value) | 1104 from_json_array_impl(j, arr, priority_tag<2> {}); |
760 { | |
761 if (not j.is_array()) | |
762 { | |
763 JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); | |
764 } | |
765 } | |
766 from_json_array_impl(j, arr, priority_tag<1> {}); | |
767 } | 1105 } |
768 | 1106 |
769 template<typename BasicJsonType, typename CompatibleObjectType, | 1107 template<typename BasicJsonType, typename CompatibleObjectType, |
770 enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0> | 1108 enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0> |
771 void from_json(const BasicJsonType& j, CompatibleObjectType& obj) | 1109 void from_json(const BasicJsonType& j, CompatibleObjectType& obj) |
772 { | 1110 { |
773 if (not j.is_object()) | 1111 if (JSON_UNLIKELY(not j.is_object())) |
774 { | 1112 { |
775 JSON_THROW(std::domain_error("type must be object, but is " + j.type_name())); | 1113 JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()))); |
776 } | 1114 } |
777 | 1115 |
778 auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>(); | 1116 auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>(); |
779 using std::begin; | 1117 using value_type = typename CompatibleObjectType::value_type; |
780 using std::end; | 1118 std::transform( |
781 // we could avoid the assignment, but this might require a for loop, which | 1119 inner_object->begin(), inner_object->end(), |
782 // might be less efficient than the container constructor for some | 1120 std::inserter(obj, obj.begin()), |
783 // containers (would it?) | 1121 [](typename BasicJsonType::object_t::value_type const & p) |
784 obj = CompatibleObjectType(begin(*inner_object), end(*inner_object)); | 1122 { |
1123 return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>()); | |
1124 }); | |
785 } | 1125 } |
786 | 1126 |
787 // overload for arithmetic types, not chosen for basic_json template arguments | 1127 // overload for arithmetic types, not chosen for basic_json template arguments |
788 // (BooleanType, etc..); note: Is it really necessary to provide explicit | 1128 // (BooleanType, etc..); note: Is it really necessary to provide explicit |
789 // overloads for boolean_t etc. in case of a custom BooleanType which is not | 1129 // overloads for boolean_t etc. in case of a custom BooleanType which is not |
818 case value_t::boolean: | 1158 case value_t::boolean: |
819 { | 1159 { |
820 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>()); | 1160 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>()); |
821 break; | 1161 break; |
822 } | 1162 } |
1163 | |
823 default: | 1164 default: |
824 { | 1165 JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); |
825 JSON_THROW(std::domain_error("type must be number, but is " + j.type_name())); | 1166 } |
826 } | 1167 } |
827 } | 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 | |
1187 struct from_json_fn | |
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 | |
1221 /// namespace to hold default `from_json` function | |
1222 /// to see why this is required: | |
1223 /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html | |
1224 namespace | |
1225 { | |
1226 constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; | |
1227 } | |
1228 } | |
1229 | |
1230 // #include <nlohmann/detail/conversions/to_json.hpp> | |
1231 | |
1232 | |
1233 #include <ciso646> // or, and, not | |
1234 #include <iterator> // begin, end | |
1235 #include <tuple> // tuple, get | |
1236 #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type | |
1237 #include <utility> // move, forward, declval, pair | |
1238 #include <valarray> // valarray | |
1239 #include <vector> // vector | |
1240 | |
1241 // #include <nlohmann/detail/meta.hpp> | |
1242 | |
1243 // #include <nlohmann/detail/value_t.hpp> | |
1244 | |
1245 | |
1246 namespace nlohmann | |
1247 { | |
1248 namespace detail | |
1249 { | |
1250 ////////////////// | |
1251 // constructors // | |
1252 ////////////////// | |
1253 | |
1254 template<value_t> struct external_constructor; | |
1255 | |
1256 template<> | |
1257 struct external_constructor<value_t::boolean> | |
1258 { | |
1259 template<typename BasicJsonType> | |
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<> | |
1269 struct external_constructor<value_t::string> | |
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<> | |
1289 struct external_constructor<value_t::number_float> | |
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<> | |
1301 struct external_constructor<value_t::number_unsigned> | |
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<> | |
1313 struct external_constructor<value_t::number_integer> | |
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<> | |
1325 struct external_constructor<value_t::array> | |
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<> | |
1381 struct external_constructor<value_t::object> | |
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 | |
1412 ///////////// | |
1413 // to_json // | |
1414 ///////////// | |
1415 | |
1416 template<typename BasicJsonType, typename T, | |
1417 enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0> | |
1418 void to_json(BasicJsonType& j, T b) noexcept | |
1419 { | |
1420 external_constructor<value_t::boolean>::construct(j, b); | |
1421 } | |
1422 | |
1423 template<typename BasicJsonType, typename CompatibleString, | |
1424 enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0> | |
1425 void to_json(BasicJsonType& j, const CompatibleString& s) | |
1426 { | |
1427 external_constructor<value_t::string>::construct(j, s); | |
1428 } | |
1429 | |
1430 template<typename BasicJsonType> | |
1431 void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) | |
1432 { | |
1433 external_constructor<value_t::string>::construct(j, std::move(s)); | |
1434 } | |
1435 | |
1436 template<typename BasicJsonType, typename FloatType, | |
1437 enable_if_t<std::is_floating_point<FloatType>::value, int> = 0> | |
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 { | |
1468 external_constructor<value_t::array>::construct(j, e); | |
1469 } | |
1470 | |
1471 template<typename BasicJsonType, typename CompatibleArrayType, | |
1472 enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or | |
1473 std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, | |
1474 int> = 0> | |
1475 void to_json(BasicJsonType& j, const CompatibleArrayType& arr) | |
1476 { | |
1477 external_constructor<value_t::array>::construct(j, arr); | |
1478 } | |
1479 | |
1480 template<typename BasicJsonType, typename T, | |
1481 enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0> | |
1482 void to_json(BasicJsonType& j, std::valarray<T> arr) | |
1483 { | |
1484 external_constructor<value_t::array>::construct(j, std::move(arr)); | |
1485 } | |
1486 | |
1487 template<typename BasicJsonType> | |
1488 void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) | |
1489 { | |
1490 external_constructor<value_t::array>::construct(j, std::move(arr)); | |
1491 } | |
1492 | |
1493 template<typename BasicJsonType, typename CompatibleObjectType, | |
1494 enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0> | |
1495 void to_json(BasicJsonType& j, const CompatibleObjectType& obj) | |
1496 { | |
1497 external_constructor<value_t::object>::construct(j, obj); | |
1498 } | |
1499 | |
1500 template<typename BasicJsonType> | |
1501 void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) | |
1502 { | |
1503 external_constructor<value_t::object>::construct(j, std::move(obj)); | |
1504 } | |
1505 | |
1506 template<typename BasicJsonType, typename T, std::size_t N, | |
1507 enable_if_t<not std::is_constructible<typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0> | |
1508 void to_json(BasicJsonType& j, T (&arr)[N]) | |
1509 { | |
1510 external_constructor<value_t::array>::construct(j, arr); | |
1511 } | |
1512 | |
1513 template<typename BasicJsonType, typename... Args> | |
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...> {}); | |
828 } | 1529 } |
829 | 1530 |
830 struct to_json_fn | 1531 struct to_json_fn |
831 { | 1532 { |
832 private: | 1533 private: |
833 template<typename BasicJsonType, typename T> | 1534 template<typename BasicJsonType, typename T> |
834 auto call(BasicJsonType& j, T&& val, priority_tag<1>) const noexcept(noexcept(to_json(j, std::forward<T>(val)))) | 1535 auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val)))) |
835 -> decltype(to_json(j, std::forward<T>(val)), void()) | 1536 -> decltype(to_json(j, std::forward<T>(val)), void()) |
836 { | 1537 { |
837 return to_json(j, std::forward<T>(val)); | 1538 return to_json(j, std::forward<T>(val)); |
838 } | 1539 } |
839 | 1540 |
840 template<typename BasicJsonType, typename T> | 1541 template<typename BasicJsonType, typename T> |
841 void call(BasicJsonType&, T&&, priority_tag<0>) const noexcept | 1542 void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept |
842 { | 1543 { |
843 static_assert(sizeof(BasicJsonType) == 0, | 1544 static_assert(sizeof(BasicJsonType) == 0, |
844 "could not find to_json() method in T's namespace"); | 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 | |
845 } | 1553 } |
846 | 1554 |
847 public: | 1555 public: |
848 template<typename BasicJsonType, typename T> | 1556 template<typename BasicJsonType, typename T> |
849 void operator()(BasicJsonType& j, T&& val) const | 1557 void operator()(BasicJsonType& j, T&& val) const |
850 noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {}))) | 1558 noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {}))) |
851 { | 1559 { |
852 return call(j, std::forward<T>(val), priority_tag<1> {}); | 1560 return call(j, std::forward<T>(val), priority_tag<1> {}); |
853 } | 1561 } |
854 }; | 1562 }; |
855 | 1563 } |
856 struct from_json_fn | 1564 |
857 { | 1565 /// namespace to hold default `to_json` function |
858 private: | |
859 template<typename BasicJsonType, typename T> | |
860 auto call(const BasicJsonType& j, T& val, priority_tag<1>) const | |
861 noexcept(noexcept(from_json(j, val))) | |
862 -> decltype(from_json(j, val), void()) | |
863 { | |
864 return from_json(j, val); | |
865 } | |
866 | |
867 template<typename BasicJsonType, typename T> | |
868 void call(const BasicJsonType&, T&, priority_tag<0>) const noexcept | |
869 { | |
870 static_assert(sizeof(BasicJsonType) == 0, | |
871 "could not find from_json() method in T's namespace"); | |
872 } | |
873 | |
874 public: | |
875 template<typename BasicJsonType, typename T> | |
876 void operator()(const BasicJsonType& j, T& val) const | |
877 noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {}))) | |
878 { | |
879 return call(j, val, priority_tag<1> {}); | |
880 } | |
881 }; | |
882 | |
883 // taken from ranges-v3 | |
884 template<typename T> | |
885 struct static_const | |
886 { | |
887 static constexpr T value{}; | |
888 }; | |
889 | |
890 template<typename T> | |
891 constexpr T static_const<T>::value; | |
892 } // namespace detail | |
893 | |
894 | |
895 /// namespace to hold default `to_json` / `from_json` functions | |
896 namespace | 1566 namespace |
897 { | 1567 { |
898 constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value; | 1568 constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value; |
899 constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; | |
900 } | 1569 } |
901 | 1570 } |
1571 | |
1572 // #include <nlohmann/detail/input/input_adapters.hpp> | |
1573 | |
1574 | |
1575 #include <algorithm> // min | |
1576 #include <array> // array | |
1577 #include <cassert> // assert | |
1578 #include <cstddef> // size_t | |
1579 #include <cstring> // strlen | |
1580 #include <ios> // streamsize, streamoff, streampos | |
1581 #include <istream> // istream | |
1582 #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next | |
1583 #include <memory> // shared_ptr, make_shared, addressof | |
1584 #include <numeric> // accumulate | |
1585 #include <string> // string, char_traits | |
1586 #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer | |
1587 #include <utility> // pair, declval | |
1588 | |
1589 // #include <nlohmann/detail/macro_scope.hpp> | |
1590 | |
1591 | |
1592 namespace nlohmann | |
1593 { | |
1594 namespace detail | |
1595 { | |
1596 //////////////////// | |
1597 // input adapters // | |
1598 //////////////////// | |
902 | 1599 |
903 /*! | 1600 /*! |
904 @brief default JSONSerializer template argument | 1601 @brief abstract input adapter interface |
905 | 1602 |
906 This serializer ignores the template arguments and uses ADL | 1603 Produces a stream of std::char_traits<char>::int_type characters from a |
907 ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl)) | 1604 std::istream, a buffer, or some other input type. Accepts the return of exactly |
908 for serialization. | 1605 one non-EOF character for future input. The int_type characters returned |
1606 consist of all valid char values as positive values (typically unsigned char), | |
1607 plus an EOF value outside that range, specified by the value of the function | |
1608 std::char_traits<char>::eof(). This value is typically -1, but could be any | |
1609 arbitrary value which is not a valid char value. | |
909 */ | 1610 */ |
910 template<typename = void, typename = void> | 1611 struct input_adapter_protocol |
1612 { | |
1613 /// get a character [0,255] or std::char_traits<char>::eof(). | |
1614 virtual std::char_traits<char>::int_type get_character() = 0; | |
1615 /// restore the last non-eof() character to input | |
1616 virtual void unget_character() = 0; | |
1617 virtual ~input_adapter_protocol() = default; | |
1618 }; | |
1619 | |
1620 /// a type to simplify interfaces | |
1621 using input_adapter_t = std::shared_ptr<input_adapter_protocol>; | |
1622 | |
1623 /*! | |
1624 Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at | |
1625 beginning of input. Does not support changing the underlying std::streambuf | |
1626 in mid-input. Maintains underlying std::istream and std::streambuf to support | |
1627 subsequent use of standard std::istream operations to process any input | |
1628 characters following those used in parsing the JSON input. Clears the | |
1629 std::istream flags; any input errors (e.g., EOF) will be detected by the first | |
1630 subsequent call for input from the std::istream. | |
1631 */ | |
1632 class input_stream_adapter : public input_adapter_protocol | |
1633 { | |
1634 public: | |
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: | |
1691 /// the associated input stream | |
1692 std::istream& is; | |
1693 std::streambuf& sb; | |
1694 }; | |
1695 | |
1696 /// input adapter for buffer input | |
1697 class input_buffer_adapter : public input_adapter_protocol | |
1698 { | |
1699 public: | |
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: | |
1733 /// pointer to the current character | |
1734 const char* cursor; | |
1735 /// pointer past the last character | |
1736 const char* limit; | |
1737 /// pointer to the first character | |
1738 const char* start; | |
1739 }; | |
1740 | |
1741 class input_adapter | |
1742 { | |
1743 public: | |
1744 // native support | |
1745 | |
1746 /// input adapter for input stream | |
1747 input_adapter(std::istream& i) | |
1748 : ia(std::make_shared<input_stream_adapter>(i)) {} | |
1749 | |
1750 /// input adapter for input stream | |
1751 input_adapter(std::istream&& i) | |
1752 : ia(std::make_shared<input_stream_adapter>(i)) {} | |
1753 | |
1754 /// input adapter for buffer | |
1755 template<typename CharT, | |
1756 typename std::enable_if< | |
1757 std::is_pointer<CharT>::value and | |
1758 std::is_integral<typename std::remove_pointer<CharT>::type>::value and | |
1759 sizeof(typename std::remove_pointer<CharT>::type) == 1, | |
1760 int>::type = 0> | |
1761 input_adapter(CharT b, std::size_t l) | |
1762 : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {} | |
1763 | |
1764 // derived support | |
1765 | |
1766 /// input adapter for string literal | |
1767 template<typename CharT, | |
1768 typename std::enable_if< | |
1769 std::is_pointer<CharT>::value and | |
1770 std::is_integral<typename std::remove_pointer<CharT>::type>::value and | |
1771 sizeof(typename std::remove_pointer<CharT>::type) == 1, | |
1772 int>::type = 0> | |
1773 input_adapter(CharT b) | |
1774 : input_adapter(reinterpret_cast<const char*>(b), | |
1775 std::strlen(reinterpret_cast<const char*>(b))) {} | |
1776 | |
1777 /// input adapter for iterator range with contiguous storage | |
1778 template<class IteratorType, | |
1779 typename std::enable_if< | |
1780 std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value, | |
1781 int>::type = 0> | |
1782 input_adapter(IteratorType first, IteratorType last) | |
1783 { | |
1784 // assertion to check that the iterator range is indeed contiguous, | |
1785 // see http://stackoverflow.com/a/35008842/266378 for more discussion | |
1786 assert(std::accumulate( | |
1787 first, last, std::pair<bool, int>(true, 0), | |
1788 [&first](std::pair<bool, int> res, decltype(*first) val) | |
1789 { | |
1790 res.first &= (val == *(std::next(std::addressof(*first), res.second++))); | |
1791 return res; | |
1792 }).first); | |
1793 | |
1794 // assertion to check that each element is 1 byte long | |
1795 static_assert( | |
1796 sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1, | |
1797 "each element in the iterator range must have the size of 1 byte"); | |
1798 | |
1799 const auto len = static_cast<size_t>(std::distance(first, last)); | |
1800 if (JSON_LIKELY(len > 0)) | |
1801 { | |
1802 // there is at least one element: use the address of first | |
1803 ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len); | |
1804 } | |
1805 else | |
1806 { | |
1807 // the address of first cannot be used: use nullptr | |
1808 ia = std::make_shared<input_buffer_adapter>(nullptr, len); | |
1809 } | |
1810 } | |
1811 | |
1812 /// input adapter for array | |
1813 template<class T, std::size_t N> | |
1814 input_adapter(T (&array)[N]) | |
1815 : input_adapter(std::begin(array), std::end(array)) {} | |
1816 | |
1817 /// input adapter for contiguous container | |
1818 template<class ContiguousContainer, typename | |
1819 std::enable_if<not std::is_pointer<ContiguousContainer>::value and | |
1820 std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value, | |
1821 int>::type = 0> | |
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: | |
1831 /// the actual adapter | |
1832 input_adapter_t ia = nullptr; | |
1833 }; | |
1834 } | |
1835 } | |
1836 | |
1837 // #include <nlohmann/detail/input/lexer.hpp> | |
1838 | |
1839 | |
1840 #include <clocale> // localeconv | |
1841 #include <cstddef> // size_t | |
1842 #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull | |
1843 #include <initializer_list> // initializer_list | |
1844 #include <ios> // hex, uppercase | |
1845 #include <iomanip> // setw, setfill | |
1846 #include <sstream> // stringstream | |
1847 #include <string> // char_traits, string | |
1848 #include <vector> // vector | |
1849 | |
1850 // #include <nlohmann/detail/macro_scope.hpp> | |
1851 | |
1852 // #include <nlohmann/detail/input/input_adapters.hpp> | |
1853 | |
1854 | |
1855 namespace nlohmann | |
1856 { | |
1857 namespace detail | |
1858 { | |
1859 /////////// | |
1860 // lexer // | |
1861 /////////// | |
1862 | |
1863 /*! | |
1864 @brief lexical analysis | |
1865 | |
1866 This class organizes the lexical analysis during JSON deserialization. | |
1867 */ | |
1868 template<typename BasicJsonType> | |
1869 class lexer | |
1870 { | |
1871 using number_integer_t = typename BasicJsonType::number_integer_t; | |
1872 using number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
1873 using number_float_t = typename BasicJsonType::number_float_t; | |
1874 using string_t = typename BasicJsonType::string_t; | |
1875 | |
1876 public: | |
1877 /// token types for the parser | |
1878 enum class token_type | |
1879 { | |
1880 uninitialized, ///< indicating the scanner is uninitialized | |
1881 literal_true, ///< the `true` literal | |
1882 literal_false, ///< the `false` literal | |
1883 literal_null, ///< the `null` literal | |
1884 value_string, ///< a string -- use get_string() for actual value | |
1885 value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value | |
1886 value_integer, ///< a signed integer -- use get_number_integer() for actual value | |
1887 value_float, ///< an floating point number -- use get_number_float() for actual value | |
1888 begin_array, ///< the character for array begin `[` | |
1889 begin_object, ///< the character for object begin `{` | |
1890 end_array, ///< the character for array end `]` | |
1891 end_object, ///< the character for object end `}` | |
1892 name_separator, ///< the name separator `:` | |
1893 value_separator, ///< the value separator `,` | |
1894 parse_error, ///< indicating a parse error | |
1895 end_of_input, ///< indicating the end of the input buffer | |
1896 literal_or_value ///< a literal or the begin of a value (only for diagnostics) | |
1897 }; | |
1898 | |
1899 /// return name of values of type token_type (only used for errors) | |
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"; | |
1914 case lexer::token_type::value_unsigned: | |
1915 case lexer::token_type::value_integer: | |
1916 case lexer::token_type::value_float: | |
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: | |
1949 ///////////////////// | |
1950 // locales | |
1951 ///////////////////// | |
1952 | |
1953 /// return the locale-dependent decimal point | |
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 | |
1961 ///////////////////// | |
1962 // scan functions | |
1963 ///////////////////// | |
1964 | |
1965 /*! | |
1966 @brief get codepoint from 4 hex characters following `\u` | |
1967 | |
1968 For input "\u c1 c2 c3 c4" the codepoint is: | |
1969 (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 | |
1970 = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) | |
1971 | |
1972 Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' | |
1973 must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The | |
1974 conversion is done by subtracting the offset (0x30, 0x37, and 0x57) | |
1975 between the ASCII value of the character and the desired integer value. | |
1976 | |
1977 @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or | |
1978 non-hex character) | |
1979 */ | |
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 | |
2013 /*! | |
2014 @brief check if the next byte(s) are inside a given range | |
2015 | |
2016 Adds the current byte and, for each passed range, reads a new byte and | |
2017 checks if it is inside the range. If a violation was detected, set up an | |
2018 error message and return false. Otherwise, return true. | |
2019 | |
2020 @param[in] ranges list of integers; interpreted as list of pairs of | |
2021 inclusive lower and upper bound, respectively | |
2022 | |
2023 @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, | |
2024 1, 2, or 3 pairs. This precondition is enforced by an assertion. | |
2025 | |
2026 @return true if and only if no range violation was detected | |
2027 */ | |
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 | |
2050 /*! | |
2051 @brief scan a string literal | |
2052 | |
2053 This function scans a string according to Sect. 7 of RFC 7159. While | |
2054 scanning, bytes are escaped and copied into buffer token_buffer. Then the | |
2055 function returns successfully, token_buffer is *not* null-terminated (as it | |
2056 may contain \0 bytes), and token_buffer.size() is the number of bytes in the | |
2057 string. | |
2058 | |
2059 @return token_type::value_string if string could be successfully scanned, | |
2060 token_type::parse_error otherwise | |
2061 | |
2062 @note In case of errors, variable error_message contains a textual | |
2063 description. | |
2064 */ | |
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 | |
2511 /*! | |
2512 @brief scan a number literal | |
2513 | |
2514 This function scans a string according to Sect. 6 of RFC 7159. | |
2515 | |
2516 The function is realized with a deterministic finite state machine derived | |
2517 from the grammar described in RFC 7159. Starting in state "init", the | |
2518 input is read and used to determined the next state. Only state "done" | |
2519 accepts the number. State "error" is a trap state to model errors. In the | |
2520 table below, "anything" means any character but the ones listed before. | |
2521 | |
2522 state | 0 | 1-9 | e E | + | - | . | anything | |
2523 ---------|----------|----------|----------|---------|---------|----------|----------- | |
2524 init | zero | any1 | [error] | [error] | minus | [error] | [error] | |
2525 minus | zero | any1 | [error] | [error] | [error] | [error] | [error] | |
2526 zero | done | done | exponent | done | done | decimal1 | done | |
2527 any1 | any1 | any1 | exponent | done | done | decimal1 | done | |
2528 decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error] | |
2529 decimal2 | decimal2 | decimal2 | exponent | done | done | done | done | |
2530 exponent | any2 | any2 | [error] | sign | sign | [error] | [error] | |
2531 sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] | |
2532 any2 | any2 | any2 | done | done | done | done | done | |
2533 | |
2534 The state machine is realized with one label per state (prefixed with | |
2535 "scan_number_") and `goto` statements between them. The state machine | |
2536 contains cycles, but any cycle can be left when EOF is read. Therefore, | |
2537 the function is guaranteed to terminate. | |
2538 | |
2539 During scanning, the read bytes are stored in token_buffer. This string is | |
2540 then converted to a signed integer, an unsigned integer, or a | |
2541 floating-point number. | |
2542 | |
2543 @return token_type::value_unsigned, token_type::value_integer, or | |
2544 token_type::value_float if number could be successfully scanned, | |
2545 token_type::parse_error otherwise | |
2546 | |
2547 @note The scanner is independent of the current locale. Internally, the | |
2548 locale's decimal point is used instead of `.` to work with the | |
2549 locale-dependent converters. | |
2550 */ | |
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 | |
2878 /*! | |
2879 @param[in] literal_text the literal text to expect | |
2880 @param[in] length the length of the passed literal text | |
2881 @param[in] return_type the token type to return on success | |
2882 */ | |
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 | |
2898 ///////////////////// | |
2899 // input management | |
2900 ///////////////////// | |
2901 | |
2902 /// reset token_buffer; current character is beginning of token | |
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 | |
2931 /// unget current character (return it again on next get) | |
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 | |
2943 /// add a character to token_buffer | |
2944 void add(int c) | |
2945 { | |
2946 token_buffer.push_back(std::char_traits<char>::to_char_type(c)); | |
2947 } | |
2948 | |
2949 public: | |
2950 ///////////////////// | |
2951 // value getters | |
2952 ///////////////////// | |
2953 | |
2954 /// return integer value | |
2955 constexpr number_integer_t get_number_integer() const noexcept | |
2956 { | |
2957 return value_integer; | |
2958 } | |
2959 | |
2960 /// return unsigned integer value | |
2961 constexpr number_unsigned_t get_number_unsigned() const noexcept | |
2962 { | |
2963 return value_unsigned; | |
2964 } | |
2965 | |
2966 /// return floating-point value | |
2967 constexpr number_float_t get_number_float() const noexcept | |
2968 { | |
2969 return value_float; | |
2970 } | |
2971 | |
2972 /// return current string value (implicitly resets the token; useful only once) | |
2973 string_t&& move_string() | |
2974 { | |
2975 return std::move(token_buffer); | |
2976 } | |
2977 | |
2978 ///////////////////// | |
2979 // diagnostics | |
2980 ///////////////////// | |
2981 | |
2982 /// return position of last read token | |
2983 constexpr std::size_t get_position() const noexcept | |
2984 { | |
2985 return chars_read; | |
2986 } | |
2987 | |
2988 /// return the last read token (for errors only). Will never contain EOF | |
2989 /// (an arbitrary value that is not a valid char value, often -1), because | |
2990 /// 255 may legitimately occur. May contain NUL, which should be escaped. | |
2991 std::string get_token_string() const | |
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 | |
3015 /// return syntax error message | |
3016 constexpr const char* get_error_message() const noexcept | |
3017 { | |
3018 return error_message; | |
3019 } | |
3020 | |
3021 ///////////////////// | |
3022 // actual scanner | |
3023 ///////////////////// | |
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: | |
3090 /// input adapter | |
3091 detail::input_adapter_t ia = nullptr; | |
3092 | |
3093 /// the current character | |
3094 std::char_traits<char>::int_type current = std::char_traits<char>::eof(); | |
3095 | |
3096 /// the number of characters read | |
3097 std::size_t chars_read = 0; | |
3098 | |
3099 /// raw input token string (for error messages) | |
3100 std::vector<char> token_string {}; | |
3101 | |
3102 /// buffer for variable-length tokens (numbers, strings) | |
3103 string_t token_buffer {}; | |
3104 | |
3105 /// a description of occurred lexer errors | |
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 | |
3113 /// the decimal point | |
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 { | |
3144 //////////// | |
3145 // parser // | |
3146 //////////// | |
3147 | |
3148 /*! | |
3149 @brief syntax analysis | |
3150 | |
3151 This class implements a recursive decent parser. | |
3152 */ | |
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 { | |
3166 /// the parser read `{` and started to process a JSON object | |
3167 object_start, | |
3168 /// the parser read `}` and finished processing a JSON object | |
3169 object_end, | |
3170 /// the parser read `[` and started to process a JSON array | |
3171 array_start, | |
3172 /// the parser read `]` and finished processing a JSON array | |
3173 array_end, | |
3174 /// the parser read a key of a value in an object | |
3175 key, | |
3176 /// the parser finished reading a JSON value | |
3177 value | |
3178 }; | |
3179 | |
3180 using parser_callback_t = | |
3181 std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>; | |
3182 | |
3183 /// a parser reading from an input adapter | |
3184 explicit parser(detail::input_adapter_t adapter, | |
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 | |
3190 /*! | |
3191 @brief public parser interface | |
3192 | |
3193 @param[in] strict whether to expect the last token to be EOF | |
3194 @param[in,out] result parsed JSON value | |
3195 | |
3196 @throw parse_error.101 in case of an unexpected token | |
3197 @throw parse_error.102 if to_unicode fails or surrogate error | |
3198 @throw parse_error.103 if to_unicode fails | |
3199 */ | |
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 | |
3230 /*! | |
3231 @brief public accept interface | |
3232 | |
3233 @param[in] strict whether to expect the last token to be EOF | |
3234 @return whether the input is a proper JSON text | |
3235 */ | |
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: | |
3251 /*! | |
3252 @brief the actual parser | |
3253 @throw parse_error.101 in case of an unexpected token | |
3254 @throw parse_error.102 if to_unicode fails or surrogate error | |
3255 @throw parse_error.103 if to_unicode fails | |
3256 */ | |
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 | |
3536 /*! | |
3537 @brief the actual acceptor | |
3538 | |
3539 @invariant 1. The last token is not yet processed. Therefore, the caller | |
3540 of this function must make sure a token has been read. | |
3541 2. When this function returns, the last token is processed. | |
3542 That is, the last read character was already considered. | |
3543 | |
3544 This invariant makes sure that no token needs to be "unput". | |
3545 */ | |
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 | |
3649 /// get next token from lexer | |
3650 token_type get_token() | |
3651 { | |
3652 return (last_token = m_lexer.scan()); | |
3653 } | |
3654 | |
3655 /*! | |
3656 @throw parse_error.101 if expected token did not occur | |
3657 */ | |
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: | |
3699 /// current level of recursion | |
3700 int depth = 0; | |
3701 /// callback function | |
3702 const parser_callback_t callback = nullptr; | |
3703 /// the type of the last read token | |
3704 token_type last_token = token_type::uninitialized; | |
3705 /// the lexer | |
3706 lexer_t m_lexer; | |
3707 /// whether a syntax error occurred | |
3708 bool errored = false; | |
3709 /// possible reason for the syntax error | |
3710 token_type expected = token_type::uninitialized; | |
3711 /// whether to throw exceptions in case of errors | |
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 */ | |
3736 class primitive_iterator_t | |
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 | |
3743 /// iterator as signed integer type | |
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 | |
3752 /// set iterator to a defined beginning | |
3753 void set_begin() noexcept | |
3754 { | |
3755 m_it = begin_value; | |
3756 } | |
3757 | |
3758 /// set iterator to a defined past the end | |
3759 void set_end() noexcept | |
3760 { | |
3761 m_it = end_value; | |
3762 } | |
3763 | |
3764 /// return whether the iterator can be dereferenced | |
3765 constexpr bool is_begin() const noexcept | |
3766 { | |
3767 return m_it == begin_value; | |
3768 } | |
3769 | |
3770 /// return whether the iterator is at end | |
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 { | |
3849 /*! | |
3850 @brief an iterator value | |
3851 | |
3852 @note This structure could easily be a union, but MSVC currently does not allow | |
3853 unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. | |
3854 */ | |
3855 template<typename BasicJsonType> struct internal_iterator | |
3856 { | |
3857 /// iterator for JSON objects | |
3858 typename BasicJsonType::object_t::iterator object_iterator {}; | |
3859 /// iterator for JSON arrays | |
3860 typename BasicJsonType::array_t::iterator array_iterator {}; | |
3861 /// generic iterator for all other types | |
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 | |
3894 /*! | |
3895 @brief a template for a bidirectional iterator for the @ref basic_json class | |
3896 | |
3897 This class implements a both iterators (iterator and const_iterator) for the | |
3898 @ref basic_json class. | |
3899 | |
3900 @note An iterator is called *initialized* when a pointer to a JSON value has | |
3901 been set (e.g., by a constructor or a copy assignment). If the iterator is | |
3902 default-constructed, it is *uninitialized* and most methods are undefined. | |
3903 **The library uses assertions to detect calls on uninitialized iterators.** | |
3904 | |
3905 @requirement The class satisfies the following concept requirements: | |
3906 - | |
3907 [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator): | |
3908 The iterator that can be moved can be moved in both directions (i.e. | |
3909 incremented and decremented). | |
3910 | |
3911 @since version 1.0.0, simplified in version 2.0.9, change to bidirectional | |
3912 iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) | |
3913 */ | |
3914 template<typename BasicJsonType> | |
3915 class iter_impl | |
3916 { | |
3917 /// allow basic_json to access private members | |
3918 friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>; | |
3919 friend BasicJsonType; | |
3920 friend iteration_proxy<iter_impl>; | |
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 | |
3930 /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. | |
3931 /// The C++ Standard has never required user-defined iterators to derive from std::iterator. | |
3932 /// A user-defined iterator should provide publicly accessible typedefs named | |
3933 /// iterator_category, value_type, difference_type, pointer, and reference. | |
3934 /// Note that value_type is required to be non-const, even for constant iterators. | |
3935 using iterator_category = std::bidirectional_iterator_tag; | |
3936 | |
3937 /// the type of the values when the iterator is dereferenced | |
3938 using value_type = typename BasicJsonType::value_type; | |
3939 /// a type to represent differences between iterators | |
3940 using difference_type = typename BasicJsonType::difference_type; | |
3941 /// defines a pointer to the type iterated over (value_type) | |
3942 using pointer = typename std::conditional<std::is_const<BasicJsonType>::value, | |
3943 typename BasicJsonType::const_pointer, | |
3944 typename BasicJsonType::pointer>::type; | |
3945 /// defines a reference to the type iterated over (value_type) | |
3946 using reference = | |
3947 typename std::conditional<std::is_const<BasicJsonType>::value, | |
3948 typename BasicJsonType::const_reference, | |
3949 typename BasicJsonType::reference>::type; | |
3950 | |
3951 /// default constructor | |
3952 iter_impl() = default; | |
3953 | |
3954 /*! | |
3955 @brief constructor for a given JSON instance | |
3956 @param[in] object pointer to a JSON object for this iterator | |
3957 @pre object != nullptr | |
3958 @post The iterator is initialized; i.e. `m_object != nullptr`. | |
3959 */ | |
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 | |
3986 /*! | |
3987 @note The conventional copy constructor and copy assignment are implicitly | |
3988 defined. Combined with the following converting constructor and | |
3989 assignment, they support: (1) copy from iterator to iterator, (2) | |
3990 copy from const iterator to const iterator, and (3) conversion from | |
3991 iterator to const iterator. However conversion from const iterator | |
3992 to iterator is not defined. | |
3993 */ | |
3994 | |
3995 /*! | |
3996 @brief converting constructor | |
3997 @param[in] other non-const iterator to copy from | |
3998 @note It is not checked whether @a other is initialized. | |
3999 */ | |
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 | |
4003 /*! | |
4004 @brief converting assignment | |
4005 @param[in,out] other non-const iterator to copy from | |
4006 @return const/non-const iterator | |
4007 @note It is not checked whether @a other is initialized. | |
4008 */ | |
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: | |
4017 /*! | |
4018 @brief set the iterator to the first value | |
4019 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4020 */ | |
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 | |
4054 /*! | |
4055 @brief set the iterator past the last value | |
4056 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4057 */ | |
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: | |
4085 /*! | |
4086 @brief return a reference to the value pointed to by the iterator | |
4087 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4088 */ | |
4089 reference operator*() const | |
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 | |
4122 /*! | |
4123 @brief dereference the iterator | |
4124 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4125 */ | |
4126 pointer operator->() const | |
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 | |
4156 /*! | |
4157 @brief post-increment (it++) | |
4158 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4159 */ | |
4160 iter_impl const operator++(int) | |
4161 { | |
4162 auto result = *this; | |
4163 ++(*this); | |
4164 return result; | |
4165 } | |
4166 | |
4167 /*! | |
4168 @brief pre-increment (++it) | |
4169 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4170 */ | |
4171 iter_impl& operator++() | |
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 | |
4199 /*! | |
4200 @brief post-decrement (it--) | |
4201 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4202 */ | |
4203 iter_impl const operator--(int) | |
4204 { | |
4205 auto result = *this; | |
4206 --(*this); | |
4207 return result; | |
4208 } | |
4209 | |
4210 /*! | |
4211 @brief pre-decrement (--it) | |
4212 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4213 */ | |
4214 iter_impl& operator--() | |
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 | |
4242 /*! | |
4243 @brief comparison: equal | |
4244 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4245 */ | |
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 | |
4269 /*! | |
4270 @brief comparison: not equal | |
4271 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4272 */ | |
4273 bool operator!=(const iter_impl& other) const | |
4274 { | |
4275 return not operator==(other); | |
4276 } | |
4277 | |
4278 /*! | |
4279 @brief comparison: smaller | |
4280 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4281 */ | |
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 | |
4305 /*! | |
4306 @brief comparison: less than or equal | |
4307 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4308 */ | |
4309 bool operator<=(const iter_impl& other) const | |
4310 { | |
4311 return not other.operator < (*this); | |
4312 } | |
4313 | |
4314 /*! | |
4315 @brief comparison: greater than | |
4316 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4317 */ | |
4318 bool operator>(const iter_impl& other) const | |
4319 { | |
4320 return not operator<=(other); | |
4321 } | |
4322 | |
4323 /*! | |
4324 @brief comparison: greater than or equal | |
4325 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4326 */ | |
4327 bool operator>=(const iter_impl& other) const | |
4328 { | |
4329 return not operator<(other); | |
4330 } | |
4331 | |
4332 /*! | |
4333 @brief add to iterator | |
4334 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4335 */ | |
4336 iter_impl& operator+=(difference_type i) | |
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 | |
4361 /*! | |
4362 @brief subtract from iterator | |
4363 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4364 */ | |
4365 iter_impl& operator-=(difference_type i) | |
4366 { | |
4367 return operator+=(-i); | |
4368 } | |
4369 | |
4370 /*! | |
4371 @brief add to iterator | |
4372 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4373 */ | |
4374 iter_impl operator+(difference_type i) const | |
4375 { | |
4376 auto result = *this; | |
4377 result += i; | |
4378 return result; | |
4379 } | |
4380 | |
4381 /*! | |
4382 @brief addition of distance and iterator | |
4383 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4384 */ | |
4385 friend iter_impl operator+(difference_type i, const iter_impl& it) | |
4386 { | |
4387 auto result = it; | |
4388 result += i; | |
4389 return result; | |
4390 } | |
4391 | |
4392 /*! | |
4393 @brief subtract from iterator | |
4394 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4395 */ | |
4396 iter_impl operator-(difference_type i) const | |
4397 { | |
4398 auto result = *this; | |
4399 result -= i; | |
4400 return result; | |
4401 } | |
4402 | |
4403 /*! | |
4404 @brief return difference | |
4405 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4406 */ | |
4407 difference_type operator-(const iter_impl& other) const | |
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 | |
4424 /*! | |
4425 @brief access to successor | |
4426 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4427 */ | |
4428 reference operator[](difference_type n) const | |
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 | |
4455 /*! | |
4456 @brief return the key of an object iterator | |
4457 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4458 */ | |
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 | |
4471 /*! | |
4472 @brief return the value of an iterator | |
4473 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
4474 */ | |
4475 reference value() const | |
4476 { | |
4477 return operator*(); | |
4478 } | |
4479 | |
4480 private: | |
4481 /// associated JSON instance | |
4482 pointer m_object = nullptr; | |
4483 /// the actual iterator of the associated instance | |
4484 internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it; | |
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 { | |
4502 /// proxy class for the items() function | |
4503 template<typename IteratorType> class iteration_proxy | |
4504 { | |
4505 private: | |
4506 /// helper class for iteration | |
4507 class iteration_proxy_internal | |
4508 { | |
4509 private: | |
4510 /// the iterator | |
4511 IteratorType anchor; | |
4512 /// an index for arrays (used to create key names) | |
4513 std::size_t array_index = 0; | |
4514 | |
4515 public: | |
4516 explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {} | |
4517 | |
4518 /// dereference operator (needed for range-based for) | |
4519 iteration_proxy_internal& operator*() | |
4520 { | |
4521 return *this; | |
4522 } | |
4523 | |
4524 /// increment operator (needed for range-based for) | |
4525 iteration_proxy_internal& operator++() | |
4526 { | |
4527 ++anchor; | |
4528 ++array_index; | |
4529 | |
4530 return *this; | |
4531 } | |
4532 | |
4533 /// inequality operator (needed for range-based for) | |
4534 bool operator!=(const iteration_proxy_internal& o) const noexcept | |
4535 { | |
4536 return anchor != o.anchor; | |
4537 } | |
4538 | |
4539 /// return key of the iterator | |
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 | |
4560 /// return value of the iterator | |
4561 typename IteratorType::reference value() const | |
4562 { | |
4563 return anchor.value(); | |
4564 } | |
4565 }; | |
4566 | |
4567 /// the container to iterate | |
4568 typename IteratorType::reference container; | |
4569 | |
4570 public: | |
4571 /// construct iteration proxy from a container | |
4572 explicit iteration_proxy(typename IteratorType::reference cont) noexcept | |
4573 : container(cont) {} | |
4574 | |
4575 /// return iterator begin (needed for range-based for) | |
4576 iteration_proxy_internal begin() noexcept | |
4577 { | |
4578 return iteration_proxy_internal(container.begin()); | |
4579 } | |
4580 | |
4581 /// return iterator end (needed for range-based for) | |
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 { | |
4601 ////////////////////// | |
4602 // reverse_iterator // | |
4603 ////////////////////// | |
4604 | |
4605 /*! | |
4606 @brief a template for a reverse iterator class | |
4607 | |
4608 @tparam Base the base iterator type to reverse. Valid types are @ref | |
4609 iterator (to create @ref reverse_iterator) and @ref const_iterator (to | |
4610 create @ref const_reverse_iterator). | |
4611 | |
4612 @requirement The class satisfies the following concept requirements: | |
4613 - | |
4614 [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator): | |
4615 The iterator that can be moved can be moved in both directions (i.e. | |
4616 incremented and decremented). | |
4617 - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator): | |
4618 It is possible to write to the pointed-to element (only if @a Base is | |
4619 @ref iterator). | |
4620 | |
4621 @since version 1.0.0 | |
4622 */ | |
4623 template<typename Base> | |
4624 class json_reverse_iterator : public std::reverse_iterator<Base> | |
4625 { | |
4626 public: | |
4627 using difference_type = std::ptrdiff_t; | |
4628 /// shortcut to the reverse iterator adapter | |
4629 using base_iterator = std::reverse_iterator<Base>; | |
4630 /// the reference type for the pointed-to element | |
4631 using reference = typename Base::reference; | |
4632 | |
4633 /// create reverse iterator from iterator | |
4634 json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept | |
4635 : base_iterator(it) {} | |
4636 | |
4637 /// create reverse iterator from base class | |
4638 json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} | |
4639 | |
4640 /// post-increment (it++) | |
4641 json_reverse_iterator const operator++(int) | |
4642 { | |
4643 return static_cast<json_reverse_iterator>(base_iterator::operator++(1)); | |
4644 } | |
4645 | |
4646 /// pre-increment (++it) | |
4647 json_reverse_iterator& operator++() | |
4648 { | |
4649 return static_cast<json_reverse_iterator&>(base_iterator::operator++()); | |
4650 } | |
4651 | |
4652 /// post-decrement (it--) | |
4653 json_reverse_iterator const operator--(int) | |
4654 { | |
4655 return static_cast<json_reverse_iterator>(base_iterator::operator--(1)); | |
4656 } | |
4657 | |
4658 /// pre-decrement (--it) | |
4659 json_reverse_iterator& operator--() | |
4660 { | |
4661 return static_cast<json_reverse_iterator&>(base_iterator::operator--()); | |
4662 } | |
4663 | |
4664 /// add to iterator | |
4665 json_reverse_iterator& operator+=(difference_type i) | |
4666 { | |
4667 return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i)); | |
4668 } | |
4669 | |
4670 /// add to iterator | |
4671 json_reverse_iterator operator+(difference_type i) const | |
4672 { | |
4673 return static_cast<json_reverse_iterator>(base_iterator::operator+(i)); | |
4674 } | |
4675 | |
4676 /// subtract from iterator | |
4677 json_reverse_iterator operator-(difference_type i) const | |
4678 { | |
4679 return static_cast<json_reverse_iterator>(base_iterator::operator-(i)); | |
4680 } | |
4681 | |
4682 /// return difference | |
4683 difference_type operator-(const json_reverse_iterator& other) const | |
4684 { | |
4685 return base_iterator(*this) - base_iterator(other); | |
4686 } | |
4687 | |
4688 /// access to successor | |
4689 reference operator[](difference_type n) const | |
4690 { | |
4691 return *(this->operator+(n)); | |
4692 } | |
4693 | |
4694 /// return the key of an object iterator | |
4695 auto key() const -> decltype(std::declval<Base>().key()) | |
4696 { | |
4697 auto it = --this->base(); | |
4698 return it.key(); | |
4699 } | |
4700 | |
4701 /// return the value of an iterator | |
4702 reference value() const | |
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 { | |
4727 /// abstract output adapter interface | |
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 | |
4735 /// a type to simplify interfaces | |
4736 template<typename CharType> | |
4737 using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>; | |
4738 | |
4739 /// output adapter for byte vectors | |
4740 template<typename CharType> | |
4741 class output_vector_adapter : public output_adapter_protocol<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 | |
4760 /// output adapter for output streams | |
4761 template<typename CharType> | |
4762 class output_stream_adapter : public output_adapter_protocol<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 | |
4781 /// output adapter for basic_string | |
4782 template<typename CharType, typename StringType = std::basic_string<CharType>> | |
4783 class output_string_adapter : public output_adapter_protocol<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>> | |
4803 class output_adapter | |
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 { | |
4857 /////////////////// | |
4858 // binary reader // | |
4859 /////////////////// | |
4860 | |
4861 /*! | |
4862 @brief deserialization of CBOR and MessagePack values | |
4863 */ | |
4864 template<typename BasicJsonType> | |
4865 class binary_reader | |
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: | |
4872 /*! | |
4873 @brief create a binary reader | |
4874 | |
4875 @param[in] adapter input adapter to read from | |
4876 */ | |
4877 explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter)) | |
4878 { | |
4879 assert(ia); | |
4880 } | |
4881 | |
4882 /*! | |
4883 @brief create a JSON value from CBOR input | |
4884 | |
4885 @param[in] strict whether to expect the input to be consumed completed | |
4886 @return JSON value created from CBOR input | |
4887 | |
4888 @throw parse_error.110 if input ended unexpectedly or the end of file was | |
4889 not reached when @a strict was set to true | |
4890 @throw parse_error.112 if unsupported byte was read | |
4891 */ | |
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 | |
4903 /*! | |
4904 @brief create a JSON value from MessagePack input | |
4905 | |
4906 @param[in] strict whether to expect the input to be consumed completed | |
4907 @return JSON value created from MessagePack input | |
4908 | |
4909 @throw parse_error.110 if input ended unexpectedly or the end of file was | |
4910 not reached when @a strict was set to true | |
4911 @throw parse_error.112 if unsupported byte was read | |
4912 */ | |
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 | |
4924 /*! | |
4925 @brief create a JSON value from UBJSON input | |
4926 | |
4927 @param[in] strict whether to expect the input to be consumed completed | |
4928 @return JSON value created from UBJSON input | |
4929 | |
4930 @throw parse_error.110 if input ended unexpectedly or the end of file was | |
4931 not reached when @a strict was set to true | |
4932 @throw parse_error.112 if unsupported byte was read | |
4933 */ | |
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 | |
4945 /*! | |
4946 @brief determine system byte order | |
4947 | |
4948 @return true if and only if system's byte order is little endian | |
4949 | |
4950 @note from http://stackoverflow.com/a/1001328/266378 | |
4951 */ | |
4952 static constexpr bool little_endianess(int num = 1) noexcept | |
4953 { | |
4954 return (*reinterpret_cast<char*>(&num) == 1); | |
4955 } | |
4956 | |
4957 private: | |
4958 /*! | |
4959 @param[in] get_char whether a new character should be retrieved from the | |
4960 input (true, default) or whether the last read | |
4961 character should be considered instead | |
4962 */ | |
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 | |
5605 /*! | |
5606 @param[in] get_char whether a new character should be retrieved from the | |
5607 input (true, default) or whether the last read | |
5608 character should be considered instead | |
5609 */ | |
5610 BasicJsonType parse_ubjson_internal(const bool get_char = true) | |
5611 { | |
5612 return get_ubjson_value(get_char ? get_ignore_noop() : current); | |
5613 } | |
5614 | |
5615 /*! | |
5616 @brief get next character from the input | |
5617 | |
5618 This function provides the interface to the used input adapter. It does | |
5619 not throw in case the input reached EOF, but returns a -'ve valued | |
5620 `std::char_traits<char>::eof()` in that case. | |
5621 | |
5622 @return character read from the input | |
5623 */ | |
5624 int get() | |
5625 { | |
5626 ++chars_read; | |
5627 return (current = ia->get_character()); | |
5628 } | |
5629 | |
5630 /*! | |
5631 @return character read from the input after ignoring all 'N' entries | |
5632 */ | |
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 | |
5683 /*! | |
5684 @brief create a string by reading characters from the input | |
5685 | |
5686 @param[in] len number of bytes to read | |
5687 | |
5688 @note We can not reserve @a len bytes for the result, because @a len | |
5689 may be too large. Usually, @ref unexpect_eof() detects the end of | |
5690 the input before we run out of string memory. | |
5691 | |
5692 @return string created by reading @a len bytes | |
5693 | |
5694 @throw parse_error.110 if input has less than @a len bytes | |
5695 */ | |
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 | |
5709 /*! | |
5710 @brief reads a CBOR string | |
5711 | |
5712 This function first reads starting bytes to determine the expected | |
5713 string length and then copies this number of bytes into a string. | |
5714 Additionally, CBOR's strings with indefinite lengths are supported. | |
5715 | |
5716 @return string | |
5717 | |
5718 @throw parse_error.110 if input ended | |
5719 @throw parse_error.113 if an unexpected byte is read | |
5720 */ | |
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 | |
5822 /*! | |
5823 @brief reads a MessagePack string | |
5824 | |
5825 This function first reads starting bytes to determine the expected | |
5826 string length and then copies this number of bytes into a string. | |
5827 | |
5828 @return string | |
5829 | |
5830 @throw parse_error.110 if input ended | |
5831 @throw parse_error.113 if an unexpected byte is read | |
5832 */ | |
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 | |
5928 /*! | |
5929 @brief reads a UBJSON string | |
5930 | |
5931 This function is either called after reading the 'S' byte explicitly | |
5932 indicating a string, or in case of an object key where the 'S' byte can be | |
5933 left out. | |
5934 | |
5935 @param[in] get_char whether a new character should be retrieved from the | |
5936 input (true, default) or whether the last read | |
5937 character should be considered instead | |
5938 | |
5939 @return string | |
5940 | |
5941 @throw parse_error.110 if input ended | |
5942 @throw parse_error.113 if an unexpected byte is read | |
5943 */ | |
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 | |
5973 /*! | |
5974 @brief determine the type and size for a container | |
5975 | |
5976 In the optimized UBJSON format, a type and a size can be provided to allow | |
5977 for a more compact representation. | |
5978 | |
5979 @return pair of the size and the type | |
5980 */ | |
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 | |
6166 /*! | |
6167 @brief throw if end of input is not reached | |
6168 @throw parse_error.110 if input not ended | |
6169 */ | |
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 | |
6178 /*! | |
6179 @briefthrow if end of input is reached | |
6180 @throw parse_error.110 if input ended | |
6181 */ | |
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: | |
6191 /// input adapter | |
6192 input_adapter_t ia = nullptr; | |
6193 | |
6194 /// the current character | |
6195 int current = std::char_traits<char>::eof(); | |
6196 | |
6197 /// the number of characters read | |
6198 std::size_t chars_read = 0; | |
6199 | |
6200 /// whether we can assume little endianess | |
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 { | |
6224 /////////////////// | |
6225 // binary writer // | |
6226 /////////////////// | |
6227 | |
6228 /*! | |
6229 @brief serialization to CBOR and MessagePack values | |
6230 */ | |
6231 template<typename BasicJsonType, typename CharType> | |
6232 class binary_writer | |
6233 { | |
6234 public: | |
6235 /*! | |
6236 @brief create a binary writer | |
6237 | |
6238 @param[in] adapter output adapter to write to | |
6239 */ | |
6240 explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter) | |
6241 { | |
6242 assert(oa); | |
6243 } | |
6244 | |
6245 /*! | |
6246 @brief[in] j JSON value to serialize | |
6247 */ | |
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 | |
6266 case value_t::number_integer: | |
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 | |
6331 case value_t::number_unsigned: | |
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 | |
6489 /*! | |
6490 @brief[in] j JSON value to serialize | |
6491 */ | |
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 | |
6510 case value_t::number_integer: | |
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 | |
6586 case value_t::number_unsigned: | |
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 | |
6728 /*! | |
6729 @param[in] j JSON value to serialize | |
6730 @param[in] use_count whether to use '#' prefixes (optimized format) | |
6731 @param[in] use_type whether to use '$' prefixes (optimized format) | |
6732 @param[in] add_prefix whether prefixes need to be used for this value | |
6733 */ | |
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 | |
6757 case value_t::number_integer: | |
6758 { | |
6759 write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix); | |
6760 break; | |
6761 } | |
6762 | |
6763 case value_t::number_unsigned: | |
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 | |
7035 /*! | |
7036 @brief determine the type prefix of container values | |
7037 | |
7038 @note This function does not need to be 100% accurate when it comes to | |
7039 integer limits. In case a number exceeds the limits of int64_t, | |
7040 this will be detected by a later call to function | |
7041 write_number_with_ubjson_prefix. Therefore, we return 'L' for any | |
7042 value that does not fit the previous limits. | |
7043 */ | |
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 | |
7054 case value_t::number_integer: | |
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 | |
7078 case value_t::number_unsigned: | |
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: | |
7120 /// whether we can assume little endianess | |
7121 const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess(); | |
7122 | |
7123 /// the output | |
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 | |
7164 /*! | |
7165 @brief implements the Grisu2 algorithm for binary to decimal floating-point | |
7166 conversion. | |
7167 | |
7168 This implementation is a slightly modified version of the reference | |
7169 implementation which may be obtained from | |
7170 http://florian.loitsch.com/publications (bench.tar.gz). | |
7171 | |
7172 The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. | |
7173 | |
7174 For a detailed description of the algorithm see: | |
7175 | |
7176 [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with | |
7177 Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming | |
7178 Language Design and Implementation, PLDI 2010 | |
7179 [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", | |
7180 Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language | |
7181 Design and Implementation, PLDI 1996 | |
7182 */ | |
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 | |
7206 /*! | |
7207 @brief returns x - y | |
7208 @pre x.e == y.e and x.f >= y.f | |
7209 */ | |
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 | |
7218 /*! | |
7219 @brief returns x * y | |
7220 @note The result is rounded. (Only the upper q bits are returned.) | |
7221 */ | |
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 | |
7283 /*! | |
7284 @brief normalize x such that the significand is >= 2^(q-1) | |
7285 @pre x.f != 0 | |
7286 */ | |
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 | |
7300 /*! | |
7301 @brief normalize x such that the result has the exponent E | |
7302 @pre e >= x.e and the upper e - x.e bits of x.f must be zero. | |
7303 */ | |
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 | |
7315 struct boundaries | |
7316 { | |
7317 diyfp w; | |
7318 diyfp minus; | |
7319 diyfp plus; | |
7320 }; | |
7321 | |
7322 /*! | |
7323 Compute the (normalized) diyfp representing the input number 'value' and its | |
7324 boundaries. | |
7325 | |
7326 @pre value must be finite and positive | |
7327 */ | |
7328 template <typename FloatType> | |
7329 boundaries compute_boundaries(FloatType value) | |
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 | |
7461 /*! | |
7462 For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached | |
7463 power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c | |
7464 satisfies (Definition 3.2 from [1]) | |
7465 | |
7466 alpha <= e_c + e + q <= gamma. | |
7467 */ | |
7468 inline cached_power get_cached_power_for_binary_exponent(int e) | |
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 | |
7628 /*! | |
7629 For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. | |
7630 For n == 0, returns 1 and sets pow10 := 1. | |
7631 */ | |
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 | |
7725 /*! | |
7726 Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. | |
7727 M- and M+ must be normalized and share the same exponent -60 <= e <= -32. | |
7728 */ | |
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 | |
7964 /*! | |
7965 v = buf * 10^decimal_exponent | |
7966 len is the length of the buffer (number of decimal digits) | |
7967 The buffer must be large enough, i.e. >= max_digits10. | |
7968 */ | |
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 | |
7984 const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); | |
7985 | |
7986 const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k | |
7987 | |
7988 // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] | |
7989 const diyfp w = diyfp::mul(v, c_minus_k); | |
7990 const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); | |
7991 const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); | |
7992 | |
7993 // ----(---+---)---------------(---+---)---------------(---+---)---- | |
7994 // w- w w+ | |
7995 // = c*m- = c*v = c*m+ | |
7996 // | |
7997 // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and | |
7998 // w+ are now off by a small amount. | |
7999 // In fact: | |
8000 // | |
8001 // w - v * 10^k < 1 ulp | |
8002 // | |
8003 // To account for this inaccuracy, add resp. subtract 1 ulp. | |
8004 // | |
8005 // --------+---[---------------(---+---)---------------]---+-------- | |
8006 // w- M- w M+ w+ | |
8007 // | |
8008 // Now any number in [M-, M+] (bounds included) will round to w when input, | |
8009 // regardless of how the input rounding algorithm breaks ties. | |
8010 // | |
8011 // And digit_gen generates the shortest possible such number in [M-, M+]. | |
8012 // Note that this does not mean that Grisu2 always generates the shortest | |
8013 // possible number in the interval (m-, m+). | |
8014 const diyfp M_minus(w_minus.f + 1, w_minus.e); | |
8015 const diyfp M_plus (w_plus.f - 1, w_plus.e ); | |
8016 | |
8017 decimal_exponent = -cached.k; // = -(-k) = k | |
8018 | |
8019 grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); | |
8020 } | |
8021 | |
8022 /*! | |
8023 v = buf * 10^decimal_exponent | |
8024 len is the length of the buffer (number of decimal digits) | |
8025 The buffer must be large enough, i.e. >= max_digits10. | |
8026 */ | |
8027 template <typename FloatType> | |
8028 void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) | |
8029 { | |
8030 static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3, | |
8031 "internal error: not enough precision"); | |
8032 | |
8033 assert(std::isfinite(value)); | |
8034 assert(value > 0); | |
8035 | |
8036 // If the neighbors (and boundaries) of 'value' are always computed for double-precision | |
8037 // numbers, all float's can be recovered using strtod (and strtof). However, the resulting | |
8038 // decimal representations are not exactly "short". | |
8039 // | |
8040 // The documentation for 'std::to_chars' (http://en.cppreference.com/w/cpp/utility/to_chars) | |
8041 // says "value is converted to a string as if by std::sprintf in the default ("C") locale" | |
8042 // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars' | |
8043 // does. | |
8044 // On the other hand, the documentation for 'std::to_chars' requires that "parsing the | |
8045 // representation using the corresponding std::from_chars function recovers value exactly". That | |
8046 // indicates that single precision floating-point numbers should be recovered using | |
8047 // 'std::strtof'. | |
8048 // | |
8049 // NB: If the neighbors are computed for single-precision numbers, there is a single float | |
8050 // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision | |
8051 // value is off by 1 ulp. | |
8052 #if 0 | |
8053 const boundaries w = compute_boundaries(static_cast<double>(value)); | |
8054 #else | |
8055 const boundaries w = compute_boundaries(value); | |
8056 #endif | |
8057 | |
8058 grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); | |
8059 } | |
8060 | |
8061 /*! | |
8062 @brief appends a decimal representation of e to buf | |
8063 @return a pointer to the element following the exponent. | |
8064 @pre -1000 < e < 1000 | |
8065 */ | |
8066 inline char* append_exponent(char* buf, int e) | |
8067 { | |
8068 assert(e > -1000); | |
8069 assert(e < 1000); | |
8070 | |
8071 if (e < 0) | |
8072 { | |
8073 e = -e; | |
8074 *buf++ = '-'; | |
8075 } | |
8076 else | |
8077 { | |
8078 *buf++ = '+'; | |
8079 } | |
8080 | |
8081 uint32_t k = static_cast<uint32_t>(e); | |
8082 if (k < 10) | |
8083 { | |
8084 // Always print at least two digits in the exponent. | |
8085 // This is for compatibility with printf("%g"). | |
8086 *buf++ = '0'; | |
8087 *buf++ = static_cast<char>('0' + k); | |
8088 } | |
8089 else if (k < 100) | |
8090 { | |
8091 *buf++ = static_cast<char>('0' + k / 10); | |
8092 k %= 10; | |
8093 *buf++ = static_cast<char>('0' + k); | |
8094 } | |
8095 else | |
8096 { | |
8097 *buf++ = static_cast<char>('0' + k / 100); | |
8098 k %= 100; | |
8099 *buf++ = static_cast<char>('0' + k / 10); | |
8100 k %= 10; | |
8101 *buf++ = static_cast<char>('0' + k); | |
8102 } | |
8103 | |
8104 return buf; | |
8105 } | |
8106 | |
8107 /*! | |
8108 @brief prettify v = buf * 10^decimal_exponent | |
8109 | |
8110 If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point | |
8111 notation. Otherwise it will be printed in exponential notation. | |
8112 | |
8113 @pre min_exp < 0 | |
8114 @pre max_exp > 0 | |
8115 */ | |
8116 inline char* format_buffer(char* buf, int len, int decimal_exponent, | |
8117 int min_exp, int max_exp) | |
8118 { | |
8119 assert(min_exp < 0); | |
8120 assert(max_exp > 0); | |
8121 | |
8122 const int k = len; | |
8123 const int n = len + decimal_exponent; | |
8124 | |
8125 // v = buf * 10^(n-k) | |
8126 // k is the length of the buffer (number of decimal digits) | |
8127 // n is the position of the decimal point relative to the start of the buffer. | |
8128 | |
8129 if (k <= n and n <= max_exp) | |
8130 { | |
8131 // digits[000] | |
8132 // len <= max_exp + 2 | |
8133 | |
8134 std::memset(buf + k, '0', static_cast<size_t>(n - k)); | |
8135 // Make it look like a floating-point number (#362, #378) | |
8136 buf[n + 0] = '.'; | |
8137 buf[n + 1] = '0'; | |
8138 return buf + (n + 2); | |
8139 } | |
8140 | |
8141 if (0 < n and n <= max_exp) | |
8142 { | |
8143 // dig.its | |
8144 // len <= max_digits10 + 1 | |
8145 | |
8146 assert(k > n); | |
8147 | |
8148 std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n)); | |
8149 buf[n] = '.'; | |
8150 return buf + (k + 1); | |
8151 } | |
8152 | |
8153 if (min_exp < n and n <= 0) | |
8154 { | |
8155 // 0.[000]digits | |
8156 // len <= 2 + (-min_exp - 1) + max_digits10 | |
8157 | |
8158 std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k)); | |
8159 buf[0] = '0'; | |
8160 buf[1] = '.'; | |
8161 std::memset(buf + 2, '0', static_cast<size_t>(-n)); | |
8162 return buf + (2 + (-n) + k); | |
8163 } | |
8164 | |
8165 if (k == 1) | |
8166 { | |
8167 // dE+123 | |
8168 // len <= 1 + 5 | |
8169 | |
8170 buf += 1; | |
8171 } | |
8172 else | |
8173 { | |
8174 // d.igitsE+123 | |
8175 // len <= max_digits10 + 1 + 5 | |
8176 | |
8177 std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1)); | |
8178 buf[1] = '.'; | |
8179 buf += 1 + k; | |
8180 } | |
8181 | |
8182 *buf++ = 'e'; | |
8183 return append_exponent(buf, n - 1); | |
8184 } | |
8185 | |
8186 } // namespace dtoa_impl | |
8187 | |
8188 /*! | |
8189 @brief generates a decimal representation of the floating-point number value in [first, last). | |
8190 | |
8191 The format of the resulting decimal representation is similar to printf's %g | |
8192 format. Returns an iterator pointing past-the-end of the decimal representation. | |
8193 | |
8194 @note The input number must be finite, i.e. NaN's and Inf's are not supported. | |
8195 @note The buffer must be large enough. | |
8196 @note The result is NOT null-terminated. | |
8197 */ | |
8198 template <typename FloatType> | |
8199 char* to_chars(char* first, char* last, FloatType value) | |
8200 { | |
8201 static_cast<void>(last); // maybe unused - fix warning | |
8202 assert(std::isfinite(value)); | |
8203 | |
8204 // Use signbit(value) instead of (value < 0) since signbit works for -0. | |
8205 if (std::signbit(value)) | |
8206 { | |
8207 value = -value; | |
8208 *first++ = '-'; | |
8209 } | |
8210 | |
8211 if (value == 0) // +-0 | |
8212 { | |
8213 *first++ = '0'; | |
8214 // Make it look like a floating-point number (#362, #378) | |
8215 *first++ = '.'; | |
8216 *first++ = '0'; | |
8217 return first; | |
8218 } | |
8219 | |
8220 assert(last - first >= std::numeric_limits<FloatType>::max_digits10); | |
8221 | |
8222 // Compute v = buffer * 10^decimal_exponent. | |
8223 // The decimal digits are stored in the buffer, which needs to be interpreted | |
8224 // as an unsigned decimal integer. | |
8225 // len is the length of the buffer, i.e. the number of decimal digits. | |
8226 int len = 0; | |
8227 int decimal_exponent = 0; | |
8228 dtoa_impl::grisu2(first, len, decimal_exponent, value); | |
8229 | |
8230 assert(len <= std::numeric_limits<FloatType>::max_digits10); | |
8231 | |
8232 // Format the buffer like printf("%.*g", prec, value) | |
8233 constexpr int kMinExp = -4; | |
8234 // Use digits10 here to increase compatibility with version 2. | |
8235 constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10; | |
8236 | |
8237 assert(last - first >= kMaxExp + 2); | |
8238 assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10); | |
8239 assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6); | |
8240 | |
8241 return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); | |
8242 } | |
8243 | |
8244 } // namespace detail | |
8245 } // namespace nlohmann | |
8246 | |
8247 // #include <nlohmann/detail/macro_scope.hpp> | |
8248 | |
8249 // #include <nlohmann/detail/meta.hpp> | |
8250 | |
8251 // #include <nlohmann/detail/output/output_adapters.hpp> | |
8252 | |
8253 // #include <nlohmann/detail/value_t.hpp> | |
8254 | |
8255 | |
8256 namespace nlohmann | |
8257 { | |
8258 namespace detail | |
8259 { | |
8260 /////////////////// | |
8261 // serialization // | |
8262 /////////////////// | |
8263 | |
8264 template<typename BasicJsonType> | |
8265 class serializer | |
8266 { | |
8267 using string_t = typename BasicJsonType::string_t; | |
8268 using number_float_t = typename BasicJsonType::number_float_t; | |
8269 using number_integer_t = typename BasicJsonType::number_integer_t; | |
8270 using number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
8271 static constexpr uint8_t UTF8_ACCEPT = 0; | |
8272 static constexpr uint8_t UTF8_REJECT = 1; | |
8273 | |
8274 public: | |
8275 /*! | |
8276 @param[in] s output stream to serialize to | |
8277 @param[in] ichar indentation character to use | |
8278 */ | |
8279 serializer(output_adapter_t<char> s, const char ichar) | |
8280 : o(std::move(s)), loc(std::localeconv()), | |
8281 thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep)), | |
8282 decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point)), | |
8283 indent_char(ichar), indent_string(512, indent_char) | |
8284 {} | |
8285 | |
8286 // delete because of pointer members | |
8287 serializer(const serializer&) = delete; | |
8288 serializer& operator=(const serializer&) = delete; | |
8289 | |
8290 /*! | |
8291 @brief internal implementation of the serialization function | |
8292 | |
8293 This function is called by the public member function dump and organizes | |
8294 the serialization internally. The indentation level is propagated as | |
8295 additional parameter. In case of arrays and objects, the function is | |
8296 called recursively. | |
8297 | |
8298 - strings and object keys are escaped using `escape_string()` | |
8299 - integer numbers are converted implicitly via `operator<<` | |
8300 - floating-point numbers are converted to a string using `"%g"` format | |
8301 | |
8302 @param[in] val value to serialize | |
8303 @param[in] pretty_print whether the output shall be pretty-printed | |
8304 @param[in] indent_step the indent level | |
8305 @param[in] current_indent the current indent level (only used internally) | |
8306 */ | |
8307 void dump(const BasicJsonType& val, const bool pretty_print, | |
8308 const bool ensure_ascii, | |
8309 const unsigned int indent_step, | |
8310 const unsigned int current_indent = 0) | |
8311 { | |
8312 switch (val.m_type) | |
8313 { | |
8314 case value_t::object: | |
8315 { | |
8316 if (val.m_value.object->empty()) | |
8317 { | |
8318 o->write_characters("{}", 2); | |
8319 return; | |
8320 } | |
8321 | |
8322 if (pretty_print) | |
8323 { | |
8324 o->write_characters("{\n", 2); | |
8325 | |
8326 // variable to hold indentation for recursive calls | |
8327 const auto new_indent = current_indent + indent_step; | |
8328 if (JSON_UNLIKELY(indent_string.size() < new_indent)) | |
8329 { | |
8330 indent_string.resize(indent_string.size() * 2, ' '); | |
8331 } | |
8332 | |
8333 // first n-1 elements | |
8334 auto i = val.m_value.object->cbegin(); | |
8335 for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) | |
8336 { | |
8337 o->write_characters(indent_string.c_str(), new_indent); | |
8338 o->write_character('\"'); | |
8339 dump_escaped(i->first, ensure_ascii); | |
8340 o->write_characters("\": ", 3); | |
8341 dump(i->second, true, ensure_ascii, indent_step, new_indent); | |
8342 o->write_characters(",\n", 2); | |
8343 } | |
8344 | |
8345 // last element | |
8346 assert(i != val.m_value.object->cend()); | |
8347 assert(std::next(i) == val.m_value.object->cend()); | |
8348 o->write_characters(indent_string.c_str(), new_indent); | |
8349 o->write_character('\"'); | |
8350 dump_escaped(i->first, ensure_ascii); | |
8351 o->write_characters("\": ", 3); | |
8352 dump(i->second, true, ensure_ascii, indent_step, new_indent); | |
8353 | |
8354 o->write_character('\n'); | |
8355 o->write_characters(indent_string.c_str(), current_indent); | |
8356 o->write_character('}'); | |
8357 } | |
8358 else | |
8359 { | |
8360 o->write_character('{'); | |
8361 | |
8362 // first n-1 elements | |
8363 auto i = val.m_value.object->cbegin(); | |
8364 for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) | |
8365 { | |
8366 o->write_character('\"'); | |
8367 dump_escaped(i->first, ensure_ascii); | |
8368 o->write_characters("\":", 2); | |
8369 dump(i->second, false, ensure_ascii, indent_step, current_indent); | |
8370 o->write_character(','); | |
8371 } | |
8372 | |
8373 // last element | |
8374 assert(i != val.m_value.object->cend()); | |
8375 assert(std::next(i) == val.m_value.object->cend()); | |
8376 o->write_character('\"'); | |
8377 dump_escaped(i->first, ensure_ascii); | |
8378 o->write_characters("\":", 2); | |
8379 dump(i->second, false, ensure_ascii, indent_step, current_indent); | |
8380 | |
8381 o->write_character('}'); | |
8382 } | |
8383 | |
8384 return; | |
8385 } | |
8386 | |
8387 case value_t::array: | |
8388 { | |
8389 if (val.m_value.array->empty()) | |
8390 { | |
8391 o->write_characters("[]", 2); | |
8392 return; | |
8393 } | |
8394 | |
8395 if (pretty_print) | |
8396 { | |
8397 o->write_characters("[\n", 2); | |
8398 | |
8399 // variable to hold indentation for recursive calls | |
8400 const auto new_indent = current_indent + indent_step; | |
8401 if (JSON_UNLIKELY(indent_string.size() < new_indent)) | |
8402 { | |
8403 indent_string.resize(indent_string.size() * 2, ' '); | |
8404 } | |
8405 | |
8406 // first n-1 elements | |
8407 for (auto i = val.m_value.array->cbegin(); | |
8408 i != val.m_value.array->cend() - 1; ++i) | |
8409 { | |
8410 o->write_characters(indent_string.c_str(), new_indent); | |
8411 dump(*i, true, ensure_ascii, indent_step, new_indent); | |
8412 o->write_characters(",\n", 2); | |
8413 } | |
8414 | |
8415 // last element | |
8416 assert(not val.m_value.array->empty()); | |
8417 o->write_characters(indent_string.c_str(), new_indent); | |
8418 dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); | |
8419 | |
8420 o->write_character('\n'); | |
8421 o->write_characters(indent_string.c_str(), current_indent); | |
8422 o->write_character(']'); | |
8423 } | |
8424 else | |
8425 { | |
8426 o->write_character('['); | |
8427 | |
8428 // first n-1 elements | |
8429 for (auto i = val.m_value.array->cbegin(); | |
8430 i != val.m_value.array->cend() - 1; ++i) | |
8431 { | |
8432 dump(*i, false, ensure_ascii, indent_step, current_indent); | |
8433 o->write_character(','); | |
8434 } | |
8435 | |
8436 // last element | |
8437 assert(not val.m_value.array->empty()); | |
8438 dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); | |
8439 | |
8440 o->write_character(']'); | |
8441 } | |
8442 | |
8443 return; | |
8444 } | |
8445 | |
8446 case value_t::string: | |
8447 { | |
8448 o->write_character('\"'); | |
8449 dump_escaped(*val.m_value.string, ensure_ascii); | |
8450 o->write_character('\"'); | |
8451 return; | |
8452 } | |
8453 | |
8454 case value_t::boolean: | |
8455 { | |
8456 if (val.m_value.boolean) | |
8457 { | |
8458 o->write_characters("true", 4); | |
8459 } | |
8460 else | |
8461 { | |
8462 o->write_characters("false", 5); | |
8463 } | |
8464 return; | |
8465 } | |
8466 | |
8467 case value_t::number_integer: | |
8468 { | |
8469 dump_integer(val.m_value.number_integer); | |
8470 return; | |
8471 } | |
8472 | |
8473 case value_t::number_unsigned: | |
8474 { | |
8475 dump_integer(val.m_value.number_unsigned); | |
8476 return; | |
8477 } | |
8478 | |
8479 case value_t::number_float: | |
8480 { | |
8481 dump_float(val.m_value.number_float); | |
8482 return; | |
8483 } | |
8484 | |
8485 case value_t::discarded: | |
8486 { | |
8487 o->write_characters("<discarded>", 11); | |
8488 return; | |
8489 } | |
8490 | |
8491 case value_t::null: | |
8492 { | |
8493 o->write_characters("null", 4); | |
8494 return; | |
8495 } | |
8496 } | |
8497 } | |
8498 | |
8499 private: | |
8500 /*! | |
8501 @brief dump escaped string | |
8502 | |
8503 Escape a string by replacing certain special characters by a sequence of an | |
8504 escape character (backslash) and another character and other control | |
8505 characters by a sequence of "\u" followed by a four-digit hex | |
8506 representation. The escaped string is written to output stream @a o. | |
8507 | |
8508 @param[in] s the string to escape | |
8509 @param[in] ensure_ascii whether to escape non-ASCII characters with | |
8510 \uXXXX sequences | |
8511 | |
8512 @complexity Linear in the length of string @a s. | |
8513 */ | |
8514 void dump_escaped(const string_t& s, const bool ensure_ascii) | |
8515 { | |
8516 uint32_t codepoint; | |
8517 uint8_t state = UTF8_ACCEPT; | |
8518 std::size_t bytes = 0; // number of bytes written to string_buffer | |
8519 | |
8520 for (std::size_t i = 0; i < s.size(); ++i) | |
8521 { | |
8522 const auto byte = static_cast<uint8_t>(s[i]); | |
8523 | |
8524 switch (decode(state, codepoint, byte)) | |
8525 { | |
8526 case UTF8_ACCEPT: // decode found a new code point | |
8527 { | |
8528 switch (codepoint) | |
8529 { | |
8530 case 0x08: // backspace | |
8531 { | |
8532 string_buffer[bytes++] = '\\'; | |
8533 string_buffer[bytes++] = 'b'; | |
8534 break; | |
8535 } | |
8536 | |
8537 case 0x09: // horizontal tab | |
8538 { | |
8539 string_buffer[bytes++] = '\\'; | |
8540 string_buffer[bytes++] = 't'; | |
8541 break; | |
8542 } | |
8543 | |
8544 case 0x0A: // newline | |
8545 { | |
8546 string_buffer[bytes++] = '\\'; | |
8547 string_buffer[bytes++] = 'n'; | |
8548 break; | |
8549 } | |
8550 | |
8551 case 0x0C: // formfeed | |
8552 { | |
8553 string_buffer[bytes++] = '\\'; | |
8554 string_buffer[bytes++] = 'f'; | |
8555 break; | |
8556 } | |
8557 | |
8558 case 0x0D: // carriage return | |
8559 { | |
8560 string_buffer[bytes++] = '\\'; | |
8561 string_buffer[bytes++] = 'r'; | |
8562 break; | |
8563 } | |
8564 | |
8565 case 0x22: // quotation mark | |
8566 { | |
8567 string_buffer[bytes++] = '\\'; | |
8568 string_buffer[bytes++] = '\"'; | |
8569 break; | |
8570 } | |
8571 | |
8572 case 0x5C: // reverse solidus | |
8573 { | |
8574 string_buffer[bytes++] = '\\'; | |
8575 string_buffer[bytes++] = '\\'; | |
8576 break; | |
8577 } | |
8578 | |
8579 default: | |
8580 { | |
8581 // escape control characters (0x00..0x1F) or, if | |
8582 // ensure_ascii parameter is used, non-ASCII characters | |
8583 if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F))) | |
8584 { | |
8585 if (codepoint <= 0xFFFF) | |
8586 { | |
8587 std::snprintf(string_buffer.data() + bytes, 7, "\\u%04x", | |
8588 static_cast<uint16_t>(codepoint)); | |
8589 bytes += 6; | |
8590 } | |
8591 else | |
8592 { | |
8593 std::snprintf(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x", | |
8594 static_cast<uint16_t>(0xD7C0 + (codepoint >> 10)), | |
8595 static_cast<uint16_t>(0xDC00 + (codepoint & 0x3FF))); | |
8596 bytes += 12; | |
8597 } | |
8598 } | |
8599 else | |
8600 { | |
8601 // copy byte to buffer (all previous bytes | |
8602 // been copied have in default case above) | |
8603 string_buffer[bytes++] = s[i]; | |
8604 } | |
8605 break; | |
8606 } | |
8607 } | |
8608 | |
8609 // write buffer and reset index; there must be 13 bytes | |
8610 // left, as this is the maximal number of bytes to be | |
8611 // written ("\uxxxx\uxxxx\0") for one code point | |
8612 if (string_buffer.size() - bytes < 13) | |
8613 { | |
8614 o->write_characters(string_buffer.data(), bytes); | |
8615 bytes = 0; | |
8616 } | |
8617 break; | |
8618 } | |
8619 | |
8620 case UTF8_REJECT: // decode found invalid UTF-8 byte | |
8621 { | |
8622 std::stringstream ss; | |
8623 ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(byte); | |
8624 JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str())); | |
8625 } | |
8626 | |
8627 default: // decode found yet incomplete multi-byte code point | |
8628 { | |
8629 if (not ensure_ascii) | |
8630 { | |
8631 // code point will not be escaped - copy byte to buffer | |
8632 string_buffer[bytes++] = s[i]; | |
8633 } | |
8634 break; | |
8635 } | |
8636 } | |
8637 } | |
8638 | |
8639 if (JSON_LIKELY(state == UTF8_ACCEPT)) | |
8640 { | |
8641 // write buffer | |
8642 if (bytes > 0) | |
8643 { | |
8644 o->write_characters(string_buffer.data(), bytes); | |
8645 } | |
8646 } | |
8647 else | |
8648 { | |
8649 // we finish reading, but do not accept: string was incomplete | |
8650 std::stringstream ss; | |
8651 ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(static_cast<uint8_t>(s.back())); | |
8652 JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str())); | |
8653 } | |
8654 } | |
8655 | |
8656 /*! | |
8657 @brief dump an integer | |
8658 | |
8659 Dump a given integer to output stream @a o. Works internally with | |
8660 @a number_buffer. | |
8661 | |
8662 @param[in] x integer number (signed or unsigned) to dump | |
8663 @tparam NumberType either @a number_integer_t or @a number_unsigned_t | |
8664 */ | |
8665 template<typename NumberType, detail::enable_if_t< | |
8666 std::is_same<NumberType, number_unsigned_t>::value or | |
8667 std::is_same<NumberType, number_integer_t>::value, | |
8668 int> = 0> | |
8669 void dump_integer(NumberType x) | |
8670 { | |
8671 // special case for "0" | |
8672 if (x == 0) | |
8673 { | |
8674 o->write_character('0'); | |
8675 return; | |
8676 } | |
8677 | |
8678 const bool is_negative = (x <= 0) and (x != 0); // see issue #755 | |
8679 std::size_t i = 0; | |
8680 | |
8681 while (x != 0) | |
8682 { | |
8683 // spare 1 byte for '\0' | |
8684 assert(i < number_buffer.size() - 1); | |
8685 | |
8686 const auto digit = std::labs(static_cast<long>(x % 10)); | |
8687 number_buffer[i++] = static_cast<char>('0' + digit); | |
8688 x /= 10; | |
8689 } | |
8690 | |
8691 if (is_negative) | |
8692 { | |
8693 // make sure there is capacity for the '-' | |
8694 assert(i < number_buffer.size() - 2); | |
8695 number_buffer[i++] = '-'; | |
8696 } | |
8697 | |
8698 std::reverse(number_buffer.begin(), number_buffer.begin() + i); | |
8699 o->write_characters(number_buffer.data(), i); | |
8700 } | |
8701 | |
8702 /*! | |
8703 @brief dump a floating-point number | |
8704 | |
8705 Dump a given floating-point number to output stream @a o. Works internally | |
8706 with @a number_buffer. | |
8707 | |
8708 @param[in] x floating-point number to dump | |
8709 */ | |
8710 void dump_float(number_float_t x) | |
8711 { | |
8712 // NaN / inf | |
8713 if (not std::isfinite(x)) | |
8714 { | |
8715 o->write_characters("null", 4); | |
8716 return; | |
8717 } | |
8718 | |
8719 // If number_float_t is an IEEE-754 single or double precision number, | |
8720 // use the Grisu2 algorithm to produce short numbers which are | |
8721 // guaranteed to round-trip, using strtof and strtod, resp. | |
8722 // | |
8723 // NB: The test below works if <long double> == <double>. | |
8724 static constexpr bool is_ieee_single_or_double | |
8725 = (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 24 and std::numeric_limits<number_float_t>::max_exponent == 128) or | |
8726 (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 53 and std::numeric_limits<number_float_t>::max_exponent == 1024); | |
8727 | |
8728 dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>()); | |
8729 } | |
8730 | |
8731 void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) | |
8732 { | |
8733 char* begin = number_buffer.data(); | |
8734 char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); | |
8735 | |
8736 o->write_characters(begin, static_cast<size_t>(end - begin)); | |
8737 } | |
8738 | |
8739 void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) | |
8740 { | |
8741 // get number of digits for a float -> text -> float round-trip | |
8742 static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10; | |
8743 | |
8744 // the actual conversion | |
8745 std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x); | |
8746 | |
8747 // negative value indicates an error | |
8748 assert(len > 0); | |
8749 // check if buffer was large enough | |
8750 assert(static_cast<std::size_t>(len) < number_buffer.size()); | |
8751 | |
8752 // erase thousands separator | |
8753 if (thousands_sep != '\0') | |
8754 { | |
8755 const auto end = std::remove(number_buffer.begin(), | |
8756 number_buffer.begin() + len, thousands_sep); | |
8757 std::fill(end, number_buffer.end(), '\0'); | |
8758 assert((end - number_buffer.begin()) <= len); | |
8759 len = (end - number_buffer.begin()); | |
8760 } | |
8761 | |
8762 // convert decimal point to '.' | |
8763 if (decimal_point != '\0' and decimal_point != '.') | |
8764 { | |
8765 const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); | |
8766 if (dec_pos != number_buffer.end()) | |
8767 { | |
8768 *dec_pos = '.'; | |
8769 } | |
8770 } | |
8771 | |
8772 o->write_characters(number_buffer.data(), static_cast<std::size_t>(len)); | |
8773 | |
8774 // determine if need to append ".0" | |
8775 const bool value_is_int_like = | |
8776 std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, | |
8777 [](char c) | |
8778 { | |
8779 return (c == '.' or c == 'e'); | |
8780 }); | |
8781 | |
8782 if (value_is_int_like) | |
8783 { | |
8784 o->write_characters(".0", 2); | |
8785 } | |
8786 } | |
8787 | |
8788 /*! | |
8789 @brief check whether a string is UTF-8 encoded | |
8790 | |
8791 The function checks each byte of a string whether it is UTF-8 encoded. The | |
8792 result of the check is stored in the @a state parameter. The function must | |
8793 be called initially with state 0 (accept). State 1 means the string must | |
8794 be rejected, because the current byte is not allowed. If the string is | |
8795 completely processed, but the state is non-zero, the string ended | |
8796 prematurely; that is, the last byte indicated more bytes should have | |
8797 followed. | |
8798 | |
8799 @param[in,out] state the state of the decoding | |
8800 @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) | |
8801 @param[in] byte next byte to decode | |
8802 @return new state | |
8803 | |
8804 @note The function has been edited: a std::array is used. | |
8805 | |
8806 @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de> | |
8807 @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ | |
8808 */ | |
8809 static uint8_t decode(uint8_t& state, uint32_t& codep, const uint8_t byte) noexcept | |
8810 { | |
8811 static const std::array<uint8_t, 400> utf8d = | |
8812 { | |
8813 { | |
8814 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F | |
8815 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F | |
8816 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F | |
8817 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F | |
8818 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F | |
8819 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF | |
8820 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF | |
8821 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF | |
8822 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF | |
8823 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 | |
8824 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 | |
8825 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 | |
8826 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 | |
8827 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 | |
8828 } | |
8829 }; | |
8830 | |
8831 const uint8_t type = utf8d[byte]; | |
8832 | |
8833 codep = (state != UTF8_ACCEPT) | |
8834 ? (byte & 0x3fu) | (codep << 6) | |
8835 : static_cast<uint32_t>(0xff >> type) & (byte); | |
8836 | |
8837 state = utf8d[256u + state * 16u + type]; | |
8838 return state; | |
8839 } | |
8840 | |
8841 private: | |
8842 /// the output of the serializer | |
8843 output_adapter_t<char> o = nullptr; | |
8844 | |
8845 /// a (hopefully) large enough character buffer | |
8846 std::array<char, 64> number_buffer{{}}; | |
8847 | |
8848 /// the locale | |
8849 const std::lconv* loc = nullptr; | |
8850 /// the locale's thousand separator character | |
8851 const char thousands_sep = '\0'; | |
8852 /// the locale's decimal point character | |
8853 const char decimal_point = '\0'; | |
8854 | |
8855 /// string buffer | |
8856 std::array<char, 512> string_buffer{{}}; | |
8857 | |
8858 /// the indentation character | |
8859 const char indent_char; | |
8860 /// the indentation string | |
8861 string_t indent_string; | |
8862 }; | |
8863 } | |
8864 } | |
8865 | |
8866 // #include <nlohmann/detail/json_ref.hpp> | |
8867 | |
8868 | |
8869 #include <initializer_list> | |
8870 #include <utility> | |
8871 | |
8872 namespace nlohmann | |
8873 { | |
8874 namespace detail | |
8875 { | |
8876 template<typename BasicJsonType> | |
8877 class json_ref | |
8878 { | |
8879 public: | |
8880 using value_type = BasicJsonType; | |
8881 | |
8882 json_ref(value_type&& value) | |
8883 : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true) | |
8884 {} | |
8885 | |
8886 json_ref(const value_type& value) | |
8887 : value_ref(const_cast<value_type*>(&value)), is_rvalue(false) | |
8888 {} | |
8889 | |
8890 json_ref(std::initializer_list<json_ref> init) | |
8891 : owned_value(init), value_ref(&owned_value), is_rvalue(true) | |
8892 {} | |
8893 | |
8894 template<class... Args> | |
8895 json_ref(Args&& ... args) | |
8896 : owned_value(std::forward<Args>(args)...), value_ref(&owned_value), is_rvalue(true) | |
8897 {} | |
8898 | |
8899 // class should be movable only | |
8900 json_ref(json_ref&&) = default; | |
8901 json_ref(const json_ref&) = delete; | |
8902 json_ref& operator=(const json_ref&) = delete; | |
8903 | |
8904 value_type moved_or_copied() const | |
8905 { | |
8906 if (is_rvalue) | |
8907 { | |
8908 return std::move(*value_ref); | |
8909 } | |
8910 return *value_ref; | |
8911 } | |
8912 | |
8913 value_type const& operator*() const | |
8914 { | |
8915 return *static_cast<value_type const*>(value_ref); | |
8916 } | |
8917 | |
8918 value_type const* operator->() const | |
8919 { | |
8920 return static_cast<value_type const*>(value_ref); | |
8921 } | |
8922 | |
8923 private: | |
8924 mutable value_type owned_value = nullptr; | |
8925 value_type* value_ref = nullptr; | |
8926 const bool is_rvalue; | |
8927 }; | |
8928 } | |
8929 } | |
8930 | |
8931 // #include <nlohmann/detail/json_pointer.hpp> | |
8932 | |
8933 | |
8934 #include <cassert> // assert | |
8935 #include <numeric> // accumulate | |
8936 #include <string> // string | |
8937 #include <vector> // vector | |
8938 | |
8939 // #include <nlohmann/detail/macro_scope.hpp> | |
8940 | |
8941 // #include <nlohmann/detail/exceptions.hpp> | |
8942 | |
8943 // #include <nlohmann/detail/value_t.hpp> | |
8944 | |
8945 | |
8946 namespace nlohmann | |
8947 { | |
8948 template<typename BasicJsonType> | |
8949 class json_pointer | |
8950 { | |
8951 // allow basic_json to access private members | |
8952 NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
8953 friend class basic_json; | |
8954 | |
8955 public: | |
8956 /*! | |
8957 @brief create JSON pointer | |
8958 | |
8959 Create a JSON pointer according to the syntax described in | |
8960 [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). | |
8961 | |
8962 @param[in] s string representing the JSON pointer; if omitted, the empty | |
8963 string is assumed which references the whole JSON value | |
8964 | |
8965 @throw parse_error.107 if the given JSON pointer @a s is nonempty and does | |
8966 not begin with a slash (`/`); see example below | |
8967 | |
8968 @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is | |
8969 not followed by `0` (representing `~`) or `1` (representing `/`); see | |
8970 example below | |
8971 | |
8972 @liveexample{The example shows the construction several valid JSON pointers | |
8973 as well as the exceptional behavior.,json_pointer} | |
8974 | |
8975 @since version 2.0.0 | |
8976 */ | |
8977 explicit json_pointer(const std::string& s = "") | |
8978 : reference_tokens(split(s)) | |
8979 {} | |
8980 | |
8981 /*! | |
8982 @brief return a string representation of the JSON pointer | |
8983 | |
8984 @invariant For each JSON pointer `ptr`, it holds: | |
8985 @code {.cpp} | |
8986 ptr == json_pointer(ptr.to_string()); | |
8987 @endcode | |
8988 | |
8989 @return a string representation of the JSON pointer | |
8990 | |
8991 @liveexample{The example shows the result of `to_string`., | |
8992 json_pointer__to_string} | |
8993 | |
8994 @since version 2.0.0 | |
8995 */ | |
8996 std::string to_string() const noexcept | |
8997 { | |
8998 return std::accumulate(reference_tokens.begin(), reference_tokens.end(), | |
8999 std::string{}, | |
9000 [](const std::string & a, const std::string & b) | |
9001 { | |
9002 return a + "/" + escape(b); | |
9003 }); | |
9004 } | |
9005 | |
9006 /// @copydoc to_string() | |
9007 operator std::string() const | |
9008 { | |
9009 return to_string(); | |
9010 } | |
9011 | |
9012 /*! | |
9013 @param[in] s reference token to be converted into an array index | |
9014 | |
9015 @return integer representation of @a s | |
9016 | |
9017 @throw out_of_range.404 if string @a s could not be converted to an integer | |
9018 */ | |
9019 static int array_index(const std::string& s) | |
9020 { | |
9021 std::size_t processed_chars = 0; | |
9022 const int res = std::stoi(s, &processed_chars); | |
9023 | |
9024 // check if the string was completely read | |
9025 if (JSON_UNLIKELY(processed_chars != s.size())) | |
9026 { | |
9027 JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'")); | |
9028 } | |
9029 | |
9030 return res; | |
9031 } | |
9032 | |
9033 private: | |
9034 /*! | |
9035 @brief remove and return last reference pointer | |
9036 @throw out_of_range.405 if JSON pointer has no parent | |
9037 */ | |
9038 std::string pop_back() | |
9039 { | |
9040 if (JSON_UNLIKELY(is_root())) | |
9041 { | |
9042 JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); | |
9043 } | |
9044 | |
9045 auto last = reference_tokens.back(); | |
9046 reference_tokens.pop_back(); | |
9047 return last; | |
9048 } | |
9049 | |
9050 /// return whether pointer points to the root document | |
9051 bool is_root() const | |
9052 { | |
9053 return reference_tokens.empty(); | |
9054 } | |
9055 | |
9056 json_pointer top() const | |
9057 { | |
9058 if (JSON_UNLIKELY(is_root())) | |
9059 { | |
9060 JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); | |
9061 } | |
9062 | |
9063 json_pointer result = *this; | |
9064 result.reference_tokens = {reference_tokens[0]}; | |
9065 return result; | |
9066 } | |
9067 | |
9068 /*! | |
9069 @brief create and return a reference to the pointed to value | |
9070 | |
9071 @complexity Linear in the number of reference tokens. | |
9072 | |
9073 @throw parse_error.109 if array index is not a number | |
9074 @throw type_error.313 if value cannot be unflattened | |
9075 */ | |
9076 BasicJsonType& get_and_create(BasicJsonType& j) const | |
9077 { | |
9078 using size_type = typename BasicJsonType::size_type; | |
9079 auto result = &j; | |
9080 | |
9081 // in case no reference tokens exist, return a reference to the JSON value | |
9082 // j which will be overwritten by a primitive value | |
9083 for (const auto& reference_token : reference_tokens) | |
9084 { | |
9085 switch (result->m_type) | |
9086 { | |
9087 case detail::value_t::null: | |
9088 { | |
9089 if (reference_token == "0") | |
9090 { | |
9091 // start a new array if reference token is 0 | |
9092 result = &result->operator[](0); | |
9093 } | |
9094 else | |
9095 { | |
9096 // start a new object otherwise | |
9097 result = &result->operator[](reference_token); | |
9098 } | |
9099 break; | |
9100 } | |
9101 | |
9102 case detail::value_t::object: | |
9103 { | |
9104 // create an entry in the object | |
9105 result = &result->operator[](reference_token); | |
9106 break; | |
9107 } | |
9108 | |
9109 case detail::value_t::array: | |
9110 { | |
9111 // create an entry in the array | |
9112 JSON_TRY | |
9113 { | |
9114 result = &result->operator[](static_cast<size_type>(array_index(reference_token))); | |
9115 } | |
9116 JSON_CATCH(std::invalid_argument&) | |
9117 { | |
9118 JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); | |
9119 } | |
9120 break; | |
9121 } | |
9122 | |
9123 /* | |
9124 The following code is only reached if there exists a reference | |
9125 token _and_ the current value is primitive. In this case, we have | |
9126 an error situation, because primitive values may only occur as | |
9127 single value; that is, with an empty list of reference tokens. | |
9128 */ | |
9129 default: | |
9130 JSON_THROW(detail::type_error::create(313, "invalid value to unflatten")); | |
9131 } | |
9132 } | |
9133 | |
9134 return *result; | |
9135 } | |
9136 | |
9137 /*! | |
9138 @brief return a reference to the pointed to value | |
9139 | |
9140 @note This version does not throw if a value is not present, but tries to | |
9141 create nested values instead. For instance, calling this function | |
9142 with pointer `"/this/that"` on a null value is equivalent to calling | |
9143 `operator[]("this").operator[]("that")` on that value, effectively | |
9144 changing the null value to an object. | |
9145 | |
9146 @param[in] ptr a JSON value | |
9147 | |
9148 @return reference to the JSON value pointed to by the JSON pointer | |
9149 | |
9150 @complexity Linear in the length of the JSON pointer. | |
9151 | |
9152 @throw parse_error.106 if an array index begins with '0' | |
9153 @throw parse_error.109 if an array index was not a number | |
9154 @throw out_of_range.404 if the JSON pointer can not be resolved | |
9155 */ | |
9156 BasicJsonType& get_unchecked(BasicJsonType* ptr) const | |
9157 { | |
9158 using size_type = typename BasicJsonType::size_type; | |
9159 for (const auto& reference_token : reference_tokens) | |
9160 { | |
9161 // convert null values to arrays or objects before continuing | |
9162 if (ptr->m_type == detail::value_t::null) | |
9163 { | |
9164 // check if reference token is a number | |
9165 const bool nums = | |
9166 std::all_of(reference_token.begin(), reference_token.end(), | |
9167 [](const char x) | |
9168 { | |
9169 return (x >= '0' and x <= '9'); | |
9170 }); | |
9171 | |
9172 // change value to array for numbers or "-" or to object otherwise | |
9173 *ptr = (nums or reference_token == "-") | |
9174 ? detail::value_t::array | |
9175 : detail::value_t::object; | |
9176 } | |
9177 | |
9178 switch (ptr->m_type) | |
9179 { | |
9180 case detail::value_t::object: | |
9181 { | |
9182 // use unchecked object access | |
9183 ptr = &ptr->operator[](reference_token); | |
9184 break; | |
9185 } | |
9186 | |
9187 case detail::value_t::array: | |
9188 { | |
9189 // error condition (cf. RFC 6901, Sect. 4) | |
9190 if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) | |
9191 { | |
9192 JSON_THROW(detail::parse_error::create(106, 0, | |
9193 "array index '" + reference_token + | |
9194 "' must not begin with '0'")); | |
9195 } | |
9196 | |
9197 if (reference_token == "-") | |
9198 { | |
9199 // explicitly treat "-" as index beyond the end | |
9200 ptr = &ptr->operator[](ptr->m_value.array->size()); | |
9201 } | |
9202 else | |
9203 { | |
9204 // convert array index to number; unchecked access | |
9205 JSON_TRY | |
9206 { | |
9207 ptr = &ptr->operator[]( | |
9208 static_cast<size_type>(array_index(reference_token))); | |
9209 } | |
9210 JSON_CATCH(std::invalid_argument&) | |
9211 { | |
9212 JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); | |
9213 } | |
9214 } | |
9215 break; | |
9216 } | |
9217 | |
9218 default: | |
9219 JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); | |
9220 } | |
9221 } | |
9222 | |
9223 return *ptr; | |
9224 } | |
9225 | |
9226 /*! | |
9227 @throw parse_error.106 if an array index begins with '0' | |
9228 @throw parse_error.109 if an array index was not a number | |
9229 @throw out_of_range.402 if the array index '-' is used | |
9230 @throw out_of_range.404 if the JSON pointer can not be resolved | |
9231 */ | |
9232 BasicJsonType& get_checked(BasicJsonType* ptr) const | |
9233 { | |
9234 using size_type = typename BasicJsonType::size_type; | |
9235 for (const auto& reference_token : reference_tokens) | |
9236 { | |
9237 switch (ptr->m_type) | |
9238 { | |
9239 case detail::value_t::object: | |
9240 { | |
9241 // note: at performs range check | |
9242 ptr = &ptr->at(reference_token); | |
9243 break; | |
9244 } | |
9245 | |
9246 case detail::value_t::array: | |
9247 { | |
9248 if (JSON_UNLIKELY(reference_token == "-")) | |
9249 { | |
9250 // "-" always fails the range check | |
9251 JSON_THROW(detail::out_of_range::create(402, | |
9252 "array index '-' (" + std::to_string(ptr->m_value.array->size()) + | |
9253 ") is out of range")); | |
9254 } | |
9255 | |
9256 // error condition (cf. RFC 6901, Sect. 4) | |
9257 if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) | |
9258 { | |
9259 JSON_THROW(detail::parse_error::create(106, 0, | |
9260 "array index '" + reference_token + | |
9261 "' must not begin with '0'")); | |
9262 } | |
9263 | |
9264 // note: at performs range check | |
9265 JSON_TRY | |
9266 { | |
9267 ptr = &ptr->at(static_cast<size_type>(array_index(reference_token))); | |
9268 } | |
9269 JSON_CATCH(std::invalid_argument&) | |
9270 { | |
9271 JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); | |
9272 } | |
9273 break; | |
9274 } | |
9275 | |
9276 default: | |
9277 JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); | |
9278 } | |
9279 } | |
9280 | |
9281 return *ptr; | |
9282 } | |
9283 | |
9284 /*! | |
9285 @brief return a const reference to the pointed to value | |
9286 | |
9287 @param[in] ptr a JSON value | |
9288 | |
9289 @return const reference to the JSON value pointed to by the JSON | |
9290 pointer | |
9291 | |
9292 @throw parse_error.106 if an array index begins with '0' | |
9293 @throw parse_error.109 if an array index was not a number | |
9294 @throw out_of_range.402 if the array index '-' is used | |
9295 @throw out_of_range.404 if the JSON pointer can not be resolved | |
9296 */ | |
9297 const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const | |
9298 { | |
9299 using size_type = typename BasicJsonType::size_type; | |
9300 for (const auto& reference_token : reference_tokens) | |
9301 { | |
9302 switch (ptr->m_type) | |
9303 { | |
9304 case detail::value_t::object: | |
9305 { | |
9306 // use unchecked object access | |
9307 ptr = &ptr->operator[](reference_token); | |
9308 break; | |
9309 } | |
9310 | |
9311 case detail::value_t::array: | |
9312 { | |
9313 if (JSON_UNLIKELY(reference_token == "-")) | |
9314 { | |
9315 // "-" cannot be used for const access | |
9316 JSON_THROW(detail::out_of_range::create(402, | |
9317 "array index '-' (" + std::to_string(ptr->m_value.array->size()) + | |
9318 ") is out of range")); | |
9319 } | |
9320 | |
9321 // error condition (cf. RFC 6901, Sect. 4) | |
9322 if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) | |
9323 { | |
9324 JSON_THROW(detail::parse_error::create(106, 0, | |
9325 "array index '" + reference_token + | |
9326 "' must not begin with '0'")); | |
9327 } | |
9328 | |
9329 // use unchecked array access | |
9330 JSON_TRY | |
9331 { | |
9332 ptr = &ptr->operator[]( | |
9333 static_cast<size_type>(array_index(reference_token))); | |
9334 } | |
9335 JSON_CATCH(std::invalid_argument&) | |
9336 { | |
9337 JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); | |
9338 } | |
9339 break; | |
9340 } | |
9341 | |
9342 default: | |
9343 JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); | |
9344 } | |
9345 } | |
9346 | |
9347 return *ptr; | |
9348 } | |
9349 | |
9350 /*! | |
9351 @throw parse_error.106 if an array index begins with '0' | |
9352 @throw parse_error.109 if an array index was not a number | |
9353 @throw out_of_range.402 if the array index '-' is used | |
9354 @throw out_of_range.404 if the JSON pointer can not be resolved | |
9355 */ | |
9356 const BasicJsonType& get_checked(const BasicJsonType* ptr) const | |
9357 { | |
9358 using size_type = typename BasicJsonType::size_type; | |
9359 for (const auto& reference_token : reference_tokens) | |
9360 { | |
9361 switch (ptr->m_type) | |
9362 { | |
9363 case detail::value_t::object: | |
9364 { | |
9365 // note: at performs range check | |
9366 ptr = &ptr->at(reference_token); | |
9367 break; | |
9368 } | |
9369 | |
9370 case detail::value_t::array: | |
9371 { | |
9372 if (JSON_UNLIKELY(reference_token == "-")) | |
9373 { | |
9374 // "-" always fails the range check | |
9375 JSON_THROW(detail::out_of_range::create(402, | |
9376 "array index '-' (" + std::to_string(ptr->m_value.array->size()) + | |
9377 ") is out of range")); | |
9378 } | |
9379 | |
9380 // error condition (cf. RFC 6901, Sect. 4) | |
9381 if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) | |
9382 { | |
9383 JSON_THROW(detail::parse_error::create(106, 0, | |
9384 "array index '" + reference_token + | |
9385 "' must not begin with '0'")); | |
9386 } | |
9387 | |
9388 // note: at performs range check | |
9389 JSON_TRY | |
9390 { | |
9391 ptr = &ptr->at(static_cast<size_type>(array_index(reference_token))); | |
9392 } | |
9393 JSON_CATCH(std::invalid_argument&) | |
9394 { | |
9395 JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); | |
9396 } | |
9397 break; | |
9398 } | |
9399 | |
9400 default: | |
9401 JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); | |
9402 } | |
9403 } | |
9404 | |
9405 return *ptr; | |
9406 } | |
9407 | |
9408 /*! | |
9409 @brief split the string input to reference tokens | |
9410 | |
9411 @note This function is only called by the json_pointer constructor. | |
9412 All exceptions below are documented there. | |
9413 | |
9414 @throw parse_error.107 if the pointer is not empty or begins with '/' | |
9415 @throw parse_error.108 if character '~' is not followed by '0' or '1' | |
9416 */ | |
9417 static std::vector<std::string> split(const std::string& reference_string) | |
9418 { | |
9419 std::vector<std::string> result; | |
9420 | |
9421 // special case: empty reference string -> no reference tokens | |
9422 if (reference_string.empty()) | |
9423 { | |
9424 return result; | |
9425 } | |
9426 | |
9427 // check if nonempty reference string begins with slash | |
9428 if (JSON_UNLIKELY(reference_string[0] != '/')) | |
9429 { | |
9430 JSON_THROW(detail::parse_error::create(107, 1, | |
9431 "JSON pointer must be empty or begin with '/' - was: '" + | |
9432 reference_string + "'")); | |
9433 } | |
9434 | |
9435 // extract the reference tokens: | |
9436 // - slash: position of the last read slash (or end of string) | |
9437 // - start: position after the previous slash | |
9438 for ( | |
9439 // search for the first slash after the first character | |
9440 std::size_t slash = reference_string.find_first_of('/', 1), | |
9441 // set the beginning of the first reference token | |
9442 start = 1; | |
9443 // we can stop if start == string::npos+1 = 0 | |
9444 start != 0; | |
9445 // set the beginning of the next reference token | |
9446 // (will eventually be 0 if slash == std::string::npos) | |
9447 start = slash + 1, | |
9448 // find next slash | |
9449 slash = reference_string.find_first_of('/', start)) | |
9450 { | |
9451 // use the text between the beginning of the reference token | |
9452 // (start) and the last slash (slash). | |
9453 auto reference_token = reference_string.substr(start, slash - start); | |
9454 | |
9455 // check reference tokens are properly escaped | |
9456 for (std::size_t pos = reference_token.find_first_of('~'); | |
9457 pos != std::string::npos; | |
9458 pos = reference_token.find_first_of('~', pos + 1)) | |
9459 { | |
9460 assert(reference_token[pos] == '~'); | |
9461 | |
9462 // ~ must be followed by 0 or 1 | |
9463 if (JSON_UNLIKELY(pos == reference_token.size() - 1 or | |
9464 (reference_token[pos + 1] != '0' and | |
9465 reference_token[pos + 1] != '1'))) | |
9466 { | |
9467 JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'")); | |
9468 } | |
9469 } | |
9470 | |
9471 // finally, store the reference token | |
9472 unescape(reference_token); | |
9473 result.push_back(reference_token); | |
9474 } | |
9475 | |
9476 return result; | |
9477 } | |
9478 | |
9479 /*! | |
9480 @brief replace all occurrences of a substring by another string | |
9481 | |
9482 @param[in,out] s the string to manipulate; changed so that all | |
9483 occurrences of @a f are replaced with @a t | |
9484 @param[in] f the substring to replace with @a t | |
9485 @param[in] t the string to replace @a f | |
9486 | |
9487 @pre The search string @a f must not be empty. **This precondition is | |
9488 enforced with an assertion.** | |
9489 | |
9490 @since version 2.0.0 | |
9491 */ | |
9492 static void replace_substring(std::string& s, const std::string& f, | |
9493 const std::string& t) | |
9494 { | |
9495 assert(not f.empty()); | |
9496 for (auto pos = s.find(f); // find first occurrence of f | |
9497 pos != std::string::npos; // make sure f was found | |
9498 s.replace(pos, f.size(), t), // replace with t, and | |
9499 pos = s.find(f, pos + t.size())) // find next occurrence of f | |
9500 {} | |
9501 } | |
9502 | |
9503 /// escape "~"" to "~0" and "/" to "~1" | |
9504 static std::string escape(std::string s) | |
9505 { | |
9506 replace_substring(s, "~", "~0"); | |
9507 replace_substring(s, "/", "~1"); | |
9508 return s; | |
9509 } | |
9510 | |
9511 /// unescape "~1" to tilde and "~0" to slash (order is important!) | |
9512 static void unescape(std::string& s) | |
9513 { | |
9514 replace_substring(s, "~1", "/"); | |
9515 replace_substring(s, "~0", "~"); | |
9516 } | |
9517 | |
9518 /*! | |
9519 @param[in] reference_string the reference string to the current value | |
9520 @param[in] value the value to consider | |
9521 @param[in,out] result the result object to insert values to | |
9522 | |
9523 @note Empty objects or arrays are flattened to `null`. | |
9524 */ | |
9525 static void flatten(const std::string& reference_string, | |
9526 const BasicJsonType& value, | |
9527 BasicJsonType& result) | |
9528 { | |
9529 switch (value.m_type) | |
9530 { | |
9531 case detail::value_t::array: | |
9532 { | |
9533 if (value.m_value.array->empty()) | |
9534 { | |
9535 // flatten empty array as null | |
9536 result[reference_string] = nullptr; | |
9537 } | |
9538 else | |
9539 { | |
9540 // iterate array and use index as reference string | |
9541 for (std::size_t i = 0; i < value.m_value.array->size(); ++i) | |
9542 { | |
9543 flatten(reference_string + "/" + std::to_string(i), | |
9544 value.m_value.array->operator[](i), result); | |
9545 } | |
9546 } | |
9547 break; | |
9548 } | |
9549 | |
9550 case detail::value_t::object: | |
9551 { | |
9552 if (value.m_value.object->empty()) | |
9553 { | |
9554 // flatten empty object as null | |
9555 result[reference_string] = nullptr; | |
9556 } | |
9557 else | |
9558 { | |
9559 // iterate object and use keys as reference string | |
9560 for (const auto& element : *value.m_value.object) | |
9561 { | |
9562 flatten(reference_string + "/" + escape(element.first), element.second, result); | |
9563 } | |
9564 } | |
9565 break; | |
9566 } | |
9567 | |
9568 default: | |
9569 { | |
9570 // add primitive value with its reference string | |
9571 result[reference_string] = value; | |
9572 break; | |
9573 } | |
9574 } | |
9575 } | |
9576 | |
9577 /*! | |
9578 @param[in] value flattened JSON | |
9579 | |
9580 @return unflattened JSON | |
9581 | |
9582 @throw parse_error.109 if array index is not a number | |
9583 @throw type_error.314 if value is not an object | |
9584 @throw type_error.315 if object values are not primitive | |
9585 @throw type_error.313 if value cannot be unflattened | |
9586 */ | |
9587 static BasicJsonType | |
9588 unflatten(const BasicJsonType& value) | |
9589 { | |
9590 if (JSON_UNLIKELY(not value.is_object())) | |
9591 { | |
9592 JSON_THROW(detail::type_error::create(314, "only objects can be unflattened")); | |
9593 } | |
9594 | |
9595 BasicJsonType result; | |
9596 | |
9597 // iterate the JSON object values | |
9598 for (const auto& element : *value.m_value.object) | |
9599 { | |
9600 if (JSON_UNLIKELY(not element.second.is_primitive())) | |
9601 { | |
9602 JSON_THROW(detail::type_error::create(315, "values in object must be primitive")); | |
9603 } | |
9604 | |
9605 // assign value to reference pointed to by JSON pointer; Note that if | |
9606 // the JSON pointer is "" (i.e., points to the whole value), function | |
9607 // get_and_create returns a reference to result itself. An assignment | |
9608 // will then create a primitive value. | |
9609 json_pointer(element.first).get_and_create(result) = element.second; | |
9610 } | |
9611 | |
9612 return result; | |
9613 } | |
9614 | |
9615 friend bool operator==(json_pointer const& lhs, | |
9616 json_pointer const& rhs) noexcept | |
9617 { | |
9618 return (lhs.reference_tokens == rhs.reference_tokens); | |
9619 } | |
9620 | |
9621 friend bool operator!=(json_pointer const& lhs, | |
9622 json_pointer const& rhs) noexcept | |
9623 { | |
9624 return not (lhs == rhs); | |
9625 } | |
9626 | |
9627 /// the reference tokens | |
9628 std::vector<std::string> reference_tokens; | |
9629 }; | |
9630 } | |
9631 | |
9632 // #include <nlohmann/adl_serializer.hpp> | |
9633 | |
9634 | |
9635 #include <utility> | |
9636 | |
9637 // #include <nlohmann/detail/conversions/from_json.hpp> | |
9638 | |
9639 // #include <nlohmann/detail/conversions/to_json.hpp> | |
9640 | |
9641 | |
9642 namespace nlohmann | |
9643 { | |
9644 template<typename, typename> | |
911 struct adl_serializer | 9645 struct adl_serializer |
912 { | 9646 { |
913 /*! | 9647 /*! |
914 @brief convert a JSON value to any value type | 9648 @brief convert a JSON value to any value type |
915 | 9649 |
940 noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val)))) | 9674 noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val)))) |
941 { | 9675 { |
942 ::nlohmann::to_json(j, std::forward<ValueType>(val)); | 9676 ::nlohmann::to_json(j, std::forward<ValueType>(val)); |
943 } | 9677 } |
944 }; | 9678 }; |
945 | 9679 } |
9680 | |
9681 | |
9682 /*! | |
9683 @brief namespace for Niels Lohmann | |
9684 @see https://github.com/nlohmann | |
9685 @since version 1.0.0 | |
9686 */ | |
9687 namespace nlohmann | |
9688 { | |
946 | 9689 |
947 /*! | 9690 /*! |
948 @brief a class to store JSON values | 9691 @brief a class to store JSON values |
949 | 9692 |
950 @tparam ObjectType type for JSON objects (`std::map` by default; will be used | 9693 @tparam ObjectType type for JSON objects (`std::map` by default; will be used |
1023 | 9766 |
1024 @since version 1.0.0 | 9767 @since version 1.0.0 |
1025 | 9768 |
1026 @nosubgrouping | 9769 @nosubgrouping |
1027 */ | 9770 */ |
1028 template < | 9771 NLOHMANN_BASIC_JSON_TPL_DECLARATION |
1029 template<typename U, typename V, typename... Args> class ObjectType = std::map, | |
1030 template<typename U, typename... Args> class ArrayType = std::vector, | |
1031 class StringType = std::string, | |
1032 class BooleanType = bool, | |
1033 class NumberIntegerType = std::int64_t, | |
1034 class NumberUnsignedType = std::uint64_t, | |
1035 class NumberFloatType = double, | |
1036 template<typename U> class AllocatorType = std::allocator, | |
1037 template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer | |
1038 > | |
1039 class basic_json | 9772 class basic_json |
1040 { | 9773 { |
1041 private: | 9774 private: |
1042 template<detail::value_t> friend struct detail::external_constructor; | 9775 template<detail::value_t> friend struct detail::external_constructor; |
9776 friend ::nlohmann::json_pointer<basic_json>; | |
9777 friend ::nlohmann::detail::parser<basic_json>; | |
9778 friend ::nlohmann::detail::serializer<basic_json>; | |
9779 template<typename BasicJsonType> | |
9780 friend class ::nlohmann::detail::iter_impl; | |
9781 template<typename BasicJsonType, typename CharType> | |
9782 friend class ::nlohmann::detail::binary_writer; | |
9783 template<typename BasicJsonType> | |
9784 friend class ::nlohmann::detail::binary_reader; | |
9785 | |
1043 /// workaround type for MSVC | 9786 /// workaround type for MSVC |
1044 using basic_json_t = basic_json<ObjectType, ArrayType, StringType, | 9787 using basic_json_t = NLOHMANN_BASIC_JSON_TPL; |
1045 BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, | 9788 |
1046 AllocatorType, JSONSerializer>; | 9789 // convenience aliases for types residing in namespace detail; |
9790 using lexer = ::nlohmann::detail::lexer<basic_json>; | |
9791 using parser = ::nlohmann::detail::parser<basic_json>; | |
9792 | |
9793 using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; | |
9794 template<typename BasicJsonType> | |
9795 using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>; | |
9796 template<typename BasicJsonType> | |
9797 using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>; | |
9798 template<typename Iterator> | |
9799 using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>; | |
9800 template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>; | |
9801 | |
9802 template<typename CharType> | |
9803 using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>; | |
9804 | |
9805 using binary_reader = ::nlohmann::detail::binary_reader<basic_json>; | |
9806 template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>; | |
9807 | |
9808 using serializer = ::nlohmann::detail::serializer<basic_json>; | |
1047 | 9809 |
1048 public: | 9810 public: |
1049 using value_t = detail::value_t; | 9811 using value_t = detail::value_t; |
1050 // forward declarations | 9812 /// @copydoc nlohmann::json_pointer |
1051 template<typename U> class iter_impl; | 9813 using json_pointer = ::nlohmann::json_pointer<basic_json>; |
1052 template<typename Base> class json_reverse_iterator; | |
1053 class json_pointer; | |
1054 template<typename T, typename SFINAE> | 9814 template<typename T, typename SFINAE> |
1055 using json_serializer = JSONSerializer<T, SFINAE>; | 9815 using json_serializer = JSONSerializer<T, SFINAE>; |
9816 /// helper type for initializer lists of basic_json values | |
9817 using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>; | |
9818 | |
9819 //////////////// | |
9820 // exceptions // | |
9821 //////////////// | |
9822 | |
9823 /// @name exceptions | |
9824 /// Classes to implement user-defined exceptions. | |
9825 /// @{ | |
9826 | |
9827 /// @copydoc detail::exception | |
9828 using exception = detail::exception; | |
9829 /// @copydoc detail::parse_error | |
9830 using parse_error = detail::parse_error; | |
9831 /// @copydoc detail::invalid_iterator | |
9832 using invalid_iterator = detail::invalid_iterator; | |
9833 /// @copydoc detail::type_error | |
9834 using type_error = detail::type_error; | |
9835 /// @copydoc detail::out_of_range | |
9836 using out_of_range = detail::out_of_range; | |
9837 /// @copydoc detail::other_error | |
9838 using other_error = detail::other_error; | |
9839 | |
9840 /// @} | |
9841 | |
1056 | 9842 |
1057 ///////////////////// | 9843 ///////////////////// |
1058 // container types // | 9844 // container types // |
1059 ///////////////////// | 9845 ///////////////////// |
1060 | 9846 |
1121 `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). | 9907 `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). |
1122 | 9908 |
1123 @liveexample{The following code shows an example output of the `meta()` | 9909 @liveexample{The following code shows an example output of the `meta()` |
1124 function.,meta} | 9910 function.,meta} |
1125 | 9911 |
9912 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
9913 changes to any JSON value. | |
9914 | |
1126 @complexity Constant. | 9915 @complexity Constant. |
1127 | 9916 |
1128 @since 2.1.0 | 9917 @since 2.1.0 |
1129 */ | 9918 */ |
1130 static basic_json meta() | 9919 static basic_json meta() |
1132 basic_json result; | 9921 basic_json result; |
1133 | 9922 |
1134 result["copyright"] = "(C) 2013-2017 Niels Lohmann"; | 9923 result["copyright"] = "(C) 2013-2017 Niels Lohmann"; |
1135 result["name"] = "JSON for Modern C++"; | 9924 result["name"] = "JSON for Modern C++"; |
1136 result["url"] = "https://github.com/nlohmann/json"; | 9925 result["url"] = "https://github.com/nlohmann/json"; |
1137 result["version"] = | 9926 result["version"]["string"] = |
1138 { | 9927 std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." + |
1139 {"string", "2.1.1"}, | 9928 std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." + |
1140 {"major", 2}, | 9929 std::to_string(NLOHMANN_JSON_VERSION_PATCH); |
1141 {"minor", 1}, | 9930 result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; |
1142 {"patch", 1} | 9931 result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; |
1143 }; | 9932 result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; |
1144 | 9933 |
1145 #ifdef _WIN32 | 9934 #ifdef _WIN32 |
1146 result["platform"] = "win32"; | 9935 result["platform"] = "win32"; |
1147 #elif defined __linux__ | 9936 #elif defined __linux__ |
1148 result["platform"] = "linux"; | 9937 result["platform"] = "linux"; |
1152 result["platform"] = "unix"; | 9941 result["platform"] = "unix"; |
1153 #else | 9942 #else |
1154 result["platform"] = "unknown"; | 9943 result["platform"] = "unknown"; |
1155 #endif | 9944 #endif |
1156 | 9945 |
1157 #if defined(__clang__) | 9946 #if defined(__ICC) || defined(__INTEL_COMPILER) |
9947 result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; | |
9948 #elif defined(__clang__) | |
1158 result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; | 9949 result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; |
1159 #elif defined(__ICC) || defined(__INTEL_COMPILER) | |
1160 result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; | |
1161 #elif defined(__GNUC__) || defined(__GNUG__) | 9950 #elif defined(__GNUC__) || defined(__GNUG__) |
1162 result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; | 9951 result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; |
1163 #elif defined(__HP_cc) || defined(__HP_aCC) | 9952 #elif defined(__HP_cc) || defined(__HP_aCC) |
1164 result["compiler"] = "hp" | 9953 result["compiler"] = "hp" |
1165 #elif defined(__IBMCPP__) | 9954 #elif defined(__IBMCPP__) |
1190 /// @name JSON value data types | 9979 /// @name JSON value data types |
1191 /// The data types to store a JSON value. These types are derived from | 9980 /// The data types to store a JSON value. These types are derived from |
1192 /// the template arguments passed to class @ref basic_json. | 9981 /// the template arguments passed to class @ref basic_json. |
1193 /// @{ | 9982 /// @{ |
1194 | 9983 |
9984 #if defined(JSON_HAS_CPP_14) | |
9985 // Use transparent comparator if possible, combined with perfect forwarding | |
9986 // on find() and count() calls prevents unnecessary string construction. | |
9987 using object_comparator_t = std::less<>; | |
9988 #else | |
9989 using object_comparator_t = std::less<StringType>; | |
9990 #endif | |
9991 | |
1195 /*! | 9992 /*! |
1196 @brief a type for an object | 9993 @brief a type for an object |
1197 | 9994 |
1198 [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows: | 9995 [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows: |
1199 > An object is an unordered collection of zero or more name/value pairs, | 9996 > An object is an unordered collection of zero or more name/value pairs, |
1232 the default type, objects have the following behavior: | 10029 the default type, objects have the following behavior: |
1233 | 10030 |
1234 - When all names are unique, objects will be interoperable in the sense | 10031 - When all names are unique, objects will be interoperable in the sense |
1235 that all software implementations receiving that object will agree on | 10032 that all software implementations receiving that object will agree on |
1236 the name-value mappings. | 10033 the name-value mappings. |
1237 - When the names within an object are not unique, later stored name/value | 10034 - When the names within an object are not unique, it is unspecified which |
1238 pairs overwrite previously stored name/value pairs, leaving the used | 10035 one of the values for a given key will be chosen. For instance, |
1239 names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will | 10036 `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or |
1240 be treated as equal and both stored as `{"key": 1}`. | 10037 `{"key": 2}`. |
1241 - Internally, name/value pairs are stored in lexicographical order of the | 10038 - Internally, name/value pairs are stored in lexicographical order of the |
1242 names. Objects will also be serialized (see @ref dump) in this order. | 10039 names. Objects will also be serialized (see @ref dump) in this order. |
1243 For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored | 10040 For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored |
1244 and serialized as `{"a": 2, "b": 1}`. | 10041 and serialized as `{"a": 2, "b": 1}`. |
1245 - When comparing objects, the order of the name/value pairs is irrelevant. | 10042 - When comparing objects, the order of the name/value pairs is irrelevant. |
1250 #### Limits | 10047 #### Limits |
1251 | 10048 |
1252 [RFC 7159](http://rfc7159.net/rfc7159) specifies: | 10049 [RFC 7159](http://rfc7159.net/rfc7159) specifies: |
1253 > An implementation may set limits on the maximum depth of nesting. | 10050 > An implementation may set limits on the maximum depth of nesting. |
1254 | 10051 |
1255 In this class, the object's limit of nesting is not constraint explicitly. | 10052 In this class, the object's limit of nesting is not explicitly constrained. |
1256 However, a maximum depth of nesting may be introduced by the compiler or | 10053 However, a maximum depth of nesting may be introduced by the compiler or |
1257 runtime environment. A theoretical limit can be queried by calling the | 10054 runtime environment. A theoretical limit can be queried by calling the |
1258 @ref max_size function of a JSON object. | 10055 @ref max_size function of a JSON object. |
1259 | 10056 |
1260 #### Storage | 10057 #### Storage |
1275 7159](http://rfc7159.net/rfc7159), because any order implements the | 10072 7159](http://rfc7159.net/rfc7159), because any order implements the |
1276 specified "unordered" nature of JSON objects. | 10073 specified "unordered" nature of JSON objects. |
1277 */ | 10074 */ |
1278 using object_t = ObjectType<StringType, | 10075 using object_t = ObjectType<StringType, |
1279 basic_json, | 10076 basic_json, |
1280 std::less<StringType>, | 10077 object_comparator_t, |
1281 AllocatorType<std::pair<const StringType, | 10078 AllocatorType<std::pair<const StringType, |
1282 basic_json>>>; | 10079 basic_json>>>; |
1283 | 10080 |
1284 /*! | 10081 /*! |
1285 @brief a type for an array | 10082 @brief a type for an array |
1309 #### Limits | 10106 #### Limits |
1310 | 10107 |
1311 [RFC 7159](http://rfc7159.net/rfc7159) specifies: | 10108 [RFC 7159](http://rfc7159.net/rfc7159) specifies: |
1312 > An implementation may set limits on the maximum depth of nesting. | 10109 > An implementation may set limits on the maximum depth of nesting. |
1313 | 10110 |
1314 In this class, the array's limit of nesting is not constraint explicitly. | 10111 In this class, the array's limit of nesting is not explicitly constrained. |
1315 However, a maximum depth of nesting may be introduced by the compiler or | 10112 However, a maximum depth of nesting may be introduced by the compiler or |
1316 runtime environment. A theoretical limit can be queried by calling the | 10113 runtime environment. A theoretical limit can be queried by calling the |
1317 @ref max_size function of a JSON array. | 10114 @ref max_size function of a JSON array. |
1318 | 10115 |
1319 #### Storage | 10116 #### Storage |
1624 /// helper for exception-safe object creation | 10421 /// helper for exception-safe object creation |
1625 template<typename T, typename... Args> | 10422 template<typename T, typename... Args> |
1626 static T* create(Args&& ... args) | 10423 static T* create(Args&& ... args) |
1627 { | 10424 { |
1628 AllocatorType<T> alloc; | 10425 AllocatorType<T> alloc; |
10426 using AllocatorTraits = std::allocator_traits<AllocatorType<T>>; | |
10427 | |
1629 auto deleter = [&](T * object) | 10428 auto deleter = [&](T * object) |
1630 { | 10429 { |
1631 alloc.deallocate(object, 1); | 10430 AllocatorTraits::deallocate(alloc, object, 1); |
1632 }; | 10431 }; |
1633 std::unique_ptr<T, decltype(deleter)> object(alloc.allocate(1), deleter); | 10432 std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter); |
1634 alloc.construct(object.get(), std::forward<Args>(args)...); | 10433 AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...); |
1635 assert(object != nullptr); | 10434 assert(object != nullptr); |
1636 return object.release(); | 10435 return object.release(); |
1637 } | 10436 } |
1638 | 10437 |
1639 //////////////////////// | 10438 //////////////////////// |
1738 break; | 10537 break; |
1739 } | 10538 } |
1740 | 10539 |
1741 case value_t::null: | 10540 case value_t::null: |
1742 { | 10541 { |
10542 object = nullptr; // silence warning, see #821 | |
1743 break; | 10543 break; |
1744 } | 10544 } |
1745 | 10545 |
1746 default: | 10546 default: |
1747 { | 10547 { |
1748 if (t == value_t::null) | 10548 object = nullptr; // silence warning, see #821 |
10549 if (JSON_UNLIKELY(t == value_t::null)) | |
1749 { | 10550 { |
1750 JSON_THROW(std::domain_error("961c151d2e87f2686a955a9be24d316f1362bf21 2.1.1")); // LCOV_EXCL_LINE | 10551 JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.1.2")); // LCOV_EXCL_LINE |
1751 } | 10552 } |
1752 break; | 10553 break; |
1753 } | 10554 } |
1754 } | 10555 } |
1755 } | 10556 } |
1758 json_value(const string_t& value) | 10559 json_value(const string_t& value) |
1759 { | 10560 { |
1760 string = create<string_t>(value); | 10561 string = create<string_t>(value); |
1761 } | 10562 } |
1762 | 10563 |
10564 /// constructor for rvalue strings | |
10565 json_value(string_t&& value) | |
10566 { | |
10567 string = create<string_t>(std::move(value)); | |
10568 } | |
10569 | |
1763 /// constructor for objects | 10570 /// constructor for objects |
1764 json_value(const object_t& value) | 10571 json_value(const object_t& value) |
1765 { | 10572 { |
1766 object = create<object_t>(value); | 10573 object = create<object_t>(value); |
1767 } | 10574 } |
1768 | 10575 |
10576 /// constructor for rvalue objects | |
10577 json_value(object_t&& value) | |
10578 { | |
10579 object = create<object_t>(std::move(value)); | |
10580 } | |
10581 | |
1769 /// constructor for arrays | 10582 /// constructor for arrays |
1770 json_value(const array_t& value) | 10583 json_value(const array_t& value) |
1771 { | 10584 { |
1772 array = create<array_t>(value); | 10585 array = create<array_t>(value); |
10586 } | |
10587 | |
10588 /// constructor for rvalue arrays | |
10589 json_value(array_t&& value) | |
10590 { | |
10591 array = create<array_t>(std::move(value)); | |
10592 } | |
10593 | |
10594 void destroy(value_t t) noexcept | |
10595 { | |
10596 switch (t) | |
10597 { | |
10598 case value_t::object: | |
10599 { | |
10600 AllocatorType<object_t> alloc; | |
10601 std::allocator_traits<decltype(alloc)>::destroy(alloc, object); | |
10602 std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1); | |
10603 break; | |
10604 } | |
10605 | |
10606 case value_t::array: | |
10607 { | |
10608 AllocatorType<array_t> alloc; | |
10609 std::allocator_traits<decltype(alloc)>::destroy(alloc, array); | |
10610 std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1); | |
10611 break; | |
10612 } | |
10613 | |
10614 case value_t::string: | |
10615 { | |
10616 AllocatorType<string_t> alloc; | |
10617 std::allocator_traits<decltype(alloc)>::destroy(alloc, string); | |
10618 std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1); | |
10619 break; | |
10620 } | |
10621 | |
10622 default: | |
10623 { | |
10624 break; | |
10625 } | |
10626 } | |
1773 } | 10627 } |
1774 }; | 10628 }; |
1775 | 10629 |
1776 /*! | 10630 /*! |
1777 @brief checks the class invariants | 10631 @brief checks the class invariants |
1780 end of every constructor to make sure that created objects respect the | 10634 end of every constructor to make sure that created objects respect the |
1781 invariant. Furthermore, it has to be called each time the type of a JSON | 10635 invariant. Furthermore, it has to be called each time the type of a JSON |
1782 value is changed, because the invariant expresses a relationship between | 10636 value is changed, because the invariant expresses a relationship between |
1783 @a m_type and @a m_value. | 10637 @a m_type and @a m_value. |
1784 */ | 10638 */ |
1785 void assert_invariant() const | 10639 void assert_invariant() const noexcept |
1786 { | 10640 { |
1787 assert(m_type != value_t::object or m_value.object != nullptr); | 10641 assert(m_type != value_t::object or m_value.object != nullptr); |
1788 assert(m_type != value_t::array or m_value.array != nullptr); | 10642 assert(m_type != value_t::array or m_value.array != nullptr); |
1789 assert(m_type != value_t::string or m_value.string != nullptr); | 10643 assert(m_type != value_t::string or m_value.string != nullptr); |
1790 } | 10644 } |
1793 ////////////////////////// | 10647 ////////////////////////// |
1794 // JSON parser callback // | 10648 // JSON parser callback // |
1795 ////////////////////////// | 10649 ////////////////////////// |
1796 | 10650 |
1797 /*! | 10651 /*! |
1798 @brief JSON callback events | 10652 @brief parser event types |
1799 | 10653 |
1800 This enumeration lists the parser events that can trigger calling a | 10654 The parser callback distinguishes the following events: |
1801 callback function of type @ref parser_callback_t during parsing. | 10655 - `object_start`: the parser read `{` and started to process a JSON object |
10656 - `key`: the parser read a key of a value in an object | |
10657 - `object_end`: the parser read `}` and finished processing a JSON object | |
10658 - `array_start`: the parser read `[` and started to process a JSON array | |
10659 - `array_end`: the parser read `]` and finished processing a JSON array | |
10660 - `value`: the parser finished reading a JSON value | |
1802 | 10661 |
1803 @image html callback_events.png "Example when certain parse events are triggered" | 10662 @image html callback_events.png "Example when certain parse events are triggered" |
1804 | 10663 |
1805 @since version 1.0.0 | 10664 @sa @ref parser_callback_t for more information and examples |
1806 */ | 10665 */ |
1807 enum class parse_event_t : uint8_t | 10666 using parse_event_t = typename parser::parse_event_t; |
1808 { | |
1809 /// the parser read `{` and started to process a JSON object | |
1810 object_start, | |
1811 /// the parser read `}` and finished processing a JSON object | |
1812 object_end, | |
1813 /// the parser read `[` and started to process a JSON array | |
1814 array_start, | |
1815 /// the parser read `]` and finished processing a JSON array | |
1816 array_end, | |
1817 /// the parser read a key of a value in an object | |
1818 key, | |
1819 /// the parser finished reading a JSON value | |
1820 value | |
1821 }; | |
1822 | 10667 |
1823 /*! | 10668 /*! |
1824 @brief per-element parser callback type | 10669 @brief per-element parser callback type |
1825 | 10670 |
1826 With a parser callback function, the result of parsing a JSON text can be | 10671 With a parser callback function, the result of parsing a JSON text can be |
1827 influenced. When passed to @ref parse(std::istream&, const | 10672 influenced. When passed to @ref parse, it is called on certain events |
1828 parser_callback_t) or @ref parse(const CharT, const parser_callback_t), | 10673 (passed as @ref parse_event_t via parameter @a event) with a set recursion |
1829 it is called on certain events (passed as @ref parse_event_t via parameter | 10674 depth @a depth and context JSON value @a parsed. The return value of the |
1830 @a event) with a set recursion depth @a depth and context JSON value | 10675 callback function is a boolean indicating whether the element that emitted |
1831 @a parsed. The return value of the callback function is a boolean | 10676 the callback shall be kept or not. |
1832 indicating whether the element that emitted the callback shall be kept or | |
1833 not. | |
1834 | 10677 |
1835 We distinguish six scenarios (determined by the event type) in which the | 10678 We distinguish six scenarios (determined by the event type) in which the |
1836 callback function can be called. The following table describes the values | 10679 callback function can be called. The following table describes the values |
1837 of the parameters @a depth, @a event, and @a parsed. | 10680 of the parameters @a depth, @a event, and @a parsed. |
1838 | 10681 |
1865 | 10708 |
1866 @return Whether the JSON value which called the function during parsing | 10709 @return Whether the JSON value which called the function during parsing |
1867 should be kept (`true`) or not (`false`). In the latter case, it is either | 10710 should be kept (`true`) or not (`false`). In the latter case, it is either |
1868 skipped completely or replaced by an empty discarded object. | 10711 skipped completely or replaced by an empty discarded object. |
1869 | 10712 |
1870 @sa @ref parse(std::istream&, parser_callback_t) or | 10713 @sa @ref parse for examples |
1871 @ref parse(const CharT, const parser_callback_t) for examples | |
1872 | 10714 |
1873 @since version 1.0.0 | 10715 @since version 1.0.0 |
1874 */ | 10716 */ |
1875 using parser_callback_t = std::function<bool(int depth, | 10717 using parser_callback_t = typename parser::parser_callback_t; |
1876 parse_event_t event, | |
1877 basic_json& parsed)>; | |
1878 | 10718 |
1879 | 10719 |
1880 ////////////////// | 10720 ////////////////// |
1881 // constructors // | 10721 // constructors // |
1882 ////////////////// | 10722 ////////////////// |
1899 string | `""` | 10739 string | `""` |
1900 number | `0` | 10740 number | `0` |
1901 object | `{}` | 10741 object | `{}` |
1902 array | `[]` | 10742 array | `[]` |
1903 | 10743 |
1904 @param[in] value_type the type of the value to create | 10744 @param[in] v the type of the value to create |
1905 | 10745 |
1906 @complexity Constant. | 10746 @complexity Constant. |
1907 | 10747 |
1908 @throw std::bad_alloc if allocation for object, array, or string value | 10748 @exceptionsafety Strong guarantee: if an exception is thrown, there are no |
1909 fails | 10749 changes to any JSON value. |
1910 | 10750 |
1911 @liveexample{The following code shows the constructor for different @ref | 10751 @liveexample{The following code shows the constructor for different @ref |
1912 value_t values,basic_json__value_t} | 10752 value_t values,basic_json__value_t} |
1913 | 10753 |
10754 @sa @ref clear() -- restores the postcondition of this constructor | |
10755 | |
1914 @since version 1.0.0 | 10756 @since version 1.0.0 |
1915 */ | 10757 */ |
1916 basic_json(const value_t value_type) | 10758 basic_json(const value_t v) |
1917 : m_type(value_type), m_value(value_type) | 10759 : m_type(v), m_value(v) |
1918 { | 10760 { |
1919 assert_invariant(); | 10761 assert_invariant(); |
1920 } | 10762 } |
1921 | 10763 |
1922 /*! | 10764 /*! |
1945 | 10787 |
1946 /*! | 10788 /*! |
1947 @brief create a JSON value | 10789 @brief create a JSON value |
1948 | 10790 |
1949 This is a "catch all" constructor for all compatible JSON types; that is, | 10791 This is a "catch all" constructor for all compatible JSON types; that is, |
1950 types for which a `to_json()` method exsits. The constructor forwards the | 10792 types for which a `to_json()` method exists. The constructor forwards the |
1951 parameter @a val to that method (to `json_serializer<U>::to_json` method | 10793 parameter @a val to that method (to `json_serializer<U>::to_json` method |
1952 with `U = uncvref_t<CompatibleType>`, to be exact). | 10794 with `U = uncvref_t<CompatibleType>`, to be exact). |
1953 | 10795 |
1954 Template type @a CompatibleType includes, but is not limited to, the | 10796 Template type @a CompatibleType includes, but is not limited to, the |
1955 following types: | 10797 following types: |
1956 - **arrays**: @ref array_t and all kinds of compatible containers such as | 10798 - **arrays**: @ref array_t and all kinds of compatible containers such as |
1957 `std::vector`, `std::deque`, `std::list`, `std::forward_list`, | 10799 `std::vector`, `std::deque`, `std::list`, `std::forward_list`, |
1958 `std::array`, `std::set`, `std::unordered_set`, `std::multiset`, and | 10800 `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, |
1959 `unordered_multiset` with a `value_type` from which a @ref basic_json | 10801 `std::multiset`, and `std::unordered_multiset` with a `value_type` from |
1960 value can be constructed. | 10802 which a @ref basic_json value can be constructed. |
1961 - **objects**: @ref object_t and all kinds of compatible associative | 10803 - **objects**: @ref object_t and all kinds of compatible associative |
1962 containers such as `std::map`, `std::unordered_map`, `std::multimap`, | 10804 containers such as `std::map`, `std::unordered_map`, `std::multimap`, |
1963 and `std::unordered_multimap` with a `key_type` compatible to | 10805 and `std::unordered_multimap` with a `key_type` compatible to |
1964 @ref string_t and a `value_type` from which a @ref basic_json value can | 10806 @ref string_t and a `value_type` from which a @ref basic_json value can |
1965 be constructed. | 10807 be constructed. |
1974 | 10816 |
1975 @tparam CompatibleType a type such that: | 10817 @tparam CompatibleType a type such that: |
1976 - @a CompatibleType is not derived from `std::istream`, | 10818 - @a CompatibleType is not derived from `std::istream`, |
1977 - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move | 10819 - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move |
1978 constructors), | 10820 constructors), |
10821 - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments) | |
1979 - @a CompatibleType is not a @ref basic_json nested type (e.g., | 10822 - @a CompatibleType is not a @ref basic_json nested type (e.g., |
1980 @ref json_pointer, @ref iterator, etc ...) | 10823 @ref json_pointer, @ref iterator, etc ...) |
1981 - @ref @ref json_serializer<U> has a | 10824 - @ref @ref json_serializer<U> has a |
1982 `to_json(basic_json_t&, CompatibleType&&)` method | 10825 `to_json(basic_json_t&, CompatibleType&&)` method |
1983 | 10826 |
1984 @tparam U = `uncvref_t<CompatibleType>` | 10827 @tparam U = `uncvref_t<CompatibleType>` |
1985 | 10828 |
1986 @param[in] val the value to be forwarded | 10829 @param[in] val the value to be forwarded to the respective constructor |
1987 | 10830 |
1988 @complexity Usually linear in the size of the passed @a val, also | 10831 @complexity Usually linear in the size of the passed @a val, also |
1989 depending on the implementation of the called `to_json()` | 10832 depending on the implementation of the called `to_json()` |
1990 method. | 10833 method. |
1991 | 10834 |
1992 @throw what `json_serializer<U>::to_json()` throws | 10835 @exceptionsafety Depends on the called constructor. For types directly |
10836 supported by the library (i.e., all types for which no `to_json()` function | |
10837 was provided), strong guarantee holds: if an exception is thrown, there are | |
10838 no changes to any JSON value. | |
1993 | 10839 |
1994 @liveexample{The following code shows the constructor with several | 10840 @liveexample{The following code shows the constructor with several |
1995 compatible types.,basic_json__CompatibleType} | 10841 compatible types.,basic_json__CompatibleType} |
1996 | 10842 |
1997 @since version 2.1.0 | 10843 @since version 2.1.0 |
1998 */ | 10844 */ |
1999 template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>, | 10845 template <typename CompatibleType, |
2000 detail::enable_if_t<not std::is_base_of<std::istream, U>::value and | 10846 typename U = detail::uncvref_t<CompatibleType>, |
2001 not std::is_same<U, basic_json_t>::value and | 10847 detail::enable_if_t< |
2002 not detail::is_basic_json_nested_type< | 10848 detail::is_compatible_type<basic_json_t, U>::value, int> = 0> |
2003 basic_json_t, U>::value and | 10849 basic_json(CompatibleType && val) noexcept(noexcept( |
2004 detail::has_to_json<basic_json, U>::value, | 10850 JSONSerializer<U>::to_json(std::declval<basic_json_t&>(), |
2005 int> = 0> | 10851 std::forward<CompatibleType>(val)))) |
2006 basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json( | |
2007 std::declval<basic_json_t&>(), std::forward<CompatibleType>(val)))) | |
2008 { | 10852 { |
2009 JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val)); | 10853 JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val)); |
10854 assert_invariant(); | |
10855 } | |
10856 | |
10857 /*! | |
10858 @brief create a JSON value from an existing one | |
10859 | |
10860 This is a constructor for existing @ref basic_json types. | |
10861 It does not hijack copy/move constructors, since the parameter has different | |
10862 template arguments than the current ones. | |
10863 | |
10864 The constructor tries to convert the internal @ref m_value of the parameter. | |
10865 | |
10866 @tparam BasicJsonType a type such that: | |
10867 - @a BasicJsonType is a @ref basic_json type. | |
10868 - @a BasicJsonType has different template arguments than @ref basic_json_t. | |
10869 | |
10870 @param[in] val the @ref basic_json value to be converted. | |
10871 | |
10872 @complexity Usually linear in the size of the passed @a val, also | |
10873 depending on the implementation of the called `to_json()` | |
10874 method. | |
10875 | |
10876 @exceptionsafety Depends on the called constructor. For types directly | |
10877 supported by the library (i.e., all types for which no `to_json()` function | |
10878 was provided), strong guarantee holds: if an exception is thrown, there are | |
10879 no changes to any JSON value. | |
10880 | |
10881 @since version 3.1.2 | |
10882 */ | |
10883 template <typename BasicJsonType, | |
10884 detail::enable_if_t< | |
10885 detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0> | |
10886 basic_json(const BasicJsonType& val) | |
10887 { | |
10888 using other_boolean_t = typename BasicJsonType::boolean_t; | |
10889 using other_number_float_t = typename BasicJsonType::number_float_t; | |
10890 using other_number_integer_t = typename BasicJsonType::number_integer_t; | |
10891 using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
10892 using other_string_t = typename BasicJsonType::string_t; | |
10893 using other_object_t = typename BasicJsonType::object_t; | |
10894 using other_array_t = typename BasicJsonType::array_t; | |
10895 | |
10896 switch (val.type()) | |
10897 { | |
10898 case value_t::boolean: | |
10899 JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>()); | |
10900 break; | |
10901 case value_t::number_float: | |
10902 JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>()); | |
10903 break; | |
10904 case value_t::number_integer: | |
10905 JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>()); | |
10906 break; | |
10907 case value_t::number_unsigned: | |
10908 JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>()); | |
10909 break; | |
10910 case value_t::string: | |
10911 JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>()); | |
10912 break; | |
10913 case value_t::object: | |
10914 JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>()); | |
10915 break; | |
10916 case value_t::array: | |
10917 JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>()); | |
10918 break; | |
10919 case value_t::null: | |
10920 *this = nullptr; | |
10921 break; | |
10922 case value_t::discarded: | |
10923 m_type = value_t::discarded; | |
10924 break; | |
10925 } | |
2010 assert_invariant(); | 10926 assert_invariant(); |
2011 } | 10927 } |
2012 | 10928 |
2013 /*! | 10929 /*! |
2014 @brief create a container (array or object) from an initializer list | 10930 @brief create a container (array or object) from an initializer list |
2027 The rules aim to create the best fit between a C++ initializer list and | 10943 The rules aim to create the best fit between a C++ initializer list and |
2028 JSON values. The rationale is as follows: | 10944 JSON values. The rationale is as follows: |
2029 | 10945 |
2030 1. The empty initializer list is written as `{}` which is exactly an empty | 10946 1. The empty initializer list is written as `{}` which is exactly an empty |
2031 JSON object. | 10947 JSON object. |
2032 2. C++ has now way of describing mapped types other than to list a list of | 10948 2. C++ has no way of describing mapped types other than to list a list of |
2033 pairs. As JSON requires that keys must be of type string, rule 2 is the | 10949 pairs. As JSON requires that keys must be of type string, rule 2 is the |
2034 weakest constraint one can pose on initializer lists to interpret them | 10950 weakest constraint one can pose on initializer lists to interpret them |
2035 as an object. | 10951 as an object. |
2036 3. In all other cases, the initializer list could not be interpreted as | 10952 3. In all other cases, the initializer list could not be interpreted as |
2037 JSON object type, so interpreting it as JSON array type is safe. | 10953 JSON object type, so interpreting it as JSON array type is safe. |
2038 | 10954 |
2039 With the rules described above, the following JSON values cannot be | 10955 With the rules described above, the following JSON values cannot be |
2040 expressed by an initializer list: | 10956 expressed by an initializer list: |
2041 | 10957 |
2042 - the empty array (`[]`): use @ref array(std::initializer_list<basic_json>) | 10958 - the empty array (`[]`): use @ref array(initializer_list_t) |
2043 with an empty initializer list in this case | 10959 with an empty initializer list in this case |
2044 - arrays whose elements satisfy rule 2: use @ref | 10960 - arrays whose elements satisfy rule 2: use @ref |
2045 array(std::initializer_list<basic_json>) with the same initializer list | 10961 array(initializer_list_t) with the same initializer list |
2046 in this case | 10962 in this case |
2047 | 10963 |
2048 @note When used without parentheses around an empty initializer list, @ref | 10964 @note When used without parentheses around an empty initializer list, @ref |
2049 basic_json() is called instead of this function, yielding the JSON null | 10965 basic_json() is called instead of this function, yielding the JSON null |
2050 value. | 10966 value. |
2052 @param[in] init initializer list with JSON values | 10968 @param[in] init initializer list with JSON values |
2053 | 10969 |
2054 @param[in] type_deduction internal parameter; when set to `true`, the type | 10970 @param[in] type_deduction internal parameter; when set to `true`, the type |
2055 of the JSON value is deducted from the initializer list @a init; when set | 10971 of the JSON value is deducted from the initializer list @a init; when set |
2056 to `false`, the type provided via @a manual_type is forced. This mode is | 10972 to `false`, the type provided via @a manual_type is forced. This mode is |
2057 used by the functions @ref array(std::initializer_list<basic_json>) and | 10973 used by the functions @ref array(initializer_list_t) and |
2058 @ref object(std::initializer_list<basic_json>). | 10974 @ref object(initializer_list_t). |
2059 | 10975 |
2060 @param[in] manual_type internal parameter; when @a type_deduction is set | 10976 @param[in] manual_type internal parameter; when @a type_deduction is set |
2061 to `false`, the created JSON value will use the provided type (only @ref | 10977 to `false`, the created JSON value will use the provided type (only @ref |
2062 value_t::array and @ref value_t::object are valid); when @a type_deduction | 10978 value_t::array and @ref value_t::object are valid); when @a type_deduction |
2063 is set to `true`, this parameter has no effect | 10979 is set to `true`, this parameter has no effect |
2064 | 10980 |
2065 @throw std::domain_error if @a type_deduction is `false`, @a manual_type | 10981 @throw type_error.301 if @a type_deduction is `false`, @a manual_type is |
2066 is `value_t::object`, but @a init contains an element which is not a pair | 10982 `value_t::object`, but @a init contains an element which is not a pair |
2067 whose first element is a string; example: `"cannot create object from | 10983 whose first element is a string. In this case, the constructor could not |
2068 initializer list"` | 10984 create an object. If @a type_deduction would have be `true`, an array |
10985 would have been created. See @ref object(initializer_list_t) | |
10986 for an example. | |
2069 | 10987 |
2070 @complexity Linear in the size of the initializer list @a init. | 10988 @complexity Linear in the size of the initializer list @a init. |
10989 | |
10990 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
10991 changes to any JSON value. | |
2071 | 10992 |
2072 @liveexample{The example below shows how JSON values are created from | 10993 @liveexample{The example below shows how JSON values are created from |
2073 initializer lists.,basic_json__list_init_t} | 10994 initializer lists.,basic_json__list_init_t} |
2074 | 10995 |
2075 @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array | 10996 @sa @ref array(initializer_list_t) -- create a JSON array |
2076 value from an initializer list | 10997 value from an initializer list |
2077 @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object | 10998 @sa @ref object(initializer_list_t) -- create a JSON object |
2078 value from an initializer list | 10999 value from an initializer list |
2079 | 11000 |
2080 @since version 1.0.0 | 11001 @since version 1.0.0 |
2081 */ | 11002 */ |
2082 basic_json(std::initializer_list<basic_json> init, | 11003 basic_json(initializer_list_t init, |
2083 bool type_deduction = true, | 11004 bool type_deduction = true, |
2084 value_t manual_type = value_t::array) | 11005 value_t manual_type = value_t::array) |
2085 { | 11006 { |
2086 // check if each element is an array with two elements whose first | 11007 // check if each element is an array with two elements whose first |
2087 // element is a string | 11008 // element is a string |
2088 bool is_an_object = std::all_of(init.begin(), init.end(), | 11009 bool is_an_object = std::all_of(init.begin(), init.end(), |
2089 [](const basic_json & element) | 11010 [](const detail::json_ref<basic_json>& element_ref) |
2090 { | 11011 { |
2091 return element.is_array() and element.size() == 2 and element[0].is_string(); | 11012 return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string()); |
2092 }); | 11013 }); |
2093 | 11014 |
2094 // adjust type if type deduction is not wanted | 11015 // adjust type if type deduction is not wanted |
2095 if (not type_deduction) | 11016 if (not type_deduction) |
2096 { | 11017 { |
2099 { | 11020 { |
2100 is_an_object = false; | 11021 is_an_object = false; |
2101 } | 11022 } |
2102 | 11023 |
2103 // if object is wanted but impossible, throw an exception | 11024 // if object is wanted but impossible, throw an exception |
2104 if (manual_type == value_t::object and not is_an_object) | 11025 if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object)) |
2105 { | 11026 { |
2106 JSON_THROW(std::domain_error("cannot create object from initializer list")); | 11027 JSON_THROW(type_error::create(301, "cannot create object from initializer list")); |
2107 } | 11028 } |
2108 } | 11029 } |
2109 | 11030 |
2110 if (is_an_object) | 11031 if (is_an_object) |
2111 { | 11032 { |
2112 // the initializer list is a list of pairs -> create object | 11033 // the initializer list is a list of pairs -> create object |
2113 m_type = value_t::object; | 11034 m_type = value_t::object; |
2114 m_value = value_t::object; | 11035 m_value = value_t::object; |
2115 | 11036 |
2116 std::for_each(init.begin(), init.end(), [this](const basic_json & element) | 11037 std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref) |
2117 { | 11038 { |
2118 m_value.object->emplace(*(element[0].m_value.string), element[1]); | 11039 auto element = element_ref.moved_or_copied(); |
11040 m_value.object->emplace( | |
11041 std::move(*((*element.m_value.array)[0].m_value.string)), | |
11042 std::move((*element.m_value.array)[1])); | |
2119 }); | 11043 }); |
2120 } | 11044 } |
2121 else | 11045 else |
2122 { | 11046 { |
2123 // the initializer list describes an array -> create array | 11047 // the initializer list describes an array -> create array |
2124 m_type = value_t::array; | 11048 m_type = value_t::array; |
2125 m_value.array = create<array_t>(init); | 11049 m_value.array = create<array_t>(init.begin(), init.end()); |
2126 } | 11050 } |
2127 | 11051 |
2128 assert_invariant(); | 11052 assert_invariant(); |
2129 } | 11053 } |
2130 | 11054 |
2135 list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the | 11059 list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the |
2136 initializer list is empty, the empty array `[]` is created. | 11060 initializer list is empty, the empty array `[]` is created. |
2137 | 11061 |
2138 @note This function is only needed to express two edge cases that cannot | 11062 @note This function is only needed to express two edge cases that cannot |
2139 be realized with the initializer list constructor (@ref | 11063 be realized with the initializer list constructor (@ref |
2140 basic_json(std::initializer_list<basic_json>, bool, value_t)). These cases | 11064 basic_json(initializer_list_t, bool, value_t)). These cases |
2141 are: | 11065 are: |
2142 1. creating an array whose elements are all pairs whose first element is a | 11066 1. creating an array whose elements are all pairs whose first element is a |
2143 string -- in this case, the initializer list constructor would create an | 11067 string -- in this case, the initializer list constructor would create an |
2144 object, taking the first elements as keys | 11068 object, taking the first elements as keys |
2145 2. creating an empty array -- passing the empty initializer list to the | 11069 2. creating an empty array -- passing the empty initializer list to the |
2150 | 11074 |
2151 @return JSON array value | 11075 @return JSON array value |
2152 | 11076 |
2153 @complexity Linear in the size of @a init. | 11077 @complexity Linear in the size of @a init. |
2154 | 11078 |
11079 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
11080 changes to any JSON value. | |
11081 | |
2155 @liveexample{The following code shows an example for the `array` | 11082 @liveexample{The following code shows an example for the `array` |
2156 function.,array} | 11083 function.,array} |
2157 | 11084 |
2158 @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) -- | 11085 @sa @ref basic_json(initializer_list_t, bool, value_t) -- |
2159 create a JSON value from an initializer list | 11086 create a JSON value from an initializer list |
2160 @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object | 11087 @sa @ref object(initializer_list_t) -- create a JSON object |
2161 value from an initializer list | 11088 value from an initializer list |
2162 | 11089 |
2163 @since version 1.0.0 | 11090 @since version 1.0.0 |
2164 */ | 11091 */ |
2165 static basic_json array(std::initializer_list<basic_json> init = | 11092 static basic_json array(initializer_list_t init = {}) |
2166 std::initializer_list<basic_json>()) | |
2167 { | 11093 { |
2168 return basic_json(init, false, value_t::array); | 11094 return basic_json(init, false, value_t::array); |
2169 } | 11095 } |
2170 | 11096 |
2171 /*! | 11097 /*! |
2174 Creates a JSON object value from a given initializer list. The initializer | 11100 Creates a JSON object value from a given initializer list. The initializer |
2175 lists elements must be pairs, and their first elements must be strings. If | 11101 lists elements must be pairs, and their first elements must be strings. If |
2176 the initializer list is empty, the empty object `{}` is created. | 11102 the initializer list is empty, the empty object `{}` is created. |
2177 | 11103 |
2178 @note This function is only added for symmetry reasons. In contrast to the | 11104 @note This function is only added for symmetry reasons. In contrast to the |
2179 related function @ref array(std::initializer_list<basic_json>), there are | 11105 related function @ref array(initializer_list_t), there are |
2180 no cases which can only be expressed by this function. That is, any | 11106 no cases which can only be expressed by this function. That is, any |
2181 initializer list @a init can also be passed to the initializer list | 11107 initializer list @a init can also be passed to the initializer list |
2182 constructor @ref basic_json(std::initializer_list<basic_json>, bool, | 11108 constructor @ref basic_json(initializer_list_t, bool, value_t). |
2183 value_t). | |
2184 | 11109 |
2185 @param[in] init initializer list to create an object from (optional) | 11110 @param[in] init initializer list to create an object from (optional) |
2186 | 11111 |
2187 @return JSON object value | 11112 @return JSON object value |
2188 | 11113 |
2189 @throw std::domain_error if @a init is not a pair whose first elements are | 11114 @throw type_error.301 if @a init is not a list of pairs whose first |
2190 strings; thrown by | 11115 elements are strings. In this case, no object can be created. When such a |
2191 @ref basic_json(std::initializer_list<basic_json>, bool, value_t) | 11116 value is passed to @ref basic_json(initializer_list_t, bool, value_t), |
11117 an array would have been created from the passed initializer list @a init. | |
11118 See example below. | |
2192 | 11119 |
2193 @complexity Linear in the size of @a init. | 11120 @complexity Linear in the size of @a init. |
11121 | |
11122 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
11123 changes to any JSON value. | |
2194 | 11124 |
2195 @liveexample{The following code shows an example for the `object` | 11125 @liveexample{The following code shows an example for the `object` |
2196 function.,object} | 11126 function.,object} |
2197 | 11127 |
2198 @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) -- | 11128 @sa @ref basic_json(initializer_list_t, bool, value_t) -- |
2199 create a JSON value from an initializer list | 11129 create a JSON value from an initializer list |
2200 @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array | 11130 @sa @ref array(initializer_list_t) -- create a JSON array |
2201 value from an initializer list | 11131 value from an initializer list |
2202 | 11132 |
2203 @since version 1.0.0 | 11133 @since version 1.0.0 |
2204 */ | 11134 */ |
2205 static basic_json object(std::initializer_list<basic_json> init = | 11135 static basic_json object(initializer_list_t init = {}) |
2206 std::initializer_list<basic_json>()) | |
2207 { | 11136 { |
2208 return basic_json(init, false, value_t::object); | 11137 return basic_json(init, false, value_t::object); |
2209 } | 11138 } |
2210 | 11139 |
2211 /*! | 11140 /*! |
2212 @brief construct an array with count copies of given value | 11141 @brief construct an array with count copies of given value |
2213 | 11142 |
2214 Constructs a JSON array value by creating @a cnt copies of a passed value. | 11143 Constructs a JSON array value by creating @a cnt copies of a passed value. |
2215 In case @a cnt is `0`, an empty array is created. As postcondition, | 11144 In case @a cnt is `0`, an empty array is created. |
2216 `std::distance(begin(),end()) == cnt` holds. | |
2217 | 11145 |
2218 @param[in] cnt the number of JSON copies of @a val to create | 11146 @param[in] cnt the number of JSON copies of @a val to create |
2219 @param[in] val the JSON value to copy | 11147 @param[in] val the JSON value to copy |
2220 | 11148 |
11149 @post `std::distance(begin(),end()) == cnt` holds. | |
11150 | |
2221 @complexity Linear in @a cnt. | 11151 @complexity Linear in @a cnt. |
11152 | |
11153 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
11154 changes to any JSON value. | |
2222 | 11155 |
2223 @liveexample{The following code shows examples for the @ref | 11156 @liveexample{The following code shows examples for the @ref |
2224 basic_json(size_type\, const basic_json&) | 11157 basic_json(size_type\, const basic_json&) |
2225 constructor.,basic_json__size_type_basic_json} | 11158 constructor.,basic_json__size_type_basic_json} |
2226 | 11159 |
2236 /*! | 11169 /*! |
2237 @brief construct a JSON container given an iterator range | 11170 @brief construct a JSON container given an iterator range |
2238 | 11171 |
2239 Constructs the JSON value with the contents of the range `[first, last)`. | 11172 Constructs the JSON value with the contents of the range `[first, last)`. |
2240 The semantics depends on the different types a JSON value can have: | 11173 The semantics depends on the different types a JSON value can have: |
2241 - In case of primitive types (number, boolean, or string), @a first must | 11174 - In case of a null type, invalid_iterator.206 is thrown. |
2242 be `begin()` and @a last must be `end()`. In this case, the value is | 11175 - In case of other primitive types (number, boolean, or string), @a first |
2243 copied. Otherwise, std::out_of_range is thrown. | 11176 must be `begin()` and @a last must be `end()`. In this case, the value is |
11177 copied. Otherwise, invalid_iterator.204 is thrown. | |
2244 - In case of structured types (array, object), the constructor behaves as | 11178 - In case of structured types (array, object), the constructor behaves as |
2245 similar versions for `std::vector`. | 11179 similar versions for `std::vector` or `std::map`; that is, a JSON array |
2246 - In case of a null type, std::domain_error is thrown. | 11180 or object is constructed from the values in the range. |
2247 | 11181 |
2248 @tparam InputIT an input iterator type (@ref iterator or @ref | 11182 @tparam InputIT an input iterator type (@ref iterator or @ref |
2249 const_iterator) | 11183 const_iterator) |
2250 | 11184 |
2251 @param[in] first begin of the range to copy from (included) | 11185 @param[in] first begin of the range to copy from (included) |
2252 @param[in] last end of the range to copy from (excluded) | 11186 @param[in] last end of the range to copy from (excluded) |
2253 | 11187 |
2254 @pre Iterators @a first and @a last must be initialized. **This | 11188 @pre Iterators @a first and @a last must be initialized. **This |
2255 precondition is enforced with an assertion.** | 11189 precondition is enforced with an assertion (see warning).** If |
2256 | 11190 assertions are switched off, a violation of this precondition yields |
2257 @throw std::domain_error if iterators are not compatible; that is, do not | 11191 undefined behavior. |
2258 belong to the same JSON value; example: `"iterators are not compatible"` | 11192 |
2259 @throw std::out_of_range if iterators are for a primitive type (number, | 11193 @pre Range `[first, last)` is valid. Usually, this precondition cannot be |
2260 boolean, or string) where an out of range error can be detected easily; | 11194 checked efficiently. Only certain edge cases are detected; see the |
2261 example: `"iterators out of range"` | 11195 description of the exceptions below. A violation of this precondition |
2262 @throw std::bad_alloc if allocation for object, array, or string fails | 11196 yields undefined behavior. |
2263 @throw std::domain_error if called with a null value; example: `"cannot | 11197 |
2264 use construct with iterators from null"` | 11198 @warning A precondition is enforced with a runtime assertion that will |
11199 result in calling `std::abort` if this precondition is not met. | |
11200 Assertions can be disabled by defining `NDEBUG` at compile time. | |
11201 See http://en.cppreference.com/w/cpp/error/assert for more | |
11202 information. | |
11203 | |
11204 @throw invalid_iterator.201 if iterators @a first and @a last are not | |
11205 compatible (i.e., do not belong to the same JSON value). In this case, | |
11206 the range `[first, last)` is undefined. | |
11207 @throw invalid_iterator.204 if iterators @a first and @a last belong to a | |
11208 primitive type (number, boolean, or string), but @a first does not point | |
11209 to the first element any more. In this case, the range `[first, last)` is | |
11210 undefined. See example code below. | |
11211 @throw invalid_iterator.206 if iterators @a first and @a last belong to a | |
11212 null value. In this case, the range `[first, last)` is undefined. | |
2265 | 11213 |
2266 @complexity Linear in distance between @a first and @a last. | 11214 @complexity Linear in distance between @a first and @a last. |
11215 | |
11216 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
11217 changes to any JSON value. | |
2267 | 11218 |
2268 @liveexample{The example below shows several ways to create JSON values by | 11219 @liveexample{The example below shows several ways to create JSON values by |
2269 specifying a subrange with iterators.,basic_json__InputIt_InputIt} | 11220 specifying a subrange with iterators.,basic_json__InputIt_InputIt} |
2270 | 11221 |
2271 @since version 1.0.0 | 11222 @since version 1.0.0 |
2277 { | 11228 { |
2278 assert(first.m_object != nullptr); | 11229 assert(first.m_object != nullptr); |
2279 assert(last.m_object != nullptr); | 11230 assert(last.m_object != nullptr); |
2280 | 11231 |
2281 // make sure iterator fits the current value | 11232 // make sure iterator fits the current value |
2282 if (first.m_object != last.m_object) | 11233 if (JSON_UNLIKELY(first.m_object != last.m_object)) |
2283 { | 11234 { |
2284 JSON_THROW(std::domain_error("iterators are not compatible")); | 11235 JSON_THROW(invalid_iterator::create(201, "iterators are not compatible")); |
2285 } | 11236 } |
2286 | 11237 |
2287 // copy type from first iterator | 11238 // copy type from first iterator |
2288 m_type = first.m_object->m_type; | 11239 m_type = first.m_object->m_type; |
2289 | 11240 |
2294 case value_t::number_float: | 11245 case value_t::number_float: |
2295 case value_t::number_integer: | 11246 case value_t::number_integer: |
2296 case value_t::number_unsigned: | 11247 case value_t::number_unsigned: |
2297 case value_t::string: | 11248 case value_t::string: |
2298 { | 11249 { |
2299 if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end()) | 11250 if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin() |
2300 { | 11251 or not last.m_it.primitive_iterator.is_end())) |
2301 JSON_THROW(std::out_of_range("iterators out of range")); | 11252 { |
11253 JSON_THROW(invalid_iterator::create(204, "iterators out of range")); | |
2302 } | 11254 } |
2303 break; | 11255 break; |
2304 } | 11256 } |
2305 | 11257 |
2306 default: | 11258 default: |
2307 { | |
2308 break; | 11259 break; |
2309 } | |
2310 } | 11260 } |
2311 | 11261 |
2312 switch (m_type) | 11262 switch (m_type) |
2313 { | 11263 { |
2314 case value_t::number_integer: | 11264 case value_t::number_integer: |
2354 last.m_it.array_iterator); | 11304 last.m_it.array_iterator); |
2355 break; | 11305 break; |
2356 } | 11306 } |
2357 | 11307 |
2358 default: | 11308 default: |
2359 { | 11309 JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + |
2360 JSON_THROW(std::domain_error("cannot use construct with iterators from " + first.m_object->type_name())); | 11310 std::string(first.m_object->type_name()))); |
2361 } | |
2362 } | 11311 } |
2363 | 11312 |
2364 assert_invariant(); | 11313 assert_invariant(); |
2365 } | 11314 } |
2366 | 11315 |
2367 /*! | |
2368 @brief construct a JSON value given an input stream | |
2369 | |
2370 @param[in,out] i stream to read a serialized JSON value from | |
2371 @param[in] cb a parser callback function of type @ref parser_callback_t | |
2372 which is used to control the deserialization by filtering unwanted values | |
2373 (optional) | |
2374 | |
2375 @complexity Linear in the length of the input. The parser is a predictive | |
2376 LL(1) parser. The complexity can be higher if the parser callback function | |
2377 @a cb has a super-linear complexity. | |
2378 | |
2379 @note A UTF-8 byte order mark is silently ignored. | |
2380 | |
2381 @deprecated This constructor is deprecated and will be removed in version | |
2382 3.0.0 to unify the interface of the library. Deserialization will be | |
2383 done by stream operators or by calling one of the `parse` functions, | |
2384 e.g. @ref parse(std::istream&, const parser_callback_t). That is, calls | |
2385 like `json j(i);` for an input stream @a i need to be replaced by | |
2386 `json j = json::parse(i);`. See the example below. | |
2387 | |
2388 @liveexample{The example below demonstrates constructing a JSON value from | |
2389 a `std::stringstream` with and without callback | |
2390 function.,basic_json__istream} | |
2391 | |
2392 @since version 2.0.0, deprecated in version 2.0.3, to be removed in | |
2393 version 3.0.0 | |
2394 */ | |
2395 JSON_DEPRECATED | |
2396 explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr) | |
2397 { | |
2398 *this = parser(i, cb).parse(); | |
2399 assert_invariant(); | |
2400 } | |
2401 | 11316 |
2402 /////////////////////////////////////// | 11317 /////////////////////////////////////// |
2403 // other constructors and destructor // | 11318 // other constructors and destructor // |
2404 /////////////////////////////////////// | 11319 /////////////////////////////////////// |
2405 | 11320 |
11321 /// @private | |
11322 basic_json(const detail::json_ref<basic_json>& ref) | |
11323 : basic_json(ref.moved_or_copied()) | |
11324 {} | |
11325 | |
2406 /*! | 11326 /*! |
2407 @brief copy constructor | 11327 @brief copy constructor |
2408 | 11328 |
2409 Creates a copy of a given JSON value. | 11329 Creates a copy of a given JSON value. |
2410 | 11330 |
2411 @param[in] other the JSON value to copy | 11331 @param[in] other the JSON value to copy |
2412 | 11332 |
11333 @post `*this == other` | |
11334 | |
2413 @complexity Linear in the size of @a other. | 11335 @complexity Linear in the size of @a other. |
11336 | |
11337 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
11338 changes to any JSON value. | |
2414 | 11339 |
2415 @requirement This function helps `basic_json` satisfying the | 11340 @requirement This function helps `basic_json` satisfying the |
2416 [Container](http://en.cppreference.com/w/cpp/concept/Container) | 11341 [Container](http://en.cppreference.com/w/cpp/concept/Container) |
2417 requirements: | 11342 requirements: |
2418 - The complexity is linear. | 11343 - The complexity is linear. |
2419 - As postcondition, it holds: `other == basic_json(other)`. | 11344 - As postcondition, it holds: `other == basic_json(other)`. |
2420 | 11345 |
2421 @throw std::bad_alloc if allocation for object, array, or string fails. | |
2422 | |
2423 @liveexample{The following code shows an example for the copy | 11346 @liveexample{The following code shows an example for the copy |
2424 constructor.,basic_json__basic_json} | 11347 constructor.,basic_json__basic_json} |
2425 | 11348 |
2426 @since version 1.0.0 | 11349 @since version 1.0.0 |
2427 */ | 11350 */ |
2474 m_value = other.m_value.number_float; | 11397 m_value = other.m_value.number_float; |
2475 break; | 11398 break; |
2476 } | 11399 } |
2477 | 11400 |
2478 default: | 11401 default: |
2479 { | |
2480 break; | 11402 break; |
2481 } | |
2482 } | 11403 } |
2483 | 11404 |
2484 assert_invariant(); | 11405 assert_invariant(); |
2485 } | 11406 } |
2486 | 11407 |
2491 value @a other using move semantics. It "steals" the resources from @a | 11412 value @a other using move semantics. It "steals" the resources from @a |
2492 other and leaves it as JSON null value. | 11413 other and leaves it as JSON null value. |
2493 | 11414 |
2494 @param[in,out] other value to move to this object | 11415 @param[in,out] other value to move to this object |
2495 | 11416 |
2496 @post @a other is a JSON null value | 11417 @post `*this` has the same value as @a other before the call. |
11418 @post @a other is a JSON null value. | |
2497 | 11419 |
2498 @complexity Constant. | 11420 @complexity Constant. |
11421 | |
11422 @exceptionsafety No-throw guarantee: this constructor never throws | |
11423 exceptions. | |
11424 | |
11425 @requirement This function helps `basic_json` satisfying the | |
11426 [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible) | |
11427 requirements. | |
2499 | 11428 |
2500 @liveexample{The code below shows the move constructor explicitly called | 11429 @liveexample{The code below shows the move constructor explicitly called |
2501 via std::move.,basic_json__moveconstructor} | 11430 via std::move.,basic_json__moveconstructor} |
2502 | 11431 |
2503 @since version 1.0.0 | 11432 @since version 1.0.0 |
2519 /*! | 11448 /*! |
2520 @brief copy assignment | 11449 @brief copy assignment |
2521 | 11450 |
2522 Copy assignment operator. Copies a JSON value via the "copy and swap" | 11451 Copy assignment operator. Copies a JSON value via the "copy and swap" |
2523 strategy: It is expressed in terms of the copy constructor, destructor, | 11452 strategy: It is expressed in terms of the copy constructor, destructor, |
2524 and the swap() member function. | 11453 and the `swap()` member function. |
2525 | 11454 |
2526 @param[in] other value to copy from | 11455 @param[in] other value to copy from |
2527 | 11456 |
2528 @complexity Linear. | 11457 @complexity Linear. |
2529 | 11458 |
2570 - The complexity is linear. | 11499 - The complexity is linear. |
2571 - All stored elements are destroyed and all memory is freed. | 11500 - All stored elements are destroyed and all memory is freed. |
2572 | 11501 |
2573 @since version 1.0.0 | 11502 @since version 1.0.0 |
2574 */ | 11503 */ |
2575 ~basic_json() | 11504 ~basic_json() noexcept |
2576 { | 11505 { |
2577 assert_invariant(); | 11506 assert_invariant(); |
2578 | 11507 m_value.destroy(m_type); |
2579 switch (m_type) | |
2580 { | |
2581 case value_t::object: | |
2582 { | |
2583 AllocatorType<object_t> alloc; | |
2584 alloc.destroy(m_value.object); | |
2585 alloc.deallocate(m_value.object, 1); | |
2586 break; | |
2587 } | |
2588 | |
2589 case value_t::array: | |
2590 { | |
2591 AllocatorType<array_t> alloc; | |
2592 alloc.destroy(m_value.array); | |
2593 alloc.deallocate(m_value.array, 1); | |
2594 break; | |
2595 } | |
2596 | |
2597 case value_t::string: | |
2598 { | |
2599 AllocatorType<string_t> alloc; | |
2600 alloc.destroy(m_value.string); | |
2601 alloc.deallocate(m_value.string, 1); | |
2602 break; | |
2603 } | |
2604 | |
2605 default: | |
2606 { | |
2607 // all other types need no specific destructor | |
2608 break; | |
2609 } | |
2610 } | |
2611 } | 11508 } |
2612 | 11509 |
2613 /// @} | 11510 /// @} |
2614 | 11511 |
2615 public: | 11512 public: |
2624 /*! | 11521 /*! |
2625 @brief serialization | 11522 @brief serialization |
2626 | 11523 |
2627 Serialization function for JSON values. The function tries to mimic | 11524 Serialization function for JSON values. The function tries to mimic |
2628 Python's `json.dumps()` function, and currently supports its @a indent | 11525 Python's `json.dumps()` function, and currently supports its @a indent |
2629 parameter. | 11526 and @a ensure_ascii parameters. |
2630 | 11527 |
2631 @param[in] indent If indent is nonnegative, then array elements and object | 11528 @param[in] indent If indent is nonnegative, then array elements and object |
2632 members will be pretty-printed with that indent level. An indent level of | 11529 members will be pretty-printed with that indent level. An indent level of |
2633 `0` will only insert newlines. `-1` (the default) selects the most compact | 11530 `0` will only insert newlines. `-1` (the default) selects the most compact |
2634 representation. | 11531 representation. |
11532 @param[in] indent_char The character to use for indentation if @a indent is | |
11533 greater than `0`. The default is ` ` (space). | |
11534 @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters | |
11535 in the output are escaped with `\uXXXX` sequences, and the result consists | |
11536 of ASCII characters only. | |
2635 | 11537 |
2636 @return string containing the serialization of the JSON value | 11538 @return string containing the serialization of the JSON value |
2637 | 11539 |
11540 @throw type_error.316 if a string stored inside the JSON value is not | |
11541 UTF-8 encoded | |
11542 | |
2638 @complexity Linear. | 11543 @complexity Linear. |
2639 | 11544 |
2640 @liveexample{The following example shows the effect of different @a indent | 11545 @exceptionsafety Strong guarantee: if an exception is thrown, there are no |
2641 parameters to the result of the serialization.,dump} | 11546 changes in the JSON value. |
11547 | |
11548 @liveexample{The following example shows the effect of different @a indent\, | |
11549 @a indent_char\, and @a ensure_ascii parameters to the result of the | |
11550 serialization.,dump} | |
2642 | 11551 |
2643 @see https://docs.python.org/2/library/json.html#json.dump | 11552 @see https://docs.python.org/2/library/json.html#json.dump |
2644 | 11553 |
2645 @since version 1.0.0 | 11554 @since version 1.0.0; indentation character @a indent_char, option |
2646 */ | 11555 @a ensure_ascii and exceptions added in version 3.0.0 |
2647 string_t dump(const int indent = -1) const | 11556 */ |
2648 { | 11557 string_t dump(const int indent = -1, const char indent_char = ' ', |
2649 std::stringstream ss; | 11558 const bool ensure_ascii = false) const |
11559 { | |
11560 string_t result; | |
11561 serializer s(detail::output_adapter<char, string_t>(result), indent_char); | |
2650 | 11562 |
2651 if (indent >= 0) | 11563 if (indent >= 0) |
2652 { | 11564 { |
2653 dump(ss, true, static_cast<unsigned int>(indent)); | 11565 s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent)); |
2654 } | 11566 } |
2655 else | 11567 else |
2656 { | 11568 { |
2657 dump(ss, false, 0); | 11569 s.dump(*this, false, ensure_ascii, 0); |
2658 } | 11570 } |
2659 | 11571 |
2660 return ss.str(); | 11572 return result; |
2661 } | 11573 } |
2662 | 11574 |
2663 /*! | 11575 /*! |
2664 @brief return the type of the JSON value (explicit) | 11576 @brief return the type of the JSON value (explicit) |
2665 | 11577 |
2666 Return the type of the JSON value as a value from the @ref value_t | 11578 Return the type of the JSON value as a value from the @ref value_t |
2667 enumeration. | 11579 enumeration. |
2668 | 11580 |
2669 @return the type of the JSON value | 11581 @return the type of the JSON value |
11582 Value type | return value | |
11583 ------------------------- | ------------------------- | |
11584 null | value_t::null | |
11585 boolean | value_t::boolean | |
11586 string | value_t::string | |
11587 number (integer) | value_t::number_integer | |
11588 number (unsigned integer) | value_t::number_unsigned | |
11589 number (floating-point) | value_t::number_float | |
11590 object | value_t::object | |
11591 array | value_t::array | |
11592 discarded | value_t::discarded | |
2670 | 11593 |
2671 @complexity Constant. | 11594 @complexity Constant. |
2672 | 11595 |
2673 @exceptionsafety No-throw guarantee: this member function never throws | 11596 @exceptionsafety No-throw guarantee: this member function never throws |
2674 exceptions. | 11597 exceptions. |
2675 | 11598 |
2676 @liveexample{The following code exemplifies `type()` for all JSON | 11599 @liveexample{The following code exemplifies `type()` for all JSON |
2677 types.,type} | 11600 types.,type} |
2678 | 11601 |
11602 @sa @ref operator value_t() -- return the type of the JSON value (implicit) | |
11603 @sa @ref type_name() -- return the type as string | |
11604 | |
2679 @since version 1.0.0 | 11605 @since version 1.0.0 |
2680 */ | 11606 */ |
2681 constexpr value_t type() const noexcept | 11607 constexpr value_t type() const noexcept |
2682 { | 11608 { |
2683 return m_type; | 11609 return m_type; |
2684 } | 11610 } |
2685 | 11611 |
2686 /*! | 11612 /*! |
2687 @brief return whether type is primitive | 11613 @brief return whether type is primitive |
2688 | 11614 |
2689 This function returns true iff the JSON type is primitive (string, number, | 11615 This function returns true if and only if the JSON type is primitive |
2690 boolean, or null). | 11616 (string, number, boolean, or null). |
2691 | 11617 |
2692 @return `true` if type is primitive (string, number, boolean, or null), | 11618 @return `true` if type is primitive (string, number, boolean, or null), |
2693 `false` otherwise. | 11619 `false` otherwise. |
2694 | 11620 |
2695 @complexity Constant. | 11621 @complexity Constant. |
2714 } | 11640 } |
2715 | 11641 |
2716 /*! | 11642 /*! |
2717 @brief return whether type is structured | 11643 @brief return whether type is structured |
2718 | 11644 |
2719 This function returns true iff the JSON type is structured (array or | 11645 This function returns true if and only if the JSON type is structured |
2720 object). | 11646 (array or object). |
2721 | 11647 |
2722 @return `true` if type is structured (array or object), `false` otherwise. | 11648 @return `true` if type is structured (array or object), `false` otherwise. |
2723 | 11649 |
2724 @complexity Constant. | 11650 @complexity Constant. |
2725 | 11651 |
2741 } | 11667 } |
2742 | 11668 |
2743 /*! | 11669 /*! |
2744 @brief return whether value is null | 11670 @brief return whether value is null |
2745 | 11671 |
2746 This function returns true iff the JSON value is null. | 11672 This function returns true if and only if the JSON value is null. |
2747 | 11673 |
2748 @return `true` if type is null, `false` otherwise. | 11674 @return `true` if type is null, `false` otherwise. |
2749 | 11675 |
2750 @complexity Constant. | 11676 @complexity Constant. |
2751 | 11677 |
2757 | 11683 |
2758 @since version 1.0.0 | 11684 @since version 1.0.0 |
2759 */ | 11685 */ |
2760 constexpr bool is_null() const noexcept | 11686 constexpr bool is_null() const noexcept |
2761 { | 11687 { |
2762 return m_type == value_t::null; | 11688 return (m_type == value_t::null); |
2763 } | 11689 } |
2764 | 11690 |
2765 /*! | 11691 /*! |
2766 @brief return whether value is a boolean | 11692 @brief return whether value is a boolean |
2767 | 11693 |
2768 This function returns true iff the JSON value is a boolean. | 11694 This function returns true if and only if the JSON value is a boolean. |
2769 | 11695 |
2770 @return `true` if type is boolean, `false` otherwise. | 11696 @return `true` if type is boolean, `false` otherwise. |
2771 | 11697 |
2772 @complexity Constant. | 11698 @complexity Constant. |
2773 | 11699 |
2779 | 11705 |
2780 @since version 1.0.0 | 11706 @since version 1.0.0 |
2781 */ | 11707 */ |
2782 constexpr bool is_boolean() const noexcept | 11708 constexpr bool is_boolean() const noexcept |
2783 { | 11709 { |
2784 return m_type == value_t::boolean; | 11710 return (m_type == value_t::boolean); |
2785 } | 11711 } |
2786 | 11712 |
2787 /*! | 11713 /*! |
2788 @brief return whether value is a number | 11714 @brief return whether value is a number |
2789 | 11715 |
2790 This function returns true iff the JSON value is a number. This includes | 11716 This function returns true if and only if the JSON value is a number. This |
2791 both integer and floating-point values. | 11717 includes both integer (signed and unsigned) and floating-point values. |
2792 | 11718 |
2793 @return `true` if type is number (regardless whether integer, unsigned | 11719 @return `true` if type is number (regardless whether integer, unsigned |
2794 integer or floating-type), `false` otherwise. | 11720 integer or floating-type), `false` otherwise. |
2795 | 11721 |
2796 @complexity Constant. | 11722 @complexity Constant. |
2815 } | 11741 } |
2816 | 11742 |
2817 /*! | 11743 /*! |
2818 @brief return whether value is an integer number | 11744 @brief return whether value is an integer number |
2819 | 11745 |
2820 This function returns true iff the JSON value is an integer or unsigned | 11746 This function returns true if and only if the JSON value is a signed or |
2821 integer number. This excludes floating-point values. | 11747 unsigned integer number. This excludes floating-point values. |
2822 | 11748 |
2823 @return `true` if type is an integer or unsigned integer number, `false` | 11749 @return `true` if type is an integer or unsigned integer number, `false` |
2824 otherwise. | 11750 otherwise. |
2825 | 11751 |
2826 @complexity Constant. | 11752 @complexity Constant. |
2838 | 11764 |
2839 @since version 1.0.0 | 11765 @since version 1.0.0 |
2840 */ | 11766 */ |
2841 constexpr bool is_number_integer() const noexcept | 11767 constexpr bool is_number_integer() const noexcept |
2842 { | 11768 { |
2843 return m_type == value_t::number_integer or m_type == value_t::number_unsigned; | 11769 return (m_type == value_t::number_integer or m_type == value_t::number_unsigned); |
2844 } | 11770 } |
2845 | 11771 |
2846 /*! | 11772 /*! |
2847 @brief return whether value is an unsigned integer number | 11773 @brief return whether value is an unsigned integer number |
2848 | 11774 |
2849 This function returns true iff the JSON value is an unsigned integer | 11775 This function returns true if and only if the JSON value is an unsigned |
2850 number. This excludes floating-point and (signed) integer values. | 11776 integer number. This excludes floating-point and signed integer values. |
2851 | 11777 |
2852 @return `true` if type is an unsigned integer number, `false` otherwise. | 11778 @return `true` if type is an unsigned integer number, `false` otherwise. |
2853 | 11779 |
2854 @complexity Constant. | 11780 @complexity Constant. |
2855 | 11781 |
2866 | 11792 |
2867 @since version 2.0.0 | 11793 @since version 2.0.0 |
2868 */ | 11794 */ |
2869 constexpr bool is_number_unsigned() const noexcept | 11795 constexpr bool is_number_unsigned() const noexcept |
2870 { | 11796 { |
2871 return m_type == value_t::number_unsigned; | 11797 return (m_type == value_t::number_unsigned); |
2872 } | 11798 } |
2873 | 11799 |
2874 /*! | 11800 /*! |
2875 @brief return whether value is a floating-point number | 11801 @brief return whether value is a floating-point number |
2876 | 11802 |
2877 This function returns true iff the JSON value is a floating-point number. | 11803 This function returns true if and only if the JSON value is a |
2878 This excludes integer and unsigned integer values. | 11804 floating-point number. This excludes signed and unsigned integer values. |
2879 | 11805 |
2880 @return `true` if type is a floating-point number, `false` otherwise. | 11806 @return `true` if type is a floating-point number, `false` otherwise. |
2881 | 11807 |
2882 @complexity Constant. | 11808 @complexity Constant. |
2883 | 11809 |
2894 | 11820 |
2895 @since version 1.0.0 | 11821 @since version 1.0.0 |
2896 */ | 11822 */ |
2897 constexpr bool is_number_float() const noexcept | 11823 constexpr bool is_number_float() const noexcept |
2898 { | 11824 { |
2899 return m_type == value_t::number_float; | 11825 return (m_type == value_t::number_float); |
2900 } | 11826 } |
2901 | 11827 |
2902 /*! | 11828 /*! |
2903 @brief return whether value is an object | 11829 @brief return whether value is an object |
2904 | 11830 |
2905 This function returns true iff the JSON value is an object. | 11831 This function returns true if and only if the JSON value is an object. |
2906 | 11832 |
2907 @return `true` if type is object, `false` otherwise. | 11833 @return `true` if type is object, `false` otherwise. |
2908 | 11834 |
2909 @complexity Constant. | 11835 @complexity Constant. |
2910 | 11836 |
2916 | 11842 |
2917 @since version 1.0.0 | 11843 @since version 1.0.0 |
2918 */ | 11844 */ |
2919 constexpr bool is_object() const noexcept | 11845 constexpr bool is_object() const noexcept |
2920 { | 11846 { |
2921 return m_type == value_t::object; | 11847 return (m_type == value_t::object); |
2922 } | 11848 } |
2923 | 11849 |
2924 /*! | 11850 /*! |
2925 @brief return whether value is an array | 11851 @brief return whether value is an array |
2926 | 11852 |
2927 This function returns true iff the JSON value is an array. | 11853 This function returns true if and only if the JSON value is an array. |
2928 | 11854 |
2929 @return `true` if type is array, `false` otherwise. | 11855 @return `true` if type is array, `false` otherwise. |
2930 | 11856 |
2931 @complexity Constant. | 11857 @complexity Constant. |
2932 | 11858 |
2938 | 11864 |
2939 @since version 1.0.0 | 11865 @since version 1.0.0 |
2940 */ | 11866 */ |
2941 constexpr bool is_array() const noexcept | 11867 constexpr bool is_array() const noexcept |
2942 { | 11868 { |
2943 return m_type == value_t::array; | 11869 return (m_type == value_t::array); |
2944 } | 11870 } |
2945 | 11871 |
2946 /*! | 11872 /*! |
2947 @brief return whether value is a string | 11873 @brief return whether value is a string |
2948 | 11874 |
2949 This function returns true iff the JSON value is a string. | 11875 This function returns true if and only if the JSON value is a string. |
2950 | 11876 |
2951 @return `true` if type is string, `false` otherwise. | 11877 @return `true` if type is string, `false` otherwise. |
2952 | 11878 |
2953 @complexity Constant. | 11879 @complexity Constant. |
2954 | 11880 |
2960 | 11886 |
2961 @since version 1.0.0 | 11887 @since version 1.0.0 |
2962 */ | 11888 */ |
2963 constexpr bool is_string() const noexcept | 11889 constexpr bool is_string() const noexcept |
2964 { | 11890 { |
2965 return m_type == value_t::string; | 11891 return (m_type == value_t::string); |
2966 } | 11892 } |
2967 | 11893 |
2968 /*! | 11894 /*! |
2969 @brief return whether value is discarded | 11895 @brief return whether value is discarded |
2970 | 11896 |
2971 This function returns true iff the JSON value was discarded during parsing | 11897 This function returns true if and only if the JSON value was discarded |
2972 with a callback function (see @ref parser_callback_t). | 11898 during parsing with a callback function (see @ref parser_callback_t). |
2973 | 11899 |
2974 @note This function will always be `false` for JSON values after parsing. | 11900 @note This function will always be `false` for JSON values after parsing. |
2975 That is, discarded values can only occur during parsing, but will be | 11901 That is, discarded values can only occur during parsing, but will be |
2976 removed when inside a structured value or replaced by null in other cases. | 11902 removed when inside a structured value or replaced by null in other cases. |
2977 | 11903 |
2987 | 11913 |
2988 @since version 1.0.0 | 11914 @since version 1.0.0 |
2989 */ | 11915 */ |
2990 constexpr bool is_discarded() const noexcept | 11916 constexpr bool is_discarded() const noexcept |
2991 { | 11917 { |
2992 return m_type == value_t::discarded; | 11918 return (m_type == value_t::discarded); |
2993 } | 11919 } |
2994 | 11920 |
2995 /*! | 11921 /*! |
2996 @brief return the type of the JSON value (implicit) | 11922 @brief return the type of the JSON value (implicit) |
2997 | 11923 |
3005 @exceptionsafety No-throw guarantee: this member function never throws | 11931 @exceptionsafety No-throw guarantee: this member function never throws |
3006 exceptions. | 11932 exceptions. |
3007 | 11933 |
3008 @liveexample{The following code exemplifies the @ref value_t operator for | 11934 @liveexample{The following code exemplifies the @ref value_t operator for |
3009 all JSON types.,operator__value_t} | 11935 all JSON types.,operator__value_t} |
11936 | |
11937 @sa @ref type() -- return the type of the JSON value (explicit) | |
11938 @sa @ref type_name() -- return the type as string | |
3010 | 11939 |
3011 @since version 1.0.0 | 11940 @since version 1.0.0 |
3012 */ | 11941 */ |
3013 constexpr operator value_t() const noexcept | 11942 constexpr operator value_t() const noexcept |
3014 { | 11943 { |
3023 ////////////////// | 11952 ////////////////// |
3024 | 11953 |
3025 /// get a boolean (explicit) | 11954 /// get a boolean (explicit) |
3026 boolean_t get_impl(boolean_t* /*unused*/) const | 11955 boolean_t get_impl(boolean_t* /*unused*/) const |
3027 { | 11956 { |
3028 if (is_boolean()) | 11957 if (JSON_LIKELY(is_boolean())) |
3029 { | 11958 { |
3030 return m_value.boolean; | 11959 return m_value.boolean; |
3031 } | 11960 } |
3032 | 11961 |
3033 JSON_THROW(std::domain_error("type must be boolean, but is " + type_name())); | 11962 JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()))); |
3034 } | 11963 } |
3035 | 11964 |
3036 /// get a pointer to the value (object) | 11965 /// get a pointer to the value (object) |
3037 object_t* get_impl_ptr(object_t* /*unused*/) noexcept | 11966 object_t* get_impl_ptr(object_t* /*unused*/) noexcept |
3038 { | 11967 { |
3118 } | 12047 } |
3119 | 12048 |
3120 /*! | 12049 /*! |
3121 @brief helper function to implement get_ref() | 12050 @brief helper function to implement get_ref() |
3122 | 12051 |
3123 This funcion helps to implement get_ref() without code duplication for | 12052 This function helps to implement get_ref() without code duplication for |
3124 const and non-const overloads | 12053 const and non-const overloads |
3125 | 12054 |
3126 @tparam ThisType will be deduced as `basic_json` or `const basic_json` | 12055 @tparam ThisType will be deduced as `basic_json` or `const basic_json` |
3127 | 12056 |
3128 @throw std::domain_error if ReferenceType does not match underlying value | 12057 @throw type_error.303 if ReferenceType does not match underlying value |
3129 type of the current JSON | 12058 type of the current JSON |
3130 */ | 12059 */ |
3131 template<typename ReferenceType, typename ThisType> | 12060 template<typename ReferenceType, typename ThisType> |
3132 static ReferenceType get_ref_impl(ThisType& obj) | 12061 static ReferenceType get_ref_impl(ThisType& obj) |
3133 { | 12062 { |
3134 // helper type | |
3135 using PointerType = typename std::add_pointer<ReferenceType>::type; | |
3136 | |
3137 // delegate the call to get_ptr<>() | 12063 // delegate the call to get_ptr<>() |
3138 auto ptr = obj.template get_ptr<PointerType>(); | 12064 auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>(); |
3139 | 12065 |
3140 if (ptr != nullptr) | 12066 if (JSON_LIKELY(ptr != nullptr)) |
3141 { | 12067 { |
3142 return *ptr; | 12068 return *ptr; |
3143 } | 12069 } |
3144 | 12070 |
3145 JSON_THROW(std::domain_error("incompatible ReferenceType for get_ref, actual type is " + | 12071 JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()))); |
3146 obj.type_name())); | |
3147 } | 12072 } |
3148 | 12073 |
3149 public: | 12074 public: |
3150 /// @name value access | 12075 /// @name value access |
3151 /// Direct access to the stored value of a JSON value. | 12076 /// Direct access to the stored value of a JSON value. |
3163 | 12088 |
3164 @complexity Constant. | 12089 @complexity Constant. |
3165 | 12090 |
3166 @since version 2.1.0 | 12091 @since version 2.1.0 |
3167 */ | 12092 */ |
3168 template < | 12093 template<typename BasicJsonType, detail::enable_if_t< |
3169 typename BasicJsonType, | 12094 std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value, |
3170 detail::enable_if_t<std::is_same<typename std::remove_const<BasicJsonType>::type, | 12095 int> = 0> |
3171 basic_json_t>::value, | |
3172 int> = 0 > | |
3173 basic_json get() const | 12096 basic_json get() const |
12097 { | |
12098 return *this; | |
12099 } | |
12100 | |
12101 /*! | |
12102 @brief get special-case overload | |
12103 | |
12104 This overloads converts the current @ref basic_json in a different | |
12105 @ref basic_json type | |
12106 | |
12107 @tparam BasicJsonType == @ref basic_json | |
12108 | |
12109 @return a copy of *this, converted into @tparam BasicJsonType | |
12110 | |
12111 @complexity Depending on the implementation of the called `from_json()` | |
12112 method. | |
12113 | |
12114 @since version 3.1.2 | |
12115 */ | |
12116 template<typename BasicJsonType, detail::enable_if_t< | |
12117 not std::is_same<BasicJsonType, basic_json>::value and | |
12118 detail::is_basic_json<BasicJsonType>::value, int> = 0> | |
12119 BasicJsonType get() const | |
3174 { | 12120 { |
3175 return *this; | 12121 return *this; |
3176 } | 12122 } |
3177 | 12123 |
3178 /*! | 12124 /*! |
3192 @endcode | 12138 @endcode |
3193 | 12139 |
3194 This overloads is chosen if: | 12140 This overloads is chosen if: |
3195 - @a ValueType is not @ref basic_json, | 12141 - @a ValueType is not @ref basic_json, |
3196 - @ref json_serializer<ValueType> has a `from_json()` method of the form | 12142 - @ref json_serializer<ValueType> has a `from_json()` method of the form |
3197 `void from_json(const @ref basic_json&, ValueType&)`, and | 12143 `void from_json(const basic_json&, ValueType&)`, and |
3198 - @ref json_serializer<ValueType> does not have a `from_json()` method of | 12144 - @ref json_serializer<ValueType> does not have a `from_json()` method of |
3199 the form `ValueType from_json(const @ref basic_json&)` | 12145 the form `ValueType from_json(const basic_json&)` |
3200 | 12146 |
3201 @tparam ValueTypeCV the provided value type | 12147 @tparam ValueTypeCV the provided value type |
3202 @tparam ValueType the returned value type | 12148 @tparam ValueType the returned value type |
3203 | 12149 |
3204 @return copy of the JSON value, converted to @a ValueType | 12150 @return copy of the JSON value, converted to @a ValueType |
3212 associative containers such as `std::unordered_map<std::string\, | 12158 associative containers such as `std::unordered_map<std::string\, |
3213 json>`.,get__ValueType_const} | 12159 json>`.,get__ValueType_const} |
3214 | 12160 |
3215 @since version 2.1.0 | 12161 @since version 2.1.0 |
3216 */ | 12162 */ |
3217 template < | 12163 template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>, |
3218 typename ValueTypeCV, | 12164 detail::enable_if_t < |
3219 typename ValueType = detail::uncvref_t<ValueTypeCV>, | 12165 not detail::is_basic_json<ValueType>::value and |
3220 detail::enable_if_t < | 12166 detail::has_from_json<basic_json_t, ValueType>::value and |
3221 not std::is_same<basic_json_t, ValueType>::value and | 12167 not detail::has_non_default_from_json<basic_json_t, ValueType>::value, |
3222 detail::has_from_json<basic_json_t, ValueType>::value and | 12168 int> = 0> |
3223 not detail::has_non_default_from_json<basic_json_t, ValueType>::value, | |
3224 int > = 0 > | |
3225 ValueType get() const noexcept(noexcept( | 12169 ValueType get() const noexcept(noexcept( |
3226 JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>()))) | 12170 JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>()))) |
3227 { | 12171 { |
3228 // we cannot static_assert on ValueTypeCV being non-const, because | 12172 // we cannot static_assert on ValueTypeCV being non-const, because |
3229 // there is support for get<const basic_json_t>(), which is why we | 12173 // there is support for get<const basic_json_t>(), which is why we |
3253 @endcode | 12197 @endcode |
3254 | 12198 |
3255 This overloads is chosen if: | 12199 This overloads is chosen if: |
3256 - @a ValueType is not @ref basic_json and | 12200 - @a ValueType is not @ref basic_json and |
3257 - @ref json_serializer<ValueType> has a `from_json()` method of the form | 12201 - @ref json_serializer<ValueType> has a `from_json()` method of the form |
3258 `ValueType from_json(const @ref basic_json&)` | 12202 `ValueType from_json(const basic_json&)` |
3259 | 12203 |
3260 @note If @ref json_serializer<ValueType> has both overloads of | 12204 @note If @ref json_serializer<ValueType> has both overloads of |
3261 `from_json()`, this one is chosen. | 12205 `from_json()`, this one is chosen. |
3262 | 12206 |
3263 @tparam ValueTypeCV the provided value type | 12207 @tparam ValueTypeCV the provided value type |
3267 | 12211 |
3268 @throw what @ref json_serializer<ValueType> `from_json()` method throws | 12212 @throw what @ref json_serializer<ValueType> `from_json()` method throws |
3269 | 12213 |
3270 @since version 2.1.0 | 12214 @since version 2.1.0 |
3271 */ | 12215 */ |
3272 template < | 12216 template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>, |
3273 typename ValueTypeCV, | 12217 detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and |
3274 typename ValueType = detail::uncvref_t<ValueTypeCV>, | 12218 detail::has_non_default_from_json<basic_json_t, ValueType>::value, |
3275 detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and | 12219 int> = 0> |
3276 detail::has_non_default_from_json<basic_json_t, | |
3277 ValueType>::value, int> = 0 > | |
3278 ValueType get() const noexcept(noexcept( | 12220 ValueType get() const noexcept(noexcept( |
3279 JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>()))) | 12221 JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>()))) |
3280 { | 12222 { |
3281 static_assert(not std::is_reference<ValueTypeCV>::value, | 12223 static_assert(not std::is_reference<ValueTypeCV>::value, |
3282 "get() cannot be used with reference types, you might want to use get_ref()"); | 12224 "get() cannot be used with reference types, you might want to use get_ref()"); |
3402 or std::is_same<number_unsigned_t, pointee_t>::value | 12344 or std::is_same<number_unsigned_t, pointee_t>::value |
3403 or std::is_same<number_float_t, pointee_t>::value | 12345 or std::is_same<number_float_t, pointee_t>::value |
3404 , "incompatible pointer type"); | 12346 , "incompatible pointer type"); |
3405 | 12347 |
3406 // delegate the call to get_impl_ptr<>() const | 12348 // delegate the call to get_impl_ptr<>() const |
3407 return get_impl_ptr(static_cast<const PointerType>(nullptr)); | 12349 return get_impl_ptr(static_cast<PointerType>(nullptr)); |
3408 } | 12350 } |
3409 | 12351 |
3410 /*! | 12352 /*! |
3411 @brief get a reference value (implicit) | 12353 @brief get a reference value (implicit) |
3412 | 12354 |
3420 @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or | 12362 @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or |
3421 @ref number_float_t. Enforced by static assertion. | 12363 @ref number_float_t. Enforced by static assertion. |
3422 | 12364 |
3423 @return reference to the internally stored JSON value if the requested | 12365 @return reference to the internally stored JSON value if the requested |
3424 reference type @a ReferenceType fits to the JSON value; throws | 12366 reference type @a ReferenceType fits to the JSON value; throws |
3425 std::domain_error otherwise | 12367 type_error.303 otherwise |
3426 | 12368 |
3427 @throw std::domain_error in case passed type @a ReferenceType is | 12369 @throw type_error.303 in case passed type @a ReferenceType is incompatible |
3428 incompatible with the stored JSON value | 12370 with the stored JSON value; see example below |
3429 | 12371 |
3430 @complexity Constant. | 12372 @complexity Constant. |
3431 | 12373 |
3432 @liveexample{The example shows several calls to `get_ref()`.,get_ref} | 12374 @liveexample{The example shows several calls to `get_ref()`.,get_ref} |
3433 | 12375 |
3466 as well as an initializer list of this type is excluded to avoid | 12408 as well as an initializer list of this type is excluded to avoid |
3467 ambiguities as these types implicitly convert to `std::string`. | 12409 ambiguities as these types implicitly convert to `std::string`. |
3468 | 12410 |
3469 @return copy of the JSON value, converted to type @a ValueType | 12411 @return copy of the JSON value, converted to type @a ValueType |
3470 | 12412 |
3471 @throw std::domain_error in case passed type @a ValueType is incompatible | 12413 @throw type_error.302 in case passed type @a ValueType is incompatible |
3472 to JSON, thrown by @ref get() const | 12414 to the JSON value type (e.g., the JSON value is of type boolean, but a |
12415 string is requested); see example below | |
3473 | 12416 |
3474 @complexity Linear in the size of the JSON value. | 12417 @complexity Linear in the size of the JSON value. |
3475 | 12418 |
3476 @liveexample{The example below shows several conversions from JSON values | 12419 @liveexample{The example below shows several conversions from JSON values |
3477 to other types. There a few things to note: (1) Floating-point numbers can | 12420 to other types. There a few things to note: (1) Floating-point numbers can |
3482 | 12425 |
3483 @since version 1.0.0 | 12426 @since version 1.0.0 |
3484 */ | 12427 */ |
3485 template < typename ValueType, typename std::enable_if < | 12428 template < typename ValueType, typename std::enable_if < |
3486 not std::is_pointer<ValueType>::value and | 12429 not std::is_pointer<ValueType>::value and |
3487 not std::is_same<ValueType, typename string_t::value_type>::value | 12430 not std::is_same<ValueType, detail::json_ref<basic_json>>::value and |
12431 not std::is_same<ValueType, typename string_t::value_type>::value and | |
12432 not detail::is_basic_json<ValueType>::value | |
3488 #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015 | 12433 #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015 |
3489 and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value | 12434 and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value |
3490 #endif | 12435 #endif |
12436 #if defined(JSON_HAS_CPP_17) | |
12437 and not std::is_same<ValueType, typename std::string_view>::value | |
12438 #endif | |
3491 , int >::type = 0 > | 12439 , int >::type = 0 > |
3492 operator ValueType() const | 12440 operator ValueType() const |
3493 { | 12441 { |
3494 // delegate the call to get<>() const | 12442 // delegate the call to get<>() const |
3495 return get<ValueType>(); | 12443 return get<ValueType>(); |
3514 | 12462 |
3515 @param[in] idx index of the element to access | 12463 @param[in] idx index of the element to access |
3516 | 12464 |
3517 @return reference to the element at index @a idx | 12465 @return reference to the element at index @a idx |
3518 | 12466 |
3519 @throw std::domain_error if the JSON value is not an array; example: | 12467 @throw type_error.304 if the JSON value is not an array; in this case, |
3520 `"cannot use at() with string"` | 12468 calling `at` with an index makes no sense. See example below. |
3521 @throw std::out_of_range if the index @a idx is out of range of the array; | 12469 @throw out_of_range.401 if the index @a idx is out of range of the array; |
3522 that is, `idx >= size()`; example: `"array index 7 is out of range"` | 12470 that is, `idx >= size()`. See example below. |
12471 | |
12472 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
12473 changes in the JSON value. | |
3523 | 12474 |
3524 @complexity Constant. | 12475 @complexity Constant. |
3525 | 12476 |
12477 @since version 1.0.0 | |
12478 | |
3526 @liveexample{The example below shows how array elements can be read and | 12479 @liveexample{The example below shows how array elements can be read and |
3527 written using `at()`.,at__size_type} | 12480 written using `at()`. It also demonstrates the different exceptions that |
3528 | 12481 can be thrown.,at__size_type} |
3529 @since version 1.0.0 | |
3530 */ | 12482 */ |
3531 reference at(size_type idx) | 12483 reference at(size_type idx) |
3532 { | 12484 { |
3533 // at only works for arrays | 12485 // at only works for arrays |
3534 if (is_array()) | 12486 if (JSON_LIKELY(is_array())) |
3535 { | 12487 { |
3536 JSON_TRY | 12488 JSON_TRY |
3537 { | 12489 { |
3538 return m_value.array->at(idx); | 12490 return m_value.array->at(idx); |
3539 } | 12491 } |
3540 JSON_CATCH (std::out_of_range&) | 12492 JSON_CATCH (std::out_of_range&) |
3541 { | 12493 { |
3542 // create better exception explanation | 12494 // create better exception explanation |
3543 JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range")); | 12495 JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); |
3544 } | 12496 } |
3545 } | 12497 } |
3546 else | 12498 else |
3547 { | 12499 { |
3548 JSON_THROW(std::domain_error("cannot use at() with " + type_name())); | 12500 JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); |
3549 } | 12501 } |
3550 } | 12502 } |
3551 | 12503 |
3552 /*! | 12504 /*! |
3553 @brief access specified array element with bounds checking | 12505 @brief access specified array element with bounds checking |
3557 | 12509 |
3558 @param[in] idx index of the element to access | 12510 @param[in] idx index of the element to access |
3559 | 12511 |
3560 @return const reference to the element at index @a idx | 12512 @return const reference to the element at index @a idx |
3561 | 12513 |
3562 @throw std::domain_error if the JSON value is not an array; example: | 12514 @throw type_error.304 if the JSON value is not an array; in this case, |
3563 `"cannot use at() with string"` | 12515 calling `at` with an index makes no sense. See example below. |
3564 @throw std::out_of_range if the index @a idx is out of range of the array; | 12516 @throw out_of_range.401 if the index @a idx is out of range of the array; |
3565 that is, `idx >= size()`; example: `"array index 7 is out of range"` | 12517 that is, `idx >= size()`. See example below. |
12518 | |
12519 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
12520 changes in the JSON value. | |
3566 | 12521 |
3567 @complexity Constant. | 12522 @complexity Constant. |
3568 | 12523 |
12524 @since version 1.0.0 | |
12525 | |
3569 @liveexample{The example below shows how array elements can be read using | 12526 @liveexample{The example below shows how array elements can be read using |
3570 `at()`.,at__size_type_const} | 12527 `at()`. It also demonstrates the different exceptions that can be thrown., |
3571 | 12528 at__size_type_const} |
3572 @since version 1.0.0 | |
3573 */ | 12529 */ |
3574 const_reference at(size_type idx) const | 12530 const_reference at(size_type idx) const |
3575 { | 12531 { |
3576 // at only works for arrays | 12532 // at only works for arrays |
3577 if (is_array()) | 12533 if (JSON_LIKELY(is_array())) |
3578 { | 12534 { |
3579 JSON_TRY | 12535 JSON_TRY |
3580 { | 12536 { |
3581 return m_value.array->at(idx); | 12537 return m_value.array->at(idx); |
3582 } | 12538 } |
3583 JSON_CATCH (std::out_of_range&) | 12539 JSON_CATCH (std::out_of_range&) |
3584 { | 12540 { |
3585 // create better exception explanation | 12541 // create better exception explanation |
3586 JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range")); | 12542 JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); |
3587 } | 12543 } |
3588 } | 12544 } |
3589 else | 12545 else |
3590 { | 12546 { |
3591 JSON_THROW(std::domain_error("cannot use at() with " + type_name())); | 12547 JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); |
3592 } | 12548 } |
3593 } | 12549 } |
3594 | 12550 |
3595 /*! | 12551 /*! |
3596 @brief access specified object element with bounds checking | 12552 @brief access specified object element with bounds checking |
3600 | 12556 |
3601 @param[in] key key of the element to access | 12557 @param[in] key key of the element to access |
3602 | 12558 |
3603 @return reference to the element at key @a key | 12559 @return reference to the element at key @a key |
3604 | 12560 |
3605 @throw std::domain_error if the JSON value is not an object; example: | 12561 @throw type_error.304 if the JSON value is not an object; in this case, |
3606 `"cannot use at() with boolean"` | 12562 calling `at` with a key makes no sense. See example below. |
3607 @throw std::out_of_range if the key @a key is is not stored in the object; | 12563 @throw out_of_range.403 if the key @a key is is not stored in the object; |
3608 that is, `find(key) == end()`; example: `"key "the fast" not found"` | 12564 that is, `find(key) == end()`. See example below. |
12565 | |
12566 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
12567 changes in the JSON value. | |
3609 | 12568 |
3610 @complexity Logarithmic in the size of the container. | 12569 @complexity Logarithmic in the size of the container. |
3611 | |
3612 @liveexample{The example below shows how object elements can be read and | |
3613 written using `at()`.,at__object_t_key_type} | |
3614 | 12570 |
3615 @sa @ref operator[](const typename object_t::key_type&) for unchecked | 12571 @sa @ref operator[](const typename object_t::key_type&) for unchecked |
3616 access by reference | 12572 access by reference |
3617 @sa @ref value() for access by value with a default value | 12573 @sa @ref value() for access by value with a default value |
3618 | 12574 |
3619 @since version 1.0.0 | 12575 @since version 1.0.0 |
12576 | |
12577 @liveexample{The example below shows how object elements can be read and | |
12578 written using `at()`. It also demonstrates the different exceptions that | |
12579 can be thrown.,at__object_t_key_type} | |
3620 */ | 12580 */ |
3621 reference at(const typename object_t::key_type& key) | 12581 reference at(const typename object_t::key_type& key) |
3622 { | 12582 { |
3623 // at only works for objects | 12583 // at only works for objects |
3624 if (is_object()) | 12584 if (JSON_LIKELY(is_object())) |
3625 { | 12585 { |
3626 JSON_TRY | 12586 JSON_TRY |
3627 { | 12587 { |
3628 return m_value.object->at(key); | 12588 return m_value.object->at(key); |
3629 } | 12589 } |
3630 JSON_CATCH (std::out_of_range&) | 12590 JSON_CATCH (std::out_of_range&) |
3631 { | 12591 { |
3632 // create better exception explanation | 12592 // create better exception explanation |
3633 JSON_THROW(std::out_of_range("key '" + key + "' not found")); | 12593 JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); |
3634 } | 12594 } |
3635 } | 12595 } |
3636 else | 12596 else |
3637 { | 12597 { |
3638 JSON_THROW(std::domain_error("cannot use at() with " + type_name())); | 12598 JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); |
3639 } | 12599 } |
3640 } | 12600 } |
3641 | 12601 |
3642 /*! | 12602 /*! |
3643 @brief access specified object element with bounds checking | 12603 @brief access specified object element with bounds checking |
3647 | 12607 |
3648 @param[in] key key of the element to access | 12608 @param[in] key key of the element to access |
3649 | 12609 |
3650 @return const reference to the element at key @a key | 12610 @return const reference to the element at key @a key |
3651 | 12611 |
3652 @throw std::domain_error if the JSON value is not an object; example: | 12612 @throw type_error.304 if the JSON value is not an object; in this case, |
3653 `"cannot use at() with boolean"` | 12613 calling `at` with a key makes no sense. See example below. |
3654 @throw std::out_of_range if the key @a key is is not stored in the object; | 12614 @throw out_of_range.403 if the key @a key is is not stored in the object; |
3655 that is, `find(key) == end()`; example: `"key "the fast" not found"` | 12615 that is, `find(key) == end()`. See example below. |
12616 | |
12617 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
12618 changes in the JSON value. | |
3656 | 12619 |
3657 @complexity Logarithmic in the size of the container. | 12620 @complexity Logarithmic in the size of the container. |
3658 | |
3659 @liveexample{The example below shows how object elements can be read using | |
3660 `at()`.,at__object_t_key_type_const} | |
3661 | 12621 |
3662 @sa @ref operator[](const typename object_t::key_type&) for unchecked | 12622 @sa @ref operator[](const typename object_t::key_type&) for unchecked |
3663 access by reference | 12623 access by reference |
3664 @sa @ref value() for access by value with a default value | 12624 @sa @ref value() for access by value with a default value |
3665 | 12625 |
3666 @since version 1.0.0 | 12626 @since version 1.0.0 |
12627 | |
12628 @liveexample{The example below shows how object elements can be read using | |
12629 `at()`. It also demonstrates the different exceptions that can be thrown., | |
12630 at__object_t_key_type_const} | |
3667 */ | 12631 */ |
3668 const_reference at(const typename object_t::key_type& key) const | 12632 const_reference at(const typename object_t::key_type& key) const |
3669 { | 12633 { |
3670 // at only works for objects | 12634 // at only works for objects |
3671 if (is_object()) | 12635 if (JSON_LIKELY(is_object())) |
3672 { | 12636 { |
3673 JSON_TRY | 12637 JSON_TRY |
3674 { | 12638 { |
3675 return m_value.object->at(key); | 12639 return m_value.object->at(key); |
3676 } | 12640 } |
3677 JSON_CATCH (std::out_of_range&) | 12641 JSON_CATCH (std::out_of_range&) |
3678 { | 12642 { |
3679 // create better exception explanation | 12643 // create better exception explanation |
3680 JSON_THROW(std::out_of_range("key '" + key + "' not found")); | 12644 JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); |
3681 } | 12645 } |
3682 } | 12646 } |
3683 else | 12647 else |
3684 { | 12648 { |
3685 JSON_THROW(std::domain_error("cannot use at() with " + type_name())); | 12649 JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); |
3686 } | 12650 } |
3687 } | 12651 } |
3688 | 12652 |
3689 /*! | 12653 /*! |
3690 @brief access specified array element | 12654 @brief access specified array element |
3697 | 12661 |
3698 @param[in] idx index of the element to access | 12662 @param[in] idx index of the element to access |
3699 | 12663 |
3700 @return reference to the element at index @a idx | 12664 @return reference to the element at index @a idx |
3701 | 12665 |
3702 @throw std::domain_error if JSON is not an array or null; example: | 12666 @throw type_error.305 if the JSON value is not an array or null; in that |
3703 `"cannot use operator[] with string"` | 12667 cases, using the [] operator with an index makes no sense. |
3704 | 12668 |
3705 @complexity Constant if @a idx is in the range of the array. Otherwise | 12669 @complexity Constant if @a idx is in the range of the array. Otherwise |
3706 linear in `idx - size()`. | 12670 linear in `idx - size()`. |
3707 | 12671 |
3708 @liveexample{The example below shows how array elements can be read and | 12672 @liveexample{The example below shows how array elements can be read and |
3720 m_value.array = create<array_t>(); | 12684 m_value.array = create<array_t>(); |
3721 assert_invariant(); | 12685 assert_invariant(); |
3722 } | 12686 } |
3723 | 12687 |
3724 // operator[] only works for arrays | 12688 // operator[] only works for arrays |
3725 if (is_array()) | 12689 if (JSON_LIKELY(is_array())) |
3726 { | 12690 { |
3727 // fill up array with null values if given idx is outside range | 12691 // fill up array with null values if given idx is outside range |
3728 if (idx >= m_value.array->size()) | 12692 if (idx >= m_value.array->size()) |
3729 { | 12693 { |
3730 m_value.array->insert(m_value.array->end(), | 12694 m_value.array->insert(m_value.array->end(), |
3733 } | 12697 } |
3734 | 12698 |
3735 return m_value.array->operator[](idx); | 12699 return m_value.array->operator[](idx); |
3736 } | 12700 } |
3737 | 12701 |
3738 JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); | 12702 JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); |
3739 } | 12703 } |
3740 | 12704 |
3741 /*! | 12705 /*! |
3742 @brief access specified array element | 12706 @brief access specified array element |
3743 | 12707 |
3745 | 12709 |
3746 @param[in] idx index of the element to access | 12710 @param[in] idx index of the element to access |
3747 | 12711 |
3748 @return const reference to the element at index @a idx | 12712 @return const reference to the element at index @a idx |
3749 | 12713 |
3750 @throw std::domain_error if JSON is not an array; example: `"cannot use | 12714 @throw type_error.305 if the JSON value is not an array; in that case, |
3751 operator[] with null"` | 12715 using the [] operator with an index makes no sense. |
3752 | 12716 |
3753 @complexity Constant. | 12717 @complexity Constant. |
3754 | 12718 |
3755 @liveexample{The example below shows how array elements can be read using | 12719 @liveexample{The example below shows how array elements can be read using |
3756 the `[]` operator.,operatorarray__size_type_const} | 12720 the `[]` operator.,operatorarray__size_type_const} |
3758 @since version 1.0.0 | 12722 @since version 1.0.0 |
3759 */ | 12723 */ |
3760 const_reference operator[](size_type idx) const | 12724 const_reference operator[](size_type idx) const |
3761 { | 12725 { |
3762 // const operator[] only works for arrays | 12726 // const operator[] only works for arrays |
3763 if (is_array()) | 12727 if (JSON_LIKELY(is_array())) |
3764 { | 12728 { |
3765 return m_value.array->operator[](idx); | 12729 return m_value.array->operator[](idx); |
3766 } | 12730 } |
3767 | 12731 |
3768 JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); | 12732 JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); |
3769 } | 12733 } |
3770 | 12734 |
3771 /*! | 12735 /*! |
3772 @brief access specified object element | 12736 @brief access specified object element |
3773 | 12737 |
3779 | 12743 |
3780 @param[in] key key of the element to access | 12744 @param[in] key key of the element to access |
3781 | 12745 |
3782 @return reference to the element at key @a key | 12746 @return reference to the element at key @a key |
3783 | 12747 |
3784 @throw std::domain_error if JSON is not an object or null; example: | 12748 @throw type_error.305 if the JSON value is not an object or null; in that |
3785 `"cannot use operator[] with string"` | 12749 cases, using the [] operator with a key makes no sense. |
3786 | 12750 |
3787 @complexity Logarithmic in the size of the container. | 12751 @complexity Logarithmic in the size of the container. |
3788 | 12752 |
3789 @liveexample{The example below shows how object elements can be read and | 12753 @liveexample{The example below shows how object elements can be read and |
3790 written using the `[]` operator.,operatorarray__key_type} | 12754 written using the `[]` operator.,operatorarray__key_type} |
3804 m_value.object = create<object_t>(); | 12768 m_value.object = create<object_t>(); |
3805 assert_invariant(); | 12769 assert_invariant(); |
3806 } | 12770 } |
3807 | 12771 |
3808 // operator[] only works for objects | 12772 // operator[] only works for objects |
3809 if (is_object()) | 12773 if (JSON_LIKELY(is_object())) |
3810 { | 12774 { |
3811 return m_value.object->operator[](key); | 12775 return m_value.object->operator[](key); |
3812 } | 12776 } |
3813 | 12777 |
3814 JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); | 12778 JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); |
3815 } | 12779 } |
3816 | 12780 |
3817 /*! | 12781 /*! |
3818 @brief read-only access specified object element | 12782 @brief read-only access specified object element |
3819 | 12783 |
3828 @return const reference to the element at key @a key | 12792 @return const reference to the element at key @a key |
3829 | 12793 |
3830 @pre The element with key @a key must exist. **This precondition is | 12794 @pre The element with key @a key must exist. **This precondition is |
3831 enforced with an assertion.** | 12795 enforced with an assertion.** |
3832 | 12796 |
3833 @throw std::domain_error if JSON is not an object; example: `"cannot use | 12797 @throw type_error.305 if the JSON value is not an object; in that case, |
3834 operator[] with null"` | 12798 using the [] operator with a key makes no sense. |
3835 | 12799 |
3836 @complexity Logarithmic in the size of the container. | 12800 @complexity Logarithmic in the size of the container. |
3837 | 12801 |
3838 @liveexample{The example below shows how object elements can be read using | 12802 @liveexample{The example below shows how object elements can be read using |
3839 the `[]` operator.,operatorarray__key_type_const} | 12803 the `[]` operator.,operatorarray__key_type_const} |
3845 @since version 1.0.0 | 12809 @since version 1.0.0 |
3846 */ | 12810 */ |
3847 const_reference operator[](const typename object_t::key_type& key) const | 12811 const_reference operator[](const typename object_t::key_type& key) const |
3848 { | 12812 { |
3849 // const operator[] only works for objects | 12813 // const operator[] only works for objects |
3850 if (is_object()) | 12814 if (JSON_LIKELY(is_object())) |
3851 { | 12815 { |
3852 assert(m_value.object->find(key) != m_value.object->end()); | 12816 assert(m_value.object->find(key) != m_value.object->end()); |
3853 return m_value.object->find(key)->second; | 12817 return m_value.object->find(key)->second; |
3854 } | 12818 } |
3855 | 12819 |
3856 JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); | 12820 JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); |
3857 } | 12821 } |
3858 | 12822 |
3859 /*! | 12823 /*! |
3860 @brief access specified object element | 12824 @brief access specified object element |
3861 | 12825 |
3867 | 12831 |
3868 @param[in] key key of the element to access | 12832 @param[in] key key of the element to access |
3869 | 12833 |
3870 @return reference to the element at key @a key | 12834 @return reference to the element at key @a key |
3871 | 12835 |
3872 @throw std::domain_error if JSON is not an object or null; example: | 12836 @throw type_error.305 if the JSON value is not an object or null; in that |
3873 `"cannot use operator[] with string"` | 12837 cases, using the [] operator with a key makes no sense. |
3874 | 12838 |
3875 @complexity Logarithmic in the size of the container. | 12839 @complexity Logarithmic in the size of the container. |
3876 | 12840 |
3877 @liveexample{The example below shows how object elements can be read and | 12841 @liveexample{The example below shows how object elements can be read and |
3878 written using the `[]` operator.,operatorarray__key_type} | 12842 written using the `[]` operator.,operatorarray__key_type} |
3879 | 12843 |
3880 @sa @ref at(const typename object_t::key_type&) for access by reference | 12844 @sa @ref at(const typename object_t::key_type&) for access by reference |
3881 with range checking | 12845 with range checking |
3882 @sa @ref value() for access by value with a default value | 12846 @sa @ref value() for access by value with a default value |
3883 | 12847 |
3884 @since version 1.0.0 | 12848 @since version 1.1.0 |
3885 */ | 12849 */ |
3886 template<typename T, std::size_t n> | 12850 template<typename T> |
3887 reference operator[](T * (&key)[n]) | 12851 reference operator[](T* key) |
3888 { | 12852 { |
3889 return operator[](static_cast<const T>(key)); | 12853 // implicitly convert null to object |
12854 if (is_null()) | |
12855 { | |
12856 m_type = value_t::object; | |
12857 m_value = value_t::object; | |
12858 assert_invariant(); | |
12859 } | |
12860 | |
12861 // at only works for objects | |
12862 if (JSON_LIKELY(is_object())) | |
12863 { | |
12864 return m_value.object->operator[](key); | |
12865 } | |
12866 | |
12867 JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); | |
3890 } | 12868 } |
3891 | 12869 |
3892 /*! | 12870 /*! |
3893 @brief read-only access specified object element | 12871 @brief read-only access specified object element |
3894 | 12872 |
3896 bounds checking is performed. | 12874 bounds checking is performed. |
3897 | 12875 |
3898 @warning If the element with key @a key does not exist, the behavior is | 12876 @warning If the element with key @a key does not exist, the behavior is |
3899 undefined. | 12877 undefined. |
3900 | 12878 |
3901 @note This function is required for compatibility reasons with Clang. | |
3902 | |
3903 @param[in] key key of the element to access | 12879 @param[in] key key of the element to access |
3904 | 12880 |
3905 @return const reference to the element at key @a key | 12881 @return const reference to the element at key @a key |
3906 | 12882 |
3907 @throw std::domain_error if JSON is not an object; example: `"cannot use | 12883 @pre The element with key @a key must exist. **This precondition is |
3908 operator[] with null"` | 12884 enforced with an assertion.** |
12885 | |
12886 @throw type_error.305 if the JSON value is not an object; in that case, | |
12887 using the [] operator with a key makes no sense. | |
3909 | 12888 |
3910 @complexity Logarithmic in the size of the container. | 12889 @complexity Logarithmic in the size of the container. |
3911 | 12890 |
3912 @liveexample{The example below shows how object elements can be read using | 12891 @liveexample{The example below shows how object elements can be read using |
3913 the `[]` operator.,operatorarray__key_type_const} | 12892 the `[]` operator.,operatorarray__key_type_const} |
3914 | 12893 |
3915 @sa @ref at(const typename object_t::key_type&) for access by reference | 12894 @sa @ref at(const typename object_t::key_type&) for access by reference |
3916 with range checking | 12895 with range checking |
3917 @sa @ref value() for access by value with a default value | 12896 @sa @ref value() for access by value with a default value |
3918 | 12897 |
3919 @since version 1.0.0 | |
3920 */ | |
3921 template<typename T, std::size_t n> | |
3922 const_reference operator[](T * (&key)[n]) const | |
3923 { | |
3924 return operator[](static_cast<const T>(key)); | |
3925 } | |
3926 | |
3927 /*! | |
3928 @brief access specified object element | |
3929 | |
3930 Returns a reference to the element at with specified key @a key. | |
3931 | |
3932 @note If @a key is not found in the object, then it is silently added to | |
3933 the object and filled with a `null` value to make `key` a valid reference. | |
3934 In case the value was `null` before, it is converted to an object. | |
3935 | |
3936 @param[in] key key of the element to access | |
3937 | |
3938 @return reference to the element at key @a key | |
3939 | |
3940 @throw std::domain_error if JSON is not an object or null; example: | |
3941 `"cannot use operator[] with string"` | |
3942 | |
3943 @complexity Logarithmic in the size of the container. | |
3944 | |
3945 @liveexample{The example below shows how object elements can be read and | |
3946 written using the `[]` operator.,operatorarray__key_type} | |
3947 | |
3948 @sa @ref at(const typename object_t::key_type&) for access by reference | |
3949 with range checking | |
3950 @sa @ref value() for access by value with a default value | |
3951 | |
3952 @since version 1.1.0 | |
3953 */ | |
3954 template<typename T> | |
3955 reference operator[](T* key) | |
3956 { | |
3957 // implicitly convert null to object | |
3958 if (is_null()) | |
3959 { | |
3960 m_type = value_t::object; | |
3961 m_value = value_t::object; | |
3962 assert_invariant(); | |
3963 } | |
3964 | |
3965 // at only works for objects | |
3966 if (is_object()) | |
3967 { | |
3968 return m_value.object->operator[](key); | |
3969 } | |
3970 | |
3971 JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); | |
3972 } | |
3973 | |
3974 /*! | |
3975 @brief read-only access specified object element | |
3976 | |
3977 Returns a const reference to the element at with specified key @a key. No | |
3978 bounds checking is performed. | |
3979 | |
3980 @warning If the element with key @a key does not exist, the behavior is | |
3981 undefined. | |
3982 | |
3983 @param[in] key key of the element to access | |
3984 | |
3985 @return const reference to the element at key @a key | |
3986 | |
3987 @pre The element with key @a key must exist. **This precondition is | |
3988 enforced with an assertion.** | |
3989 | |
3990 @throw std::domain_error if JSON is not an object; example: `"cannot use | |
3991 operator[] with null"` | |
3992 | |
3993 @complexity Logarithmic in the size of the container. | |
3994 | |
3995 @liveexample{The example below shows how object elements can be read using | |
3996 the `[]` operator.,operatorarray__key_type_const} | |
3997 | |
3998 @sa @ref at(const typename object_t::key_type&) for access by reference | |
3999 with range checking | |
4000 @sa @ref value() for access by value with a default value | |
4001 | |
4002 @since version 1.1.0 | 12898 @since version 1.1.0 |
4003 */ | 12899 */ |
4004 template<typename T> | 12900 template<typename T> |
4005 const_reference operator[](T* key) const | 12901 const_reference operator[](T* key) const |
4006 { | 12902 { |
4007 // at only works for objects | 12903 // at only works for objects |
4008 if (is_object()) | 12904 if (JSON_LIKELY(is_object())) |
4009 { | 12905 { |
4010 assert(m_value.object->find(key) != m_value.object->end()); | 12906 assert(m_value.object->find(key) != m_value.object->end()); |
4011 return m_value.object->find(key)->second; | 12907 return m_value.object->find(key)->second; |
4012 } | 12908 } |
4013 | 12909 |
4014 JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); | 12910 JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); |
4015 } | 12911 } |
4016 | 12912 |
4017 /*! | 12913 /*! |
4018 @brief access specified object element with default value | 12914 @brief access specified object element with default value |
4019 | 12915 |
4022 | 12918 |
4023 The function is basically equivalent to executing | 12919 The function is basically equivalent to executing |
4024 @code {.cpp} | 12920 @code {.cpp} |
4025 try { | 12921 try { |
4026 return at(key); | 12922 return at(key); |
4027 } catch(std::out_of_range) { | 12923 } catch(out_of_range) { |
4028 return default_value; | 12924 return default_value; |
4029 } | 12925 } |
4030 @endcode | 12926 @endcode |
4031 | 12927 |
4032 @note Unlike @ref at(const typename object_t::key_type&), this function | 12928 @note Unlike @ref at(const typename object_t::key_type&), this function |
4045 value @a default_value must be compatible. | 12941 value @a default_value must be compatible. |
4046 | 12942 |
4047 @return copy of the element at key @a key or @a default_value if @a key | 12943 @return copy of the element at key @a key or @a default_value if @a key |
4048 is not found | 12944 is not found |
4049 | 12945 |
4050 @throw std::domain_error if JSON is not an object; example: `"cannot use | 12946 @throw type_error.306 if the JSON value is not an object; in that case, |
4051 value() with null"` | 12947 using `value()` with a key makes no sense. |
4052 | 12948 |
4053 @complexity Logarithmic in the size of the container. | 12949 @complexity Logarithmic in the size of the container. |
4054 | 12950 |
4055 @liveexample{The example below shows how object elements can be queried | 12951 @liveexample{The example below shows how object elements can be queried |
4056 with a default value.,basic_json__value} | 12952 with a default value.,basic_json__value} |
4062 | 12958 |
4063 @since version 1.0.0 | 12959 @since version 1.0.0 |
4064 */ | 12960 */ |
4065 template<class ValueType, typename std::enable_if< | 12961 template<class ValueType, typename std::enable_if< |
4066 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0> | 12962 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0> |
4067 ValueType value(const typename object_t::key_type& key, ValueType default_value) const | 12963 ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const |
4068 { | 12964 { |
4069 // at only works for objects | 12965 // at only works for objects |
4070 if (is_object()) | 12966 if (JSON_LIKELY(is_object())) |
4071 { | 12967 { |
4072 // if key is found, return value and given default value otherwise | 12968 // if key is found, return value and given default value otherwise |
4073 const auto it = find(key); | 12969 const auto it = find(key); |
4074 if (it != end()) | 12970 if (it != end()) |
4075 { | 12971 { |
4076 return *it; | 12972 return *it; |
4077 } | 12973 } |
4078 | 12974 |
4079 return default_value; | 12975 return default_value; |
4080 } | 12976 } |
4081 else | 12977 |
4082 { | 12978 JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); |
4083 JSON_THROW(std::domain_error("cannot use value() with " + type_name())); | |
4084 } | |
4085 } | 12979 } |
4086 | 12980 |
4087 /*! | 12981 /*! |
4088 @brief overload for a default value of type const char* | 12982 @brief overload for a default value of type const char* |
4089 @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const | 12983 @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const |
4101 | 12995 |
4102 The function is basically equivalent to executing | 12996 The function is basically equivalent to executing |
4103 @code {.cpp} | 12997 @code {.cpp} |
4104 try { | 12998 try { |
4105 return at(ptr); | 12999 return at(ptr); |
4106 } catch(std::out_of_range) { | 13000 } catch(out_of_range) { |
4107 return default_value; | 13001 return default_value; |
4108 } | 13002 } |
4109 @endcode | 13003 @endcode |
4110 | 13004 |
4111 @note Unlike @ref at(const json_pointer&), this function does not throw | 13005 @note Unlike @ref at(const json_pointer&), this function does not throw |
4120 value @a default_value must be compatible. | 13014 value @a default_value must be compatible. |
4121 | 13015 |
4122 @return copy of the element at key @a key or @a default_value if @a key | 13016 @return copy of the element at key @a key or @a default_value if @a key |
4123 is not found | 13017 is not found |
4124 | 13018 |
4125 @throw std::domain_error if JSON is not an object; example: `"cannot use | 13019 @throw type_error.306 if the JSON value is not an objec; in that case, |
4126 value() with null"` | 13020 using `value()` with a key makes no sense. |
4127 | 13021 |
4128 @complexity Logarithmic in the size of the container. | 13022 @complexity Logarithmic in the size of the container. |
4129 | 13023 |
4130 @liveexample{The example below shows how object elements can be queried | 13024 @liveexample{The example below shows how object elements can be queried |
4131 with a default value.,basic_json__value_ptr} | 13025 with a default value.,basic_json__value_ptr} |
4134 | 13028 |
4135 @since version 2.0.2 | 13029 @since version 2.0.2 |
4136 */ | 13030 */ |
4137 template<class ValueType, typename std::enable_if< | 13031 template<class ValueType, typename std::enable_if< |
4138 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0> | 13032 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0> |
4139 ValueType value(const json_pointer& ptr, ValueType default_value) const | 13033 ValueType value(const json_pointer& ptr, const ValueType& default_value) const |
4140 { | 13034 { |
4141 // at only works for objects | 13035 // at only works for objects |
4142 if (is_object()) | 13036 if (JSON_LIKELY(is_object())) |
4143 { | 13037 { |
4144 // if pointer resolves a value, return it or use default value | 13038 // if pointer resolves a value, return it or use default value |
4145 JSON_TRY | 13039 JSON_TRY |
4146 { | 13040 { |
4147 return ptr.get_checked(this); | 13041 return ptr.get_checked(this); |
4148 } | 13042 } |
4149 JSON_CATCH (std::out_of_range&) | 13043 JSON_CATCH (out_of_range&) |
4150 { | 13044 { |
4151 return default_value; | 13045 return default_value; |
4152 } | 13046 } |
4153 } | 13047 } |
4154 | 13048 |
4155 JSON_THROW(std::domain_error("cannot use value() with " + type_name())); | 13049 JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); |
4156 } | 13050 } |
4157 | 13051 |
4158 /*! | 13052 /*! |
4159 @brief overload for a default value of type const char* | 13053 @brief overload for a default value of type const char* |
4160 @copydoc basic_json::value(const json_pointer&, ValueType) const | 13054 @copydoc basic_json::value(const json_pointer&, ValueType) const |
4179 @pre The JSON value must not be `null` (would throw `std::out_of_range`) | 13073 @pre The JSON value must not be `null` (would throw `std::out_of_range`) |
4180 or an empty array or object (undefined behavior, **guarded by | 13074 or an empty array or object (undefined behavior, **guarded by |
4181 assertions**). | 13075 assertions**). |
4182 @post The JSON value remains unchanged. | 13076 @post The JSON value remains unchanged. |
4183 | 13077 |
4184 @throw std::out_of_range when called on `null` value | 13078 @throw invalid_iterator.214 when called on `null` value |
4185 | 13079 |
4186 @liveexample{The following code shows an example for `front()`.,front} | 13080 @liveexample{The following code shows an example for `front()`.,front} |
4187 | 13081 |
4188 @sa @ref back() -- access the last element | 13082 @sa @ref back() -- access the last element |
4189 | 13083 |
4222 @pre The JSON value must not be `null` (would throw `std::out_of_range`) | 13116 @pre The JSON value must not be `null` (would throw `std::out_of_range`) |
4223 or an empty array or object (undefined behavior, **guarded by | 13117 or an empty array or object (undefined behavior, **guarded by |
4224 assertions**). | 13118 assertions**). |
4225 @post The JSON value remains unchanged. | 13119 @post The JSON value remains unchanged. |
4226 | 13120 |
4227 @throw std::out_of_range when called on `null` value. | 13121 @throw invalid_iterator.214 when called on a `null` value. See example |
13122 below. | |
4228 | 13123 |
4229 @liveexample{The following code shows an example for `back()`.,back} | 13124 @liveexample{The following code shows an example for `back()`.,back} |
4230 | 13125 |
4231 @sa @ref front() -- access the first element | 13126 @sa @ref front() -- access the first element |
4232 | 13127 |
4266 @tparam IteratorType an @ref iterator or @ref const_iterator | 13161 @tparam IteratorType an @ref iterator or @ref const_iterator |
4267 | 13162 |
4268 @post Invalidates iterators and references at or after the point of the | 13163 @post Invalidates iterators and references at or after the point of the |
4269 erase, including the `end()` iterator. | 13164 erase, including the `end()` iterator. |
4270 | 13165 |
4271 @throw std::domain_error if called on a `null` value; example: `"cannot | 13166 @throw type_error.307 if called on a `null` value; example: `"cannot use |
4272 use erase() with null"` | 13167 erase() with null"` |
4273 @throw std::domain_error if called on an iterator which does not belong to | 13168 @throw invalid_iterator.202 if called on an iterator which does not belong |
4274 the current JSON value; example: `"iterator does not fit current value"` | 13169 to the current JSON value; example: `"iterator does not fit current |
4275 @throw std::out_of_range if called on a primitive type with invalid | 13170 value"` |
13171 @throw invalid_iterator.205 if called on a primitive type with invalid | |
4276 iterator (i.e., any iterator which is not `begin()`); example: `"iterator | 13172 iterator (i.e., any iterator which is not `begin()`); example: `"iterator |
4277 out of range"` | 13173 out of range"` |
4278 | 13174 |
4279 @complexity The complexity depends on the type: | 13175 @complexity The complexity depends on the type: |
4280 - objects: amortized constant | 13176 - objects: amortized constant |
4299 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type | 13195 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type |
4300 = 0> | 13196 = 0> |
4301 IteratorType erase(IteratorType pos) | 13197 IteratorType erase(IteratorType pos) |
4302 { | 13198 { |
4303 // make sure iterator fits the current value | 13199 // make sure iterator fits the current value |
4304 if (this != pos.m_object) | 13200 if (JSON_UNLIKELY(this != pos.m_object)) |
4305 { | 13201 { |
4306 JSON_THROW(std::domain_error("iterator does not fit current value")); | 13202 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); |
4307 } | 13203 } |
4308 | 13204 |
4309 IteratorType result = end(); | 13205 IteratorType result = end(); |
4310 | 13206 |
4311 switch (m_type) | 13207 switch (m_type) |
4314 case value_t::number_float: | 13210 case value_t::number_float: |
4315 case value_t::number_integer: | 13211 case value_t::number_integer: |
4316 case value_t::number_unsigned: | 13212 case value_t::number_unsigned: |
4317 case value_t::string: | 13213 case value_t::string: |
4318 { | 13214 { |
4319 if (not pos.m_it.primitive_iterator.is_begin()) | 13215 if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin())) |
4320 { | 13216 { |
4321 JSON_THROW(std::out_of_range("iterator out of range")); | 13217 JSON_THROW(invalid_iterator::create(205, "iterator out of range")); |
4322 } | 13218 } |
4323 | 13219 |
4324 if (is_string()) | 13220 if (is_string()) |
4325 { | 13221 { |
4326 AllocatorType<string_t> alloc; | 13222 AllocatorType<string_t> alloc; |
4327 alloc.destroy(m_value.string); | 13223 std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string); |
4328 alloc.deallocate(m_value.string, 1); | 13224 std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1); |
4329 m_value.string = nullptr; | 13225 m_value.string = nullptr; |
4330 } | 13226 } |
4331 | 13227 |
4332 m_type = value_t::null; | 13228 m_type = value_t::null; |
4333 assert_invariant(); | 13229 assert_invariant(); |
4345 result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); | 13241 result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); |
4346 break; | 13242 break; |
4347 } | 13243 } |
4348 | 13244 |
4349 default: | 13245 default: |
4350 { | 13246 JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); |
4351 JSON_THROW(std::domain_error("cannot use erase() with " + type_name())); | |
4352 } | |
4353 } | 13247 } |
4354 | 13248 |
4355 return result; | 13249 return result; |
4356 } | 13250 } |
4357 | 13251 |
4373 @tparam IteratorType an @ref iterator or @ref const_iterator | 13267 @tparam IteratorType an @ref iterator or @ref const_iterator |
4374 | 13268 |
4375 @post Invalidates iterators and references at or after the point of the | 13269 @post Invalidates iterators and references at or after the point of the |
4376 erase, including the `end()` iterator. | 13270 erase, including the `end()` iterator. |
4377 | 13271 |
4378 @throw std::domain_error if called on a `null` value; example: `"cannot | 13272 @throw type_error.307 if called on a `null` value; example: `"cannot use |
4379 use erase() with null"` | 13273 erase() with null"` |
4380 @throw std::domain_error if called on iterators which does not belong to | 13274 @throw invalid_iterator.203 if called on iterators which does not belong |
4381 the current JSON value; example: `"iterators do not fit current value"` | 13275 to the current JSON value; example: `"iterators do not fit current value"` |
4382 @throw std::out_of_range if called on a primitive type with invalid | 13276 @throw invalid_iterator.204 if called on a primitive type with invalid |
4383 iterators (i.e., if `first != begin()` and `last != end()`); example: | 13277 iterators (i.e., if `first != begin()` and `last != end()`); example: |
4384 `"iterators out of range"` | 13278 `"iterators out of range"` |
4385 | 13279 |
4386 @complexity The complexity depends on the type: | 13280 @complexity The complexity depends on the type: |
4387 - objects: `log(size()) + std::distance(first, last)` | 13281 - objects: `log(size()) + std::distance(first, last)` |
4406 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type | 13300 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type |
4407 = 0> | 13301 = 0> |
4408 IteratorType erase(IteratorType first, IteratorType last) | 13302 IteratorType erase(IteratorType first, IteratorType last) |
4409 { | 13303 { |
4410 // make sure iterator fits the current value | 13304 // make sure iterator fits the current value |
4411 if (this != first.m_object or this != last.m_object) | 13305 if (JSON_UNLIKELY(this != first.m_object or this != last.m_object)) |
4412 { | 13306 { |
4413 JSON_THROW(std::domain_error("iterators do not fit current value")); | 13307 JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value")); |
4414 } | 13308 } |
4415 | 13309 |
4416 IteratorType result = end(); | 13310 IteratorType result = end(); |
4417 | 13311 |
4418 switch (m_type) | 13312 switch (m_type) |
4421 case value_t::number_float: | 13315 case value_t::number_float: |
4422 case value_t::number_integer: | 13316 case value_t::number_integer: |
4423 case value_t::number_unsigned: | 13317 case value_t::number_unsigned: |
4424 case value_t::string: | 13318 case value_t::string: |
4425 { | 13319 { |
4426 if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end()) | 13320 if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin() |
4427 { | 13321 or not last.m_it.primitive_iterator.is_end())) |
4428 JSON_THROW(std::out_of_range("iterators out of range")); | 13322 { |
13323 JSON_THROW(invalid_iterator::create(204, "iterators out of range")); | |
4429 } | 13324 } |
4430 | 13325 |
4431 if (is_string()) | 13326 if (is_string()) |
4432 { | 13327 { |
4433 AllocatorType<string_t> alloc; | 13328 AllocatorType<string_t> alloc; |
4434 alloc.destroy(m_value.string); | 13329 std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string); |
4435 alloc.deallocate(m_value.string, 1); | 13330 std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1); |
4436 m_value.string = nullptr; | 13331 m_value.string = nullptr; |
4437 } | 13332 } |
4438 | 13333 |
4439 m_type = value_t::null; | 13334 m_type = value_t::null; |
4440 assert_invariant(); | 13335 assert_invariant(); |
4454 last.m_it.array_iterator); | 13349 last.m_it.array_iterator); |
4455 break; | 13350 break; |
4456 } | 13351 } |
4457 | 13352 |
4458 default: | 13353 default: |
4459 { | 13354 JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); |
4460 JSON_THROW(std::domain_error("cannot use erase() with " + type_name())); | |
4461 } | |
4462 } | 13355 } |
4463 | 13356 |
4464 return result; | 13357 return result; |
4465 } | 13358 } |
4466 | 13359 |
4476 found) or `1` (@a key was found). | 13369 found) or `1` (@a key was found). |
4477 | 13370 |
4478 @post References and iterators to the erased elements are invalidated. | 13371 @post References and iterators to the erased elements are invalidated. |
4479 Other references and iterators are not affected. | 13372 Other references and iterators are not affected. |
4480 | 13373 |
4481 @throw std::domain_error when called on a type other than JSON object; | 13374 @throw type_error.307 when called on a type other than JSON object; |
4482 example: `"cannot use erase() with null"` | 13375 example: `"cannot use erase() with null"` |
4483 | 13376 |
4484 @complexity `log(size()) + count(key)` | 13377 @complexity `log(size()) + count(key)` |
4485 | 13378 |
4486 @liveexample{The example shows the effect of `erase()`.,erase__key_type} | 13379 @liveexample{The example shows the effect of `erase()`.,erase__key_type} |
4494 @since version 1.0.0 | 13387 @since version 1.0.0 |
4495 */ | 13388 */ |
4496 size_type erase(const typename object_t::key_type& key) | 13389 size_type erase(const typename object_t::key_type& key) |
4497 { | 13390 { |
4498 // this erase only works for objects | 13391 // this erase only works for objects |
4499 if (is_object()) | 13392 if (JSON_LIKELY(is_object())) |
4500 { | 13393 { |
4501 return m_value.object->erase(key); | 13394 return m_value.object->erase(key); |
4502 } | 13395 } |
4503 | 13396 |
4504 JSON_THROW(std::domain_error("cannot use erase() with " + type_name())); | 13397 JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); |
4505 } | 13398 } |
4506 | 13399 |
4507 /*! | 13400 /*! |
4508 @brief remove element from a JSON array given an index | 13401 @brief remove element from a JSON array given an index |
4509 | 13402 |
4510 Removes element from a JSON array at the index @a idx. | 13403 Removes element from a JSON array at the index @a idx. |
4511 | 13404 |
4512 @param[in] idx index of the element to remove | 13405 @param[in] idx index of the element to remove |
4513 | 13406 |
4514 @throw std::domain_error when called on a type other than JSON array; | 13407 @throw type_error.307 when called on a type other than JSON object; |
4515 example: `"cannot use erase() with null"` | 13408 example: `"cannot use erase() with null"` |
4516 @throw std::out_of_range when `idx >= size()`; example: `"array index 17 | 13409 @throw out_of_range.401 when `idx >= size()`; example: `"array index 17 |
4517 is out of range"` | 13410 is out of range"` |
4518 | 13411 |
4519 @complexity Linear in distance between @a idx and the end of the container. | 13412 @complexity Linear in distance between @a idx and the end of the container. |
4520 | 13413 |
4521 @liveexample{The example shows the effect of `erase()`.,erase__size_type} | 13414 @liveexample{The example shows the effect of `erase()`.,erase__size_type} |
4529 @since version 1.0.0 | 13422 @since version 1.0.0 |
4530 */ | 13423 */ |
4531 void erase(const size_type idx) | 13424 void erase(const size_type idx) |
4532 { | 13425 { |
4533 // this erase only works for arrays | 13426 // this erase only works for arrays |
4534 if (is_array()) | 13427 if (JSON_LIKELY(is_array())) |
4535 { | 13428 { |
4536 if (idx >= size()) | 13429 if (JSON_UNLIKELY(idx >= size())) |
4537 { | 13430 { |
4538 JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range")); | 13431 JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); |
4539 } | 13432 } |
4540 | 13433 |
4541 m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx)); | 13434 m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx)); |
4542 } | 13435 } |
4543 else | 13436 else |
4544 { | 13437 { |
4545 JSON_THROW(std::domain_error("cannot use erase() with " + type_name())); | 13438 JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); |
4546 } | 13439 } |
4547 } | 13440 } |
4548 | 13441 |
4549 /// @} | 13442 /// @} |
4550 | 13443 |
4564 returned. | 13457 returned. |
4565 | 13458 |
4566 @note This method always returns @ref end() when executed on a JSON type | 13459 @note This method always returns @ref end() when executed on a JSON type |
4567 that is not an object. | 13460 that is not an object. |
4568 | 13461 |
4569 @param[in] key key value of the element to search for | 13462 @param[in] key key value of the element to search for. |
4570 | 13463 |
4571 @return Iterator to an element with key equivalent to @a key. If no such | 13464 @return Iterator to an element with key equivalent to @a key. If no such |
4572 element is found or the JSON value is not an object, past-the-end (see | 13465 element is found or the JSON value is not an object, past-the-end (see |
4573 @ref end()) iterator is returned. | 13466 @ref end()) iterator is returned. |
4574 | 13467 |
4576 | 13469 |
4577 @liveexample{The example shows how `find()` is used.,find__key_type} | 13470 @liveexample{The example shows how `find()` is used.,find__key_type} |
4578 | 13471 |
4579 @since version 1.0.0 | 13472 @since version 1.0.0 |
4580 */ | 13473 */ |
4581 iterator find(typename object_t::key_type key) | 13474 template<typename KeyT> |
13475 iterator find(KeyT&& key) | |
4582 { | 13476 { |
4583 auto result = end(); | 13477 auto result = end(); |
4584 | 13478 |
4585 if (is_object()) | 13479 if (is_object()) |
4586 { | 13480 { |
4587 result.m_it.object_iterator = m_value.object->find(key); | 13481 result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key)); |
4588 } | 13482 } |
4589 | 13483 |
4590 return result; | 13484 return result; |
4591 } | 13485 } |
4592 | 13486 |
4593 /*! | 13487 /*! |
4594 @brief find an element in a JSON object | 13488 @brief find an element in a JSON object |
4595 @copydoc find(typename object_t::key_type) | 13489 @copydoc find(KeyT&&) |
4596 */ | 13490 */ |
4597 const_iterator find(typename object_t::key_type key) const | 13491 template<typename KeyT> |
13492 const_iterator find(KeyT&& key) const | |
4598 { | 13493 { |
4599 auto result = cend(); | 13494 auto result = cend(); |
4600 | 13495 |
4601 if (is_object()) | 13496 if (is_object()) |
4602 { | 13497 { |
4603 result.m_it.object_iterator = m_value.object->find(key); | 13498 result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key)); |
4604 } | 13499 } |
4605 | 13500 |
4606 return result; | 13501 return result; |
4607 } | 13502 } |
4608 | 13503 |
4625 | 13520 |
4626 @liveexample{The example shows how `count()` is used.,count} | 13521 @liveexample{The example shows how `count()` is used.,count} |
4627 | 13522 |
4628 @since version 1.0.0 | 13523 @since version 1.0.0 |
4629 */ | 13524 */ |
4630 size_type count(typename object_t::key_type key) const | 13525 template<typename KeyT> |
13526 size_type count(KeyT&& key) const | |
4631 { | 13527 { |
4632 // return 0 for all nonobject types | 13528 // return 0 for all nonobject types |
4633 return is_object() ? m_value.object->count(key) : 0; | 13529 return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0; |
4634 } | 13530 } |
4635 | 13531 |
4636 /// @} | 13532 /// @} |
4637 | 13533 |
4638 | 13534 |
4914 const_reverse_iterator crend() const noexcept | 13810 const_reverse_iterator crend() const noexcept |
4915 { | 13811 { |
4916 return const_reverse_iterator(cbegin()); | 13812 return const_reverse_iterator(cbegin()); |
4917 } | 13813 } |
4918 | 13814 |
4919 private: | |
4920 // forward declaration | |
4921 template<typename IteratorType> class iteration_proxy; | |
4922 | |
4923 public: | 13815 public: |
4924 /*! | 13816 /*! |
4925 @brief wrapper to access iterator member functions in range-based for | 13817 @brief wrapper to access iterator member functions in range-based for |
4926 | 13818 |
4927 This function allows to access @ref iterator::key() and @ref | 13819 This function allows to access @ref iterator::key() and @ref |
4928 iterator::value() during range-based for loops. In these loops, a | 13820 iterator::value() during range-based for loops. In these loops, a |
4929 reference to the JSON values is returned, so there is no access to the | 13821 reference to the JSON values is returned, so there is no access to the |
4930 underlying iterator. | 13822 underlying iterator. |
4931 | 13823 |
13824 For loop without iterator_wrapper: | |
13825 | |
13826 @code{cpp} | |
13827 for (auto it = j_object.begin(); it != j_object.end(); ++it) | |
13828 { | |
13829 std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; | |
13830 } | |
13831 @endcode | |
13832 | |
13833 Range-based for loop without iterator proxy: | |
13834 | |
13835 @code{cpp} | |
13836 for (auto it : j_object) | |
13837 { | |
13838 // "it" is of type json::reference and has no key() member | |
13839 std::cout << "value: " << it << '\n'; | |
13840 } | |
13841 @endcode | |
13842 | |
13843 Range-based for loop with iterator proxy: | |
13844 | |
13845 @code{cpp} | |
13846 for (auto it : json::iterator_wrapper(j_object)) | |
13847 { | |
13848 std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; | |
13849 } | |
13850 @endcode | |
13851 | |
13852 @note When iterating over an array, `key()` will return the index of the | |
13853 element as string (see example). | |
13854 | |
13855 @param[in] ref reference to a JSON value | |
13856 @return iteration proxy object wrapping @a ref with an interface to use in | |
13857 range-based for loops | |
13858 | |
13859 @liveexample{The following code shows how the wrapper is used,iterator_wrapper} | |
13860 | |
13861 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
13862 changes in the JSON value. | |
13863 | |
13864 @complexity Constant. | |
13865 | |
4932 @note The name of this function is not yet final and may change in the | 13866 @note The name of this function is not yet final and may change in the |
4933 future. | 13867 future. |
4934 */ | 13868 |
4935 static iteration_proxy<iterator> iterator_wrapper(reference cont) | 13869 @deprecated This stream operator is deprecated and will be removed in |
4936 { | 13870 future 4.0.0 of the library. Please use @ref items() instead; |
4937 return iteration_proxy<iterator>(cont); | 13871 that is, replace `json::iterator_wrapper(j)` with `j.items()`. |
13872 */ | |
13873 JSON_DEPRECATED | |
13874 static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept | |
13875 { | |
13876 return ref.items(); | |
4938 } | 13877 } |
4939 | 13878 |
4940 /*! | 13879 /*! |
4941 @copydoc iterator_wrapper(reference) | 13880 @copydoc iterator_wrapper(reference) |
4942 */ | 13881 */ |
4943 static iteration_proxy<const_iterator> iterator_wrapper(const_reference cont) | 13882 JSON_DEPRECATED |
4944 { | 13883 static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept |
4945 return iteration_proxy<const_iterator>(cont); | 13884 { |
13885 return ref.items(); | |
13886 } | |
13887 | |
13888 /*! | |
13889 @brief helper to access iterator member functions in range-based for | |
13890 | |
13891 This function allows to access @ref iterator::key() and @ref | |
13892 iterator::value() during range-based for loops. In these loops, a | |
13893 reference to the JSON values is returned, so there is no access to the | |
13894 underlying iterator. | |
13895 | |
13896 For loop without `items()` function: | |
13897 | |
13898 @code{cpp} | |
13899 for (auto it = j_object.begin(); it != j_object.end(); ++it) | |
13900 { | |
13901 std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; | |
13902 } | |
13903 @endcode | |
13904 | |
13905 Range-based for loop without `items()` function: | |
13906 | |
13907 @code{cpp} | |
13908 for (auto it : j_object) | |
13909 { | |
13910 // "it" is of type json::reference and has no key() member | |
13911 std::cout << "value: " << it << '\n'; | |
13912 } | |
13913 @endcode | |
13914 | |
13915 Range-based for loop with `items()` function: | |
13916 | |
13917 @code{cpp} | |
13918 for (auto it : j_object.items()) | |
13919 { | |
13920 std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; | |
13921 } | |
13922 @endcode | |
13923 | |
13924 @note When iterating over an array, `key()` will return the index of the | |
13925 element as string (see example). For primitive types (e.g., numbers), | |
13926 `key()` returns an empty string. | |
13927 | |
13928 @return iteration proxy object wrapping @a ref with an interface to use in | |
13929 range-based for loops | |
13930 | |
13931 @liveexample{The following code shows how the function is used.,items} | |
13932 | |
13933 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
13934 changes in the JSON value. | |
13935 | |
13936 @complexity Constant. | |
13937 | |
13938 @since version 3.x.x. | |
13939 */ | |
13940 iteration_proxy<iterator> items() noexcept | |
13941 { | |
13942 return iteration_proxy<iterator>(*this); | |
13943 } | |
13944 | |
13945 /*! | |
13946 @copydoc items() | |
13947 */ | |
13948 iteration_proxy<const_iterator> items() const noexcept | |
13949 { | |
13950 return iteration_proxy<const_iterator>(*this); | |
4946 } | 13951 } |
4947 | 13952 |
4948 /// @} | 13953 /// @} |
4949 | 13954 |
4950 | 13955 |
4954 | 13959 |
4955 /// @name capacity | 13960 /// @name capacity |
4956 /// @{ | 13961 /// @{ |
4957 | 13962 |
4958 /*! | 13963 /*! |
4959 @brief checks whether the container is empty | 13964 @brief checks whether the container is empty. |
4960 | 13965 |
4961 Checks if a JSON value has no elements. | 13966 Checks if a JSON value has no elements (i.e. whether its @ref size is `0`). |
4962 | 13967 |
4963 @return The return value depends on the different types and is | 13968 @return The return value depends on the different types and is |
4964 defined as follows: | 13969 defined as follows: |
4965 Value type | return value | 13970 Value type | return value |
4966 ----------- | ------------- | 13971 ----------- | ------------- |
4969 string | `false` | 13974 string | `false` |
4970 number | `false` | 13975 number | `false` |
4971 object | result of function `object_t::empty()` | 13976 object | result of function `object_t::empty()` |
4972 array | result of function `array_t::empty()` | 13977 array | result of function `array_t::empty()` |
4973 | 13978 |
13979 @liveexample{The following code uses `empty()` to check if a JSON | |
13980 object contains any elements.,empty} | |
13981 | |
13982 @complexity Constant, as long as @ref array_t and @ref object_t satisfy | |
13983 the Container concept; that is, their `empty()` functions have constant | |
13984 complexity. | |
13985 | |
13986 @iterators No changes. | |
13987 | |
13988 @exceptionsafety No-throw guarantee: this function never throws exceptions. | |
13989 | |
4974 @note This function does not return whether a string stored as JSON value | 13990 @note This function does not return whether a string stored as JSON value |
4975 is empty - it returns whether the JSON container itself is empty which is | 13991 is empty - it returns whether the JSON container itself is empty which is |
4976 false in the case of a string. | 13992 false in the case of a string. |
4977 | |
4978 @complexity Constant, as long as @ref array_t and @ref object_t satisfy | |
4979 the Container concept; that is, their `empty()` functions have constant | |
4980 complexity. | |
4981 | 13993 |
4982 @requirement This function helps `basic_json` satisfying the | 13994 @requirement This function helps `basic_json` satisfying the |
4983 [Container](http://en.cppreference.com/w/cpp/concept/Container) | 13995 [Container](http://en.cppreference.com/w/cpp/concept/Container) |
4984 requirements: | 13996 requirements: |
4985 - The complexity is constant. | 13997 - The complexity is constant. |
4986 - Has the semantics of `begin() == end()`. | 13998 - Has the semantics of `begin() == end()`. |
4987 | |
4988 @liveexample{The following code uses `empty()` to check if a JSON | |
4989 object contains any elements.,empty} | |
4990 | 13999 |
4991 @sa @ref size() -- returns the number of elements | 14000 @sa @ref size() -- returns the number of elements |
4992 | 14001 |
4993 @since version 1.0.0 | 14002 @since version 1.0.0 |
4994 */ | 14003 */ |
5036 string | `1` | 14045 string | `1` |
5037 number | `1` | 14046 number | `1` |
5038 object | result of function object_t::size() | 14047 object | result of function object_t::size() |
5039 array | result of function array_t::size() | 14048 array | result of function array_t::size() |
5040 | 14049 |
14050 @liveexample{The following code calls `size()` on the different value | |
14051 types.,size} | |
14052 | |
14053 @complexity Constant, as long as @ref array_t and @ref object_t satisfy | |
14054 the Container concept; that is, their size() functions have constant | |
14055 complexity. | |
14056 | |
14057 @iterators No changes. | |
14058 | |
14059 @exceptionsafety No-throw guarantee: this function never throws exceptions. | |
14060 | |
5041 @note This function does not return the length of a string stored as JSON | 14061 @note This function does not return the length of a string stored as JSON |
5042 value - it returns the number of elements in the JSON value which is 1 in | 14062 value - it returns the number of elements in the JSON value which is 1 in |
5043 the case of a string. | 14063 the case of a string. |
5044 | |
5045 @complexity Constant, as long as @ref array_t and @ref object_t satisfy | |
5046 the Container concept; that is, their size() functions have constant | |
5047 complexity. | |
5048 | 14064 |
5049 @requirement This function helps `basic_json` satisfying the | 14065 @requirement This function helps `basic_json` satisfying the |
5050 [Container](http://en.cppreference.com/w/cpp/concept/Container) | 14066 [Container](http://en.cppreference.com/w/cpp/concept/Container) |
5051 requirements: | 14067 requirements: |
5052 - The complexity is constant. | 14068 - The complexity is constant. |
5053 - Has the semantics of `std::distance(begin(), end())`. | 14069 - Has the semantics of `std::distance(begin(), end())`. |
5054 | |
5055 @liveexample{The following code calls `size()` on the different value | |
5056 types.,size} | |
5057 | 14070 |
5058 @sa @ref empty() -- checks whether the container is empty | 14071 @sa @ref empty() -- checks whether the container is empty |
5059 @sa @ref max_size() -- returns the maximal number of elements | 14072 @sa @ref max_size() -- returns the maximal number of elements |
5060 | 14073 |
5061 @since version 1.0.0 | 14074 @since version 1.0.0 |
5106 string | `1` (same as `size()`) | 14119 string | `1` (same as `size()`) |
5107 number | `1` (same as `size()`) | 14120 number | `1` (same as `size()`) |
5108 object | result of function `object_t::max_size()` | 14121 object | result of function `object_t::max_size()` |
5109 array | result of function `array_t::max_size()` | 14122 array | result of function `array_t::max_size()` |
5110 | 14123 |
14124 @liveexample{The following code calls `max_size()` on the different value | |
14125 types. Note the output is implementation specific.,max_size} | |
14126 | |
5111 @complexity Constant, as long as @ref array_t and @ref object_t satisfy | 14127 @complexity Constant, as long as @ref array_t and @ref object_t satisfy |
5112 the Container concept; that is, their `max_size()` functions have constant | 14128 the Container concept; that is, their `max_size()` functions have constant |
5113 complexity. | 14129 complexity. |
14130 | |
14131 @iterators No changes. | |
14132 | |
14133 @exceptionsafety No-throw guarantee: this function never throws exceptions. | |
5114 | 14134 |
5115 @requirement This function helps `basic_json` satisfying the | 14135 @requirement This function helps `basic_json` satisfying the |
5116 [Container](http://en.cppreference.com/w/cpp/concept/Container) | 14136 [Container](http://en.cppreference.com/w/cpp/concept/Container) |
5117 requirements: | 14137 requirements: |
5118 - The complexity is constant. | 14138 - The complexity is constant. |
5119 - Has the semantics of returning `b.size()` where `b` is the largest | 14139 - Has the semantics of returning `b.size()` where `b` is the largest |
5120 possible JSON value. | 14140 possible JSON value. |
5121 | 14141 |
5122 @liveexample{The following code calls `max_size()` on the different value | |
5123 types. Note the output is implementation specific.,max_size} | |
5124 | |
5125 @sa @ref size() -- returns the number of elements | 14142 @sa @ref size() -- returns the number of elements |
5126 | 14143 |
5127 @since version 1.0.0 | 14144 @since version 1.0.0 |
5128 */ | 14145 */ |
5129 size_type max_size() const noexcept | 14146 size_type max_size() const noexcept |
5162 | 14179 |
5163 /*! | 14180 /*! |
5164 @brief clears the contents | 14181 @brief clears the contents |
5165 | 14182 |
5166 Clears the content of a JSON value and resets it to the default value as | 14183 Clears the content of a JSON value and resets it to the default value as |
5167 if @ref basic_json(value_t) would have been called: | 14184 if @ref basic_json(value_t) would have been called with the current value |
14185 type from @ref type(): | |
5168 | 14186 |
5169 Value type | initial value | 14187 Value type | initial value |
5170 ----------- | ------------- | 14188 ----------- | ------------- |
5171 null | `null` | 14189 null | `null` |
5172 boolean | `false` | 14190 boolean | `false` |
5173 string | `""` | 14191 string | `""` |
5174 number | `0` | 14192 number | `0` |
5175 object | `{}` | 14193 object | `{}` |
5176 array | `[]` | 14194 array | `[]` |
5177 | 14195 |
5178 @complexity Linear in the size of the JSON value. | 14196 @post Has the same effect as calling |
14197 @code {.cpp} | |
14198 *this = basic_json(type()); | |
14199 @endcode | |
5179 | 14200 |
5180 @liveexample{The example below shows the effect of `clear()` to different | 14201 @liveexample{The example below shows the effect of `clear()` to different |
5181 JSON types.,clear} | 14202 JSON types.,clear} |
5182 | 14203 |
14204 @complexity Linear in the size of the JSON value. | |
14205 | |
14206 @iterators All iterators, pointers and references related to this container | |
14207 are invalidated. | |
14208 | |
14209 @exceptionsafety No-throw guarantee: this function never throws exceptions. | |
14210 | |
14211 @sa @ref basic_json(value_t) -- constructor that creates an object with the | |
14212 same value than calling `clear()` | |
14213 | |
5183 @since version 1.0.0 | 14214 @since version 1.0.0 |
5184 */ | 14215 */ |
5185 void clear() noexcept | 14216 void clear() noexcept |
5186 { | 14217 { |
5187 switch (m_type) | 14218 switch (m_type) |
5227 m_value.object->clear(); | 14258 m_value.object->clear(); |
5228 break; | 14259 break; |
5229 } | 14260 } |
5230 | 14261 |
5231 default: | 14262 default: |
5232 { | |
5233 break; | 14263 break; |
5234 } | |
5235 } | 14264 } |
5236 } | 14265 } |
5237 | 14266 |
5238 /*! | 14267 /*! |
5239 @brief add an object to an array | 14268 @brief add an object to an array |
5242 function is called on a JSON null value, an empty array is created before | 14271 function is called on a JSON null value, an empty array is created before |
5243 appending @a val. | 14272 appending @a val. |
5244 | 14273 |
5245 @param[in] val the value to add to the JSON array | 14274 @param[in] val the value to add to the JSON array |
5246 | 14275 |
5247 @throw std::domain_error when called on a type other than JSON array or | 14276 @throw type_error.308 when called on a type other than JSON array or |
5248 null; example: `"cannot use push_back() with number"` | 14277 null; example: `"cannot use push_back() with number"` |
5249 | 14278 |
5250 @complexity Amortized constant. | 14279 @complexity Amortized constant. |
5251 | 14280 |
5252 @liveexample{The example shows how `push_back()` and `+=` can be used to | 14281 @liveexample{The example shows how `push_back()` and `+=` can be used to |
5256 @since version 1.0.0 | 14285 @since version 1.0.0 |
5257 */ | 14286 */ |
5258 void push_back(basic_json&& val) | 14287 void push_back(basic_json&& val) |
5259 { | 14288 { |
5260 // push_back only works for null objects or arrays | 14289 // push_back only works for null objects or arrays |
5261 if (not(is_null() or is_array())) | 14290 if (JSON_UNLIKELY(not(is_null() or is_array()))) |
5262 { | 14291 { |
5263 JSON_THROW(std::domain_error("cannot use push_back() with " + type_name())); | 14292 JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); |
5264 } | 14293 } |
5265 | 14294 |
5266 // transform null object into an array | 14295 // transform null object into an array |
5267 if (is_null()) | 14296 if (is_null()) |
5268 { | 14297 { |
5292 @copydoc push_back(basic_json&&) | 14321 @copydoc push_back(basic_json&&) |
5293 */ | 14322 */ |
5294 void push_back(const basic_json& val) | 14323 void push_back(const basic_json& val) |
5295 { | 14324 { |
5296 // push_back only works for null objects or arrays | 14325 // push_back only works for null objects or arrays |
5297 if (not(is_null() or is_array())) | 14326 if (JSON_UNLIKELY(not(is_null() or is_array()))) |
5298 { | 14327 { |
5299 JSON_THROW(std::domain_error("cannot use push_back() with " + type_name())); | 14328 JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); |
5300 } | 14329 } |
5301 | 14330 |
5302 // transform null object into an array | 14331 // transform null object into an array |
5303 if (is_null()) | 14332 if (is_null()) |
5304 { | 14333 { |
5328 called on a JSON null value, an empty object is created before inserting | 14357 called on a JSON null value, an empty object is created before inserting |
5329 @a val. | 14358 @a val. |
5330 | 14359 |
5331 @param[in] val the value to add to the JSON object | 14360 @param[in] val the value to add to the JSON object |
5332 | 14361 |
5333 @throw std::domain_error when called on a type other than JSON object or | 14362 @throw type_error.308 when called on a type other than JSON object or |
5334 null; example: `"cannot use push_back() with number"` | 14363 null; example: `"cannot use push_back() with number"` |
5335 | 14364 |
5336 @complexity Logarithmic in the size of the container, O(log(`size()`)). | 14365 @complexity Logarithmic in the size of the container, O(log(`size()`)). |
5337 | 14366 |
5338 @liveexample{The example shows how `push_back()` and `+=` can be used to | 14367 @liveexample{The example shows how `push_back()` and `+=` can be used to |
5342 @since version 1.0.0 | 14371 @since version 1.0.0 |
5343 */ | 14372 */ |
5344 void push_back(const typename object_t::value_type& val) | 14373 void push_back(const typename object_t::value_type& val) |
5345 { | 14374 { |
5346 // push_back only works for null objects or objects | 14375 // push_back only works for null objects or objects |
5347 if (not(is_null() or is_object())) | 14376 if (JSON_UNLIKELY(not(is_null() or is_object()))) |
5348 { | 14377 { |
5349 JSON_THROW(std::domain_error("cannot use push_back() with " + type_name())); | 14378 JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); |
5350 } | 14379 } |
5351 | 14380 |
5352 // transform null object into an object | 14381 // transform null object into an object |
5353 if (is_null()) | 14382 if (is_null()) |
5354 { | 14383 { |
5382 | 14411 |
5383 @a init is converted into an object element and added using | 14412 @a init is converted into an object element and added using |
5384 @ref push_back(const typename object_t::value_type&). Otherwise, @a init | 14413 @ref push_back(const typename object_t::value_type&). Otherwise, @a init |
5385 is converted to a JSON value and added using @ref push_back(basic_json&&). | 14414 is converted to a JSON value and added using @ref push_back(basic_json&&). |
5386 | 14415 |
5387 @param init an initializer list | 14416 @param[in] init an initializer list |
5388 | 14417 |
5389 @complexity Linear in the size of the initializer list @a init. | 14418 @complexity Linear in the size of the initializer list @a init. |
5390 | 14419 |
5391 @note This function is required to resolve an ambiguous overload error, | 14420 @note This function is required to resolve an ambiguous overload error, |
5392 because pairs like `{"key", "value"}` can be both interpreted as | 14421 because pairs like `{"key", "value"}` can be both interpreted as |
5394 https://github.com/nlohmann/json/issues/235 for more information. | 14423 https://github.com/nlohmann/json/issues/235 for more information. |
5395 | 14424 |
5396 @liveexample{The example shows how initializer lists are treated as | 14425 @liveexample{The example shows how initializer lists are treated as |
5397 objects when possible.,push_back__initializer_list} | 14426 objects when possible.,push_back__initializer_list} |
5398 */ | 14427 */ |
5399 void push_back(std::initializer_list<basic_json> init) | 14428 void push_back(initializer_list_t init) |
5400 { | 14429 { |
5401 if (is_object() and init.size() == 2 and init.begin()->is_string()) | 14430 if (is_object() and init.size() == 2 and (*init.begin())->is_string()) |
5402 { | 14431 { |
5403 const string_t key = *init.begin(); | 14432 basic_json&& key = init.begin()->moved_or_copied(); |
5404 push_back(typename object_t::value_type(key, *(init.begin() + 1))); | 14433 push_back(typename object_t::value_type( |
14434 std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied())); | |
5405 } | 14435 } |
5406 else | 14436 else |
5407 { | 14437 { |
5408 push_back(basic_json(init)); | 14438 push_back(basic_json(init)); |
5409 } | 14439 } |
5410 } | 14440 } |
5411 | 14441 |
5412 /*! | 14442 /*! |
5413 @brief add an object to an object | 14443 @brief add an object to an object |
5414 @copydoc push_back(std::initializer_list<basic_json>) | 14444 @copydoc push_back(initializer_list_t) |
5415 */ | 14445 */ |
5416 reference operator+=(std::initializer_list<basic_json> init) | 14446 reference operator+=(initializer_list_t init) |
5417 { | 14447 { |
5418 push_back(init); | 14448 push_back(init); |
5419 return *this; | 14449 return *this; |
5420 } | 14450 } |
5421 | 14451 |
5427 is created before appending the value created from @a args. | 14457 is created before appending the value created from @a args. |
5428 | 14458 |
5429 @param[in] args arguments to forward to a constructor of @ref basic_json | 14459 @param[in] args arguments to forward to a constructor of @ref basic_json |
5430 @tparam Args compatible types to create a @ref basic_json object | 14460 @tparam Args compatible types to create a @ref basic_json object |
5431 | 14461 |
5432 @throw std::domain_error when called on a type other than JSON array or | 14462 @throw type_error.311 when called on a type other than JSON array or |
5433 null; example: `"cannot use emplace_back() with number"` | 14463 null; example: `"cannot use emplace_back() with number"` |
5434 | 14464 |
5435 @complexity Amortized constant. | 14465 @complexity Amortized constant. |
5436 | 14466 |
5437 @liveexample{The example shows how `push_back()` can be used to add | 14467 @liveexample{The example shows how `push_back()` can be used to add |
5442 */ | 14472 */ |
5443 template<class... Args> | 14473 template<class... Args> |
5444 void emplace_back(Args&& ... args) | 14474 void emplace_back(Args&& ... args) |
5445 { | 14475 { |
5446 // emplace_back only works for null objects or arrays | 14476 // emplace_back only works for null objects or arrays |
5447 if (not(is_null() or is_array())) | 14477 if (JSON_UNLIKELY(not(is_null() or is_array()))) |
5448 { | 14478 { |
5449 JSON_THROW(std::domain_error("cannot use emplace_back() with " + type_name())); | 14479 JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()))); |
5450 } | 14480 } |
5451 | 14481 |
5452 // transform null object into an array | 14482 // transform null object into an array |
5453 if (is_null()) | 14483 if (is_null()) |
5454 { | 14484 { |
5474 | 14504 |
5475 @return a pair consisting of an iterator to the inserted element, or the | 14505 @return a pair consisting of an iterator to the inserted element, or the |
5476 already-existing element if no insertion happened, and a bool | 14506 already-existing element if no insertion happened, and a bool |
5477 denoting whether the insertion took place. | 14507 denoting whether the insertion took place. |
5478 | 14508 |
5479 @throw std::domain_error when called on a type other than JSON object or | 14509 @throw type_error.311 when called on a type other than JSON object or |
5480 null; example: `"cannot use emplace() with number"` | 14510 null; example: `"cannot use emplace() with number"` |
5481 | 14511 |
5482 @complexity Logarithmic in the size of the container, O(log(`size()`)). | 14512 @complexity Logarithmic in the size of the container, O(log(`size()`)). |
5483 | 14513 |
5484 @liveexample{The example shows how `emplace()` can be used to add elements | 14514 @liveexample{The example shows how `emplace()` can be used to add elements |
5490 */ | 14520 */ |
5491 template<class... Args> | 14521 template<class... Args> |
5492 std::pair<iterator, bool> emplace(Args&& ... args) | 14522 std::pair<iterator, bool> emplace(Args&& ... args) |
5493 { | 14523 { |
5494 // emplace only works for null objects or arrays | 14524 // emplace only works for null objects or arrays |
5495 if (not(is_null() or is_object())) | 14525 if (JSON_UNLIKELY(not(is_null() or is_object()))) |
5496 { | 14526 { |
5497 JSON_THROW(std::domain_error("cannot use emplace() with " + type_name())); | 14527 JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()))); |
5498 } | 14528 } |
5499 | 14529 |
5500 // transform null object into an object | 14530 // transform null object into an object |
5501 if (is_null()) | 14531 if (is_null()) |
5502 { | 14532 { |
5523 @param[in] pos iterator before which the content will be inserted; may be | 14553 @param[in] pos iterator before which the content will be inserted; may be |
5524 the end() iterator | 14554 the end() iterator |
5525 @param[in] val element to insert | 14555 @param[in] val element to insert |
5526 @return iterator pointing to the inserted @a val. | 14556 @return iterator pointing to the inserted @a val. |
5527 | 14557 |
5528 @throw std::domain_error if called on JSON values other than arrays; | 14558 @throw type_error.309 if called on JSON values other than arrays; |
5529 example: `"cannot use insert() with string"` | 14559 example: `"cannot use insert() with string"` |
5530 @throw std::domain_error if @a pos is not an iterator of *this; example: | 14560 @throw invalid_iterator.202 if @a pos is not an iterator of *this; |
5531 `"iterator does not fit current value"` | 14561 example: `"iterator does not fit current value"` |
5532 | 14562 |
5533 @complexity Constant plus linear in the distance between @a pos and end of | 14563 @complexity Constant plus linear in the distance between @a pos and end of |
5534 the container. | 14564 the container. |
5535 | 14565 |
5536 @liveexample{The example shows how `insert()` is used.,insert} | 14566 @liveexample{The example shows how `insert()` is used.,insert} |
5538 @since version 1.0.0 | 14568 @since version 1.0.0 |
5539 */ | 14569 */ |
5540 iterator insert(const_iterator pos, const basic_json& val) | 14570 iterator insert(const_iterator pos, const basic_json& val) |
5541 { | 14571 { |
5542 // insert only works for arrays | 14572 // insert only works for arrays |
5543 if (is_array()) | 14573 if (JSON_LIKELY(is_array())) |
5544 { | 14574 { |
5545 // check if iterator pos fits to this JSON value | 14575 // check if iterator pos fits to this JSON value |
5546 if (pos.m_object != this) | 14576 if (JSON_UNLIKELY(pos.m_object != this)) |
5547 { | 14577 { |
5548 JSON_THROW(std::domain_error("iterator does not fit current value")); | 14578 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); |
5549 } | 14579 } |
5550 | 14580 |
5551 // insert to array and return iterator | 14581 // insert to array and return iterator |
5552 iterator result(this); | 14582 iterator result(this); |
5553 result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val); | 14583 result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val); |
5554 return result; | 14584 return result; |
5555 } | 14585 } |
5556 | 14586 |
5557 JSON_THROW(std::domain_error("cannot use insert() with " + type_name())); | 14587 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); |
5558 } | 14588 } |
5559 | 14589 |
5560 /*! | 14590 /*! |
5561 @brief inserts element | 14591 @brief inserts element |
5562 @copydoc insert(const_iterator, const basic_json&) | 14592 @copydoc insert(const_iterator, const basic_json&) |
5576 @param[in] cnt number of copies of @a val to insert | 14606 @param[in] cnt number of copies of @a val to insert |
5577 @param[in] val element to insert | 14607 @param[in] val element to insert |
5578 @return iterator pointing to the first element inserted, or @a pos if | 14608 @return iterator pointing to the first element inserted, or @a pos if |
5579 `cnt==0` | 14609 `cnt==0` |
5580 | 14610 |
5581 @throw std::domain_error if called on JSON values other than arrays; | 14611 @throw type_error.309 if called on JSON values other than arrays; example: |
5582 example: `"cannot use insert() with string"` | 14612 `"cannot use insert() with string"` |
5583 @throw std::domain_error if @a pos is not an iterator of *this; example: | 14613 @throw invalid_iterator.202 if @a pos is not an iterator of *this; |
5584 `"iterator does not fit current value"` | 14614 example: `"iterator does not fit current value"` |
5585 | 14615 |
5586 @complexity Linear in @a cnt plus linear in the distance between @a pos | 14616 @complexity Linear in @a cnt plus linear in the distance between @a pos |
5587 and end of the container. | 14617 and end of the container. |
5588 | 14618 |
5589 @liveexample{The example shows how `insert()` is used.,insert__count} | 14619 @liveexample{The example shows how `insert()` is used.,insert__count} |
5591 @since version 1.0.0 | 14621 @since version 1.0.0 |
5592 */ | 14622 */ |
5593 iterator insert(const_iterator pos, size_type cnt, const basic_json& val) | 14623 iterator insert(const_iterator pos, size_type cnt, const basic_json& val) |
5594 { | 14624 { |
5595 // insert only works for arrays | 14625 // insert only works for arrays |
5596 if (is_array()) | 14626 if (JSON_LIKELY(is_array())) |
5597 { | 14627 { |
5598 // check if iterator pos fits to this JSON value | 14628 // check if iterator pos fits to this JSON value |
5599 if (pos.m_object != this) | 14629 if (JSON_UNLIKELY(pos.m_object != this)) |
5600 { | 14630 { |
5601 JSON_THROW(std::domain_error("iterator does not fit current value")); | 14631 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); |
5602 } | 14632 } |
5603 | 14633 |
5604 // insert to array and return iterator | 14634 // insert to array and return iterator |
5605 iterator result(this); | 14635 iterator result(this); |
5606 result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); | 14636 result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); |
5607 return result; | 14637 return result; |
5608 } | 14638 } |
5609 | 14639 |
5610 JSON_THROW(std::domain_error("cannot use insert() with " + type_name())); | 14640 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); |
5611 } | 14641 } |
5612 | 14642 |
5613 /*! | 14643 /*! |
5614 @brief inserts elements | 14644 @brief inserts elements |
5615 | 14645 |
5618 @param[in] pos iterator before which the content will be inserted; may be | 14648 @param[in] pos iterator before which the content will be inserted; may be |
5619 the end() iterator | 14649 the end() iterator |
5620 @param[in] first begin of the range of elements to insert | 14650 @param[in] first begin of the range of elements to insert |
5621 @param[in] last end of the range of elements to insert | 14651 @param[in] last end of the range of elements to insert |
5622 | 14652 |
5623 @throw std::domain_error if called on JSON values other than arrays; | 14653 @throw type_error.309 if called on JSON values other than arrays; example: |
5624 example: `"cannot use insert() with string"` | 14654 `"cannot use insert() with string"` |
5625 @throw std::domain_error if @a pos is not an iterator of *this; example: | 14655 @throw invalid_iterator.202 if @a pos is not an iterator of *this; |
5626 `"iterator does not fit current value"` | 14656 example: `"iterator does not fit current value"` |
5627 @throw std::domain_error if @a first and @a last do not belong to the same | 14657 @throw invalid_iterator.210 if @a first and @a last do not belong to the |
5628 JSON value; example: `"iterators do not fit"` | 14658 same JSON value; example: `"iterators do not fit"` |
5629 @throw std::domain_error if @a first or @a last are iterators into | 14659 @throw invalid_iterator.211 if @a first or @a last are iterators into |
5630 container for which insert is called; example: `"passed iterators may not | 14660 container for which insert is called; example: `"passed iterators may not |
5631 belong to container"` | 14661 belong to container"` |
5632 | 14662 |
5633 @return iterator pointing to the first element inserted, or @a pos if | 14663 @return iterator pointing to the first element inserted, or @a pos if |
5634 `first==last` | 14664 `first==last` |
5641 @since version 1.0.0 | 14671 @since version 1.0.0 |
5642 */ | 14672 */ |
5643 iterator insert(const_iterator pos, const_iterator first, const_iterator last) | 14673 iterator insert(const_iterator pos, const_iterator first, const_iterator last) |
5644 { | 14674 { |
5645 // insert only works for arrays | 14675 // insert only works for arrays |
5646 if (not is_array()) | 14676 if (JSON_UNLIKELY(not is_array())) |
5647 { | 14677 { |
5648 JSON_THROW(std::domain_error("cannot use insert() with " + type_name())); | 14678 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); |
5649 } | 14679 } |
5650 | 14680 |
5651 // check if iterator pos fits to this JSON value | 14681 // check if iterator pos fits to this JSON value |
5652 if (pos.m_object != this) | 14682 if (JSON_UNLIKELY(pos.m_object != this)) |
5653 { | 14683 { |
5654 JSON_THROW(std::domain_error("iterator does not fit current value")); | 14684 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); |
5655 } | 14685 } |
5656 | 14686 |
5657 // check if range iterators belong to the same JSON object | 14687 // check if range iterators belong to the same JSON object |
5658 if (first.m_object != last.m_object) | 14688 if (JSON_UNLIKELY(first.m_object != last.m_object)) |
5659 { | 14689 { |
5660 JSON_THROW(std::domain_error("iterators do not fit")); | 14690 JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); |
5661 } | 14691 } |
5662 | 14692 |
5663 if (first.m_object == this or last.m_object == this) | 14693 if (JSON_UNLIKELY(first.m_object == this)) |
5664 { | 14694 { |
5665 JSON_THROW(std::domain_error("passed iterators may not belong to container")); | 14695 JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container")); |
5666 } | 14696 } |
5667 | 14697 |
5668 // insert to array and return iterator | 14698 // insert to array and return iterator |
5669 iterator result(this); | 14699 iterator result(this); |
5670 result.m_it.array_iterator = m_value.array->insert( | 14700 result.m_it.array_iterator = m_value.array->insert( |
5681 | 14711 |
5682 @param[in] pos iterator before which the content will be inserted; may be | 14712 @param[in] pos iterator before which the content will be inserted; may be |
5683 the end() iterator | 14713 the end() iterator |
5684 @param[in] ilist initializer list to insert the values from | 14714 @param[in] ilist initializer list to insert the values from |
5685 | 14715 |
5686 @throw std::domain_error if called on JSON values other than arrays; | 14716 @throw type_error.309 if called on JSON values other than arrays; example: |
5687 example: `"cannot use insert() with string"` | 14717 `"cannot use insert() with string"` |
5688 @throw std::domain_error if @a pos is not an iterator of *this; example: | 14718 @throw invalid_iterator.202 if @a pos is not an iterator of *this; |
5689 `"iterator does not fit current value"` | 14719 example: `"iterator does not fit current value"` |
5690 | 14720 |
5691 @return iterator pointing to the first element inserted, or @a pos if | 14721 @return iterator pointing to the first element inserted, or @a pos if |
5692 `ilist` is empty | 14722 `ilist` is empty |
5693 | 14723 |
5694 @complexity Linear in `ilist.size()` plus linear in the distance between | 14724 @complexity Linear in `ilist.size()` plus linear in the distance between |
5696 | 14726 |
5697 @liveexample{The example shows how `insert()` is used.,insert__ilist} | 14727 @liveexample{The example shows how `insert()` is used.,insert__ilist} |
5698 | 14728 |
5699 @since version 1.0.0 | 14729 @since version 1.0.0 |
5700 */ | 14730 */ |
5701 iterator insert(const_iterator pos, std::initializer_list<basic_json> ilist) | 14731 iterator insert(const_iterator pos, initializer_list_t ilist) |
5702 { | 14732 { |
5703 // insert only works for arrays | 14733 // insert only works for arrays |
5704 if (not is_array()) | 14734 if (JSON_UNLIKELY(not is_array())) |
5705 { | 14735 { |
5706 JSON_THROW(std::domain_error("cannot use insert() with " + type_name())); | 14736 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); |
5707 } | 14737 } |
5708 | 14738 |
5709 // check if iterator pos fits to this JSON value | 14739 // check if iterator pos fits to this JSON value |
5710 if (pos.m_object != this) | 14740 if (JSON_UNLIKELY(pos.m_object != this)) |
5711 { | 14741 { |
5712 JSON_THROW(std::domain_error("iterator does not fit current value")); | 14742 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); |
5713 } | 14743 } |
5714 | 14744 |
5715 // insert to array and return iterator | 14745 // insert to array and return iterator |
5716 iterator result(this); | 14746 iterator result(this); |
5717 result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist); | 14747 result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end()); |
5718 return result; | 14748 return result; |
14749 } | |
14750 | |
14751 /*! | |
14752 @brief inserts elements | |
14753 | |
14754 Inserts elements from range `[first, last)`. | |
14755 | |
14756 @param[in] first begin of the range of elements to insert | |
14757 @param[in] last end of the range of elements to insert | |
14758 | |
14759 @throw type_error.309 if called on JSON values other than objects; example: | |
14760 `"cannot use insert() with string"` | |
14761 @throw invalid_iterator.202 if iterator @a first or @a last does does not | |
14762 point to an object; example: `"iterators first and last must point to | |
14763 objects"` | |
14764 @throw invalid_iterator.210 if @a first and @a last do not belong to the | |
14765 same JSON value; example: `"iterators do not fit"` | |
14766 | |
14767 @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number | |
14768 of elements to insert. | |
14769 | |
14770 @liveexample{The example shows how `insert()` is used.,insert__range_object} | |
14771 | |
14772 @since version 3.0.0 | |
14773 */ | |
14774 void insert(const_iterator first, const_iterator last) | |
14775 { | |
14776 // insert only works for objects | |
14777 if (JSON_UNLIKELY(not is_object())) | |
14778 { | |
14779 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); | |
14780 } | |
14781 | |
14782 // check if range iterators belong to the same JSON object | |
14783 if (JSON_UNLIKELY(first.m_object != last.m_object)) | |
14784 { | |
14785 JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); | |
14786 } | |
14787 | |
14788 // passed iterators must belong to objects | |
14789 if (JSON_UNLIKELY(not first.m_object->is_object())) | |
14790 { | |
14791 JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); | |
14792 } | |
14793 | |
14794 m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); | |
14795 } | |
14796 | |
14797 /*! | |
14798 @brief updates a JSON object from another object, overwriting existing keys | |
14799 | |
14800 Inserts all values from JSON object @a j and overwrites existing keys. | |
14801 | |
14802 @param[in] j JSON object to read values from | |
14803 | |
14804 @throw type_error.312 if called on JSON values other than objects; example: | |
14805 `"cannot use update() with string"` | |
14806 | |
14807 @complexity O(N*log(size() + N)), where N is the number of elements to | |
14808 insert. | |
14809 | |
14810 @liveexample{The example shows how `update()` is used.,update} | |
14811 | |
14812 @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update | |
14813 | |
14814 @since version 3.0.0 | |
14815 */ | |
14816 void update(const_reference j) | |
14817 { | |
14818 // implicitly convert null value to an empty object | |
14819 if (is_null()) | |
14820 { | |
14821 m_type = value_t::object; | |
14822 m_value.object = create<object_t>(); | |
14823 assert_invariant(); | |
14824 } | |
14825 | |
14826 if (JSON_UNLIKELY(not is_object())) | |
14827 { | |
14828 JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); | |
14829 } | |
14830 if (JSON_UNLIKELY(not j.is_object())) | |
14831 { | |
14832 JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name()))); | |
14833 } | |
14834 | |
14835 for (auto it = j.cbegin(); it != j.cend(); ++it) | |
14836 { | |
14837 m_value.object->operator[](it.key()) = it.value(); | |
14838 } | |
14839 } | |
14840 | |
14841 /*! | |
14842 @brief updates a JSON object from another object, overwriting existing keys | |
14843 | |
14844 Inserts all values from from range `[first, last)` and overwrites existing | |
14845 keys. | |
14846 | |
14847 @param[in] first begin of the range of elements to insert | |
14848 @param[in] last end of the range of elements to insert | |
14849 | |
14850 @throw type_error.312 if called on JSON values other than objects; example: | |
14851 `"cannot use update() with string"` | |
14852 @throw invalid_iterator.202 if iterator @a first or @a last does does not | |
14853 point to an object; example: `"iterators first and last must point to | |
14854 objects"` | |
14855 @throw invalid_iterator.210 if @a first and @a last do not belong to the | |
14856 same JSON value; example: `"iterators do not fit"` | |
14857 | |
14858 @complexity O(N*log(size() + N)), where N is the number of elements to | |
14859 insert. | |
14860 | |
14861 @liveexample{The example shows how `update()` is used__range.,update} | |
14862 | |
14863 @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update | |
14864 | |
14865 @since version 3.0.0 | |
14866 */ | |
14867 void update(const_iterator first, const_iterator last) | |
14868 { | |
14869 // implicitly convert null value to an empty object | |
14870 if (is_null()) | |
14871 { | |
14872 m_type = value_t::object; | |
14873 m_value.object = create<object_t>(); | |
14874 assert_invariant(); | |
14875 } | |
14876 | |
14877 if (JSON_UNLIKELY(not is_object())) | |
14878 { | |
14879 JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); | |
14880 } | |
14881 | |
14882 // check if range iterators belong to the same JSON object | |
14883 if (JSON_UNLIKELY(first.m_object != last.m_object)) | |
14884 { | |
14885 JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); | |
14886 } | |
14887 | |
14888 // passed iterators must belong to objects | |
14889 if (JSON_UNLIKELY(not first.m_object->is_object() | |
14890 or not last.m_object->is_object())) | |
14891 { | |
14892 JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); | |
14893 } | |
14894 | |
14895 for (auto it = first; it != last; ++it) | |
14896 { | |
14897 m_value.object->operator[](it.key()) = it.value(); | |
14898 } | |
5719 } | 14899 } |
5720 | 14900 |
5721 /*! | 14901 /*! |
5722 @brief exchanges the values | 14902 @brief exchanges the values |
5723 | 14903 |
5755 iterators and references remain valid. The past-the-end iterator is | 14935 iterators and references remain valid. The past-the-end iterator is |
5756 invalidated. | 14936 invalidated. |
5757 | 14937 |
5758 @param[in,out] other array to exchange the contents with | 14938 @param[in,out] other array to exchange the contents with |
5759 | 14939 |
5760 @throw std::domain_error when JSON value is not an array; example: | 14940 @throw type_error.310 when JSON value is not an array; example: `"cannot |
5761 `"cannot use swap() with string"` | 14941 use swap() with string"` |
5762 | 14942 |
5763 @complexity Constant. | 14943 @complexity Constant. |
5764 | 14944 |
5765 @liveexample{The example below shows how arrays can be swapped with | 14945 @liveexample{The example below shows how arrays can be swapped with |
5766 `swap()`.,swap__array_t} | 14946 `swap()`.,swap__array_t} |
5768 @since version 1.0.0 | 14948 @since version 1.0.0 |
5769 */ | 14949 */ |
5770 void swap(array_t& other) | 14950 void swap(array_t& other) |
5771 { | 14951 { |
5772 // swap only works for arrays | 14952 // swap only works for arrays |
5773 if (is_array()) | 14953 if (JSON_LIKELY(is_array())) |
5774 { | 14954 { |
5775 std::swap(*(m_value.array), other); | 14955 std::swap(*(m_value.array), other); |
5776 } | 14956 } |
5777 else | 14957 else |
5778 { | 14958 { |
5779 JSON_THROW(std::domain_error("cannot use swap() with " + type_name())); | 14959 JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); |
5780 } | 14960 } |
5781 } | 14961 } |
5782 | 14962 |
5783 /*! | 14963 /*! |
5784 @brief exchanges the values | 14964 @brief exchanges the values |
5788 iterators and references remain valid. The past-the-end iterator is | 14968 iterators and references remain valid. The past-the-end iterator is |
5789 invalidated. | 14969 invalidated. |
5790 | 14970 |
5791 @param[in,out] other object to exchange the contents with | 14971 @param[in,out] other object to exchange the contents with |
5792 | 14972 |
5793 @throw std::domain_error when JSON value is not an object; example: | 14973 @throw type_error.310 when JSON value is not an object; example: |
5794 `"cannot use swap() with string"` | 14974 `"cannot use swap() with string"` |
5795 | 14975 |
5796 @complexity Constant. | 14976 @complexity Constant. |
5797 | 14977 |
5798 @liveexample{The example below shows how objects can be swapped with | 14978 @liveexample{The example below shows how objects can be swapped with |
5801 @since version 1.0.0 | 14981 @since version 1.0.0 |
5802 */ | 14982 */ |
5803 void swap(object_t& other) | 14983 void swap(object_t& other) |
5804 { | 14984 { |
5805 // swap only works for objects | 14985 // swap only works for objects |
5806 if (is_object()) | 14986 if (JSON_LIKELY(is_object())) |
5807 { | 14987 { |
5808 std::swap(*(m_value.object), other); | 14988 std::swap(*(m_value.object), other); |
5809 } | 14989 } |
5810 else | 14990 else |
5811 { | 14991 { |
5812 JSON_THROW(std::domain_error("cannot use swap() with " + type_name())); | 14992 JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); |
5813 } | 14993 } |
5814 } | 14994 } |
5815 | 14995 |
5816 /*! | 14996 /*! |
5817 @brief exchanges the values | 14997 @brief exchanges the values |
5821 iterators and references remain valid. The past-the-end iterator is | 15001 iterators and references remain valid. The past-the-end iterator is |
5822 invalidated. | 15002 invalidated. |
5823 | 15003 |
5824 @param[in,out] other string to exchange the contents with | 15004 @param[in,out] other string to exchange the contents with |
5825 | 15005 |
5826 @throw std::domain_error when JSON value is not a string; example: `"cannot | 15006 @throw type_error.310 when JSON value is not a string; example: `"cannot |
5827 use swap() with boolean"` | 15007 use swap() with boolean"` |
5828 | 15008 |
5829 @complexity Constant. | 15009 @complexity Constant. |
5830 | 15010 |
5831 @liveexample{The example below shows how strings can be swapped with | 15011 @liveexample{The example below shows how strings can be swapped with |
5834 @since version 1.0.0 | 15014 @since version 1.0.0 |
5835 */ | 15015 */ |
5836 void swap(string_t& other) | 15016 void swap(string_t& other) |
5837 { | 15017 { |
5838 // swap only works for strings | 15018 // swap only works for strings |
5839 if (is_string()) | 15019 if (JSON_LIKELY(is_string())) |
5840 { | 15020 { |
5841 std::swap(*(m_value.string), other); | 15021 std::swap(*(m_value.string), other); |
5842 } | 15022 } |
5843 else | 15023 else |
5844 { | 15024 { |
5845 JSON_THROW(std::domain_error("cannot use swap() with " + type_name())); | 15025 JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); |
5846 } | 15026 } |
5847 } | 15027 } |
5848 | 15028 |
5849 /// @} | 15029 /// @} |
5850 | 15030 |
5859 /*! | 15039 /*! |
5860 @brief comparison: equal | 15040 @brief comparison: equal |
5861 | 15041 |
5862 Compares two JSON values for equality according to the following rules: | 15042 Compares two JSON values for equality according to the following rules: |
5863 - Two JSON values are equal if (1) they are from the same type and (2) | 15043 - Two JSON values are equal if (1) they are from the same type and (2) |
5864 their stored values are the same. | 15044 their stored values are the same according to their respective |
15045 `operator==`. | |
5865 - Integer and floating-point numbers are automatically converted before | 15046 - Integer and floating-point numbers are automatically converted before |
5866 comparison. Floating-point numbers are compared indirectly: two | 15047 comparison. Note than two NaN values are always treated as unequal. |
5867 floating-point numbers `f1` and `f2` are considered equal if neither | |
5868 `f1 > f2` nor `f2 > f1` holds. | |
5869 - Two JSON null values are equal. | 15048 - Two JSON null values are equal. |
15049 | |
15050 @note Floating-point inside JSON values numbers are compared with | |
15051 `json::number_float_t::operator==` which is `double::operator==` by | |
15052 default. To compare floating-point while respecting an epsilon, an alternative | |
15053 [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39) | |
15054 could be used, for instance | |
15055 @code {.cpp} | |
15056 template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type> | |
15057 inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept | |
15058 { | |
15059 return std::abs(a - b) <= epsilon; | |
15060 } | |
15061 @endcode | |
15062 | |
15063 @note NaN values never compare equal to themselves or to other NaN values. | |
5870 | 15064 |
5871 @param[in] lhs first JSON value to consider | 15065 @param[in] lhs first JSON value to consider |
5872 @param[in] rhs second JSON value to consider | 15066 @param[in] rhs second JSON value to consider |
5873 @return whether the values @a lhs and @a rhs are equal | 15067 @return whether the values @a lhs and @a rhs are equal |
5874 | 15068 |
15069 @exceptionsafety No-throw guarantee: this function never throws exceptions. | |
15070 | |
5875 @complexity Linear. | 15071 @complexity Linear. |
5876 | 15072 |
5877 @liveexample{The example demonstrates comparing several JSON | 15073 @liveexample{The example demonstrates comparing several JSON |
5878 types.,operator__equal} | 15074 types.,operator__equal} |
5879 | 15075 |
5887 if (lhs_type == rhs_type) | 15083 if (lhs_type == rhs_type) |
5888 { | 15084 { |
5889 switch (lhs_type) | 15085 switch (lhs_type) |
5890 { | 15086 { |
5891 case value_t::array: | 15087 case value_t::array: |
5892 { | 15088 return (*lhs.m_value.array == *rhs.m_value.array); |
5893 return *lhs.m_value.array == *rhs.m_value.array; | 15089 |
5894 } | |
5895 case value_t::object: | 15090 case value_t::object: |
5896 { | 15091 return (*lhs.m_value.object == *rhs.m_value.object); |
5897 return *lhs.m_value.object == *rhs.m_value.object; | 15092 |
5898 } | |
5899 case value_t::null: | 15093 case value_t::null: |
5900 { | |
5901 return true; | 15094 return true; |
5902 } | 15095 |
5903 case value_t::string: | 15096 case value_t::string: |
5904 { | 15097 return (*lhs.m_value.string == *rhs.m_value.string); |
5905 return *lhs.m_value.string == *rhs.m_value.string; | 15098 |
5906 } | |
5907 case value_t::boolean: | 15099 case value_t::boolean: |
5908 { | 15100 return (lhs.m_value.boolean == rhs.m_value.boolean); |
5909 return lhs.m_value.boolean == rhs.m_value.boolean; | 15101 |
5910 } | |
5911 case value_t::number_integer: | 15102 case value_t::number_integer: |
5912 { | 15103 return (lhs.m_value.number_integer == rhs.m_value.number_integer); |
5913 return lhs.m_value.number_integer == rhs.m_value.number_integer; | 15104 |
5914 } | |
5915 case value_t::number_unsigned: | 15105 case value_t::number_unsigned: |
5916 { | 15106 return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned); |
5917 return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; | 15107 |
5918 } | |
5919 case value_t::number_float: | 15108 case value_t::number_float: |
5920 { | 15109 return (lhs.m_value.number_float == rhs.m_value.number_float); |
5921 return lhs.m_value.number_float == rhs.m_value.number_float; | 15110 |
5922 } | |
5923 default: | 15111 default: |
5924 { | |
5925 return false; | 15112 return false; |
5926 } | |
5927 } | 15113 } |
5928 } | 15114 } |
5929 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) | 15115 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) |
5930 { | 15116 { |
5931 return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float; | 15117 return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float); |
5932 } | 15118 } |
5933 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) | 15119 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) |
5934 { | 15120 { |
5935 return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer); | 15121 return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer)); |
5936 } | 15122 } |
5937 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) | 15123 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) |
5938 { | 15124 { |
5939 return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float; | 15125 return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float); |
5940 } | 15126 } |
5941 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) | 15127 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) |
5942 { | 15128 { |
5943 return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned); | 15129 return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned)); |
5944 } | 15130 } |
5945 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) | 15131 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) |
5946 { | 15132 { |
5947 return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; | 15133 return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer); |
5948 } | 15134 } |
5949 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) | 15135 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) |
5950 { | 15136 { |
5951 return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned); | 15137 return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned)); |
5952 } | 15138 } |
5953 | 15139 |
5954 return false; | 15140 return false; |
5955 } | 15141 } |
5956 | 15142 |
5984 @param[in] lhs first JSON value to consider | 15170 @param[in] lhs first JSON value to consider |
5985 @param[in] rhs second JSON value to consider | 15171 @param[in] rhs second JSON value to consider |
5986 @return whether the values @a lhs and @a rhs are not equal | 15172 @return whether the values @a lhs and @a rhs are not equal |
5987 | 15173 |
5988 @complexity Linear. | 15174 @complexity Linear. |
15175 | |
15176 @exceptionsafety No-throw guarantee: this function never throws exceptions. | |
5989 | 15177 |
5990 @liveexample{The example demonstrates comparing several JSON | 15178 @liveexample{The example demonstrates comparing several JSON |
5991 types.,operator__notequal} | 15179 types.,operator__notequal} |
5992 | 15180 |
5993 @since version 1.0.0 | 15181 @since version 1.0.0 |
6036 @param[in] rhs second JSON value to consider | 15224 @param[in] rhs second JSON value to consider |
6037 @return whether @a lhs is less than @a rhs | 15225 @return whether @a lhs is less than @a rhs |
6038 | 15226 |
6039 @complexity Linear. | 15227 @complexity Linear. |
6040 | 15228 |
15229 @exceptionsafety No-throw guarantee: this function never throws exceptions. | |
15230 | |
6041 @liveexample{The example demonstrates comparing several JSON | 15231 @liveexample{The example demonstrates comparing several JSON |
6042 types.,operator__less} | 15232 types.,operator__less} |
6043 | 15233 |
6044 @since version 1.0.0 | 15234 @since version 1.0.0 |
6045 */ | 15235 */ |
6051 if (lhs_type == rhs_type) | 15241 if (lhs_type == rhs_type) |
6052 { | 15242 { |
6053 switch (lhs_type) | 15243 switch (lhs_type) |
6054 { | 15244 { |
6055 case value_t::array: | 15245 case value_t::array: |
6056 { | 15246 return (*lhs.m_value.array) < (*rhs.m_value.array); |
6057 return *lhs.m_value.array < *rhs.m_value.array; | 15247 |
6058 } | |
6059 case value_t::object: | 15248 case value_t::object: |
6060 { | |
6061 return *lhs.m_value.object < *rhs.m_value.object; | 15249 return *lhs.m_value.object < *rhs.m_value.object; |
6062 } | 15250 |
6063 case value_t::null: | 15251 case value_t::null: |
6064 { | |
6065 return false; | 15252 return false; |
6066 } | 15253 |
6067 case value_t::string: | 15254 case value_t::string: |
6068 { | |
6069 return *lhs.m_value.string < *rhs.m_value.string; | 15255 return *lhs.m_value.string < *rhs.m_value.string; |
6070 } | 15256 |
6071 case value_t::boolean: | 15257 case value_t::boolean: |
6072 { | |
6073 return lhs.m_value.boolean < rhs.m_value.boolean; | 15258 return lhs.m_value.boolean < rhs.m_value.boolean; |
6074 } | 15259 |
6075 case value_t::number_integer: | 15260 case value_t::number_integer: |
6076 { | |
6077 return lhs.m_value.number_integer < rhs.m_value.number_integer; | 15261 return lhs.m_value.number_integer < rhs.m_value.number_integer; |
6078 } | 15262 |
6079 case value_t::number_unsigned: | 15263 case value_t::number_unsigned: |
6080 { | |
6081 return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned; | 15264 return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned; |
6082 } | 15265 |
6083 case value_t::number_float: | 15266 case value_t::number_float: |
6084 { | |
6085 return lhs.m_value.number_float < rhs.m_value.number_float; | 15267 return lhs.m_value.number_float < rhs.m_value.number_float; |
6086 } | 15268 |
6087 default: | 15269 default: |
6088 { | |
6089 return false; | 15270 return false; |
6090 } | |
6091 } | 15271 } |
6092 } | 15272 } |
6093 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) | 15273 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) |
6094 { | 15274 { |
6095 return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float; | 15275 return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float; |
6120 // because MSVC has problems otherwise. | 15300 // because MSVC has problems otherwise. |
6121 return operator<(lhs_type, rhs_type); | 15301 return operator<(lhs_type, rhs_type); |
6122 } | 15302 } |
6123 | 15303 |
6124 /*! | 15304 /*! |
15305 @brief comparison: less than | |
15306 @copydoc operator<(const_reference, const_reference) | |
15307 */ | |
15308 template<typename ScalarType, typename std::enable_if< | |
15309 std::is_scalar<ScalarType>::value, int>::type = 0> | |
15310 friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept | |
15311 { | |
15312 return (lhs < basic_json(rhs)); | |
15313 } | |
15314 | |
15315 /*! | |
15316 @brief comparison: less than | |
15317 @copydoc operator<(const_reference, const_reference) | |
15318 */ | |
15319 template<typename ScalarType, typename std::enable_if< | |
15320 std::is_scalar<ScalarType>::value, int>::type = 0> | |
15321 friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept | |
15322 { | |
15323 return (basic_json(lhs) < rhs); | |
15324 } | |
15325 | |
15326 /*! | |
6125 @brief comparison: less than or equal | 15327 @brief comparison: less than or equal |
6126 | 15328 |
6127 Compares whether one JSON value @a lhs is less than or equal to another | 15329 Compares whether one JSON value @a lhs is less than or equal to another |
6128 JSON value by calculating `not (rhs < lhs)`. | 15330 JSON value by calculating `not (rhs < lhs)`. |
6129 | 15331 |
6131 @param[in] rhs second JSON value to consider | 15333 @param[in] rhs second JSON value to consider |
6132 @return whether @a lhs is less than or equal to @a rhs | 15334 @return whether @a lhs is less than or equal to @a rhs |
6133 | 15335 |
6134 @complexity Linear. | 15336 @complexity Linear. |
6135 | 15337 |
15338 @exceptionsafety No-throw guarantee: this function never throws exceptions. | |
15339 | |
6136 @liveexample{The example demonstrates comparing several JSON | 15340 @liveexample{The example demonstrates comparing several JSON |
6137 types.,operator__greater} | 15341 types.,operator__greater} |
6138 | 15342 |
6139 @since version 1.0.0 | 15343 @since version 1.0.0 |
6140 */ | 15344 */ |
6141 friend bool operator<=(const_reference lhs, const_reference rhs) noexcept | 15345 friend bool operator<=(const_reference lhs, const_reference rhs) noexcept |
6142 { | 15346 { |
6143 return not (rhs < lhs); | 15347 return not (rhs < lhs); |
15348 } | |
15349 | |
15350 /*! | |
15351 @brief comparison: less than or equal | |
15352 @copydoc operator<=(const_reference, const_reference) | |
15353 */ | |
15354 template<typename ScalarType, typename std::enable_if< | |
15355 std::is_scalar<ScalarType>::value, int>::type = 0> | |
15356 friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept | |
15357 { | |
15358 return (lhs <= basic_json(rhs)); | |
15359 } | |
15360 | |
15361 /*! | |
15362 @brief comparison: less than or equal | |
15363 @copydoc operator<=(const_reference, const_reference) | |
15364 */ | |
15365 template<typename ScalarType, typename std::enable_if< | |
15366 std::is_scalar<ScalarType>::value, int>::type = 0> | |
15367 friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept | |
15368 { | |
15369 return (basic_json(lhs) <= rhs); | |
6144 } | 15370 } |
6145 | 15371 |
6146 /*! | 15372 /*! |
6147 @brief comparison: greater than | 15373 @brief comparison: greater than |
6148 | 15374 |
6153 @param[in] rhs second JSON value to consider | 15379 @param[in] rhs second JSON value to consider |
6154 @return whether @a lhs is greater than to @a rhs | 15380 @return whether @a lhs is greater than to @a rhs |
6155 | 15381 |
6156 @complexity Linear. | 15382 @complexity Linear. |
6157 | 15383 |
15384 @exceptionsafety No-throw guarantee: this function never throws exceptions. | |
15385 | |
6158 @liveexample{The example demonstrates comparing several JSON | 15386 @liveexample{The example demonstrates comparing several JSON |
6159 types.,operator__lessequal} | 15387 types.,operator__lessequal} |
6160 | 15388 |
6161 @since version 1.0.0 | 15389 @since version 1.0.0 |
6162 */ | 15390 */ |
6163 friend bool operator>(const_reference lhs, const_reference rhs) noexcept | 15391 friend bool operator>(const_reference lhs, const_reference rhs) noexcept |
6164 { | 15392 { |
6165 return not (lhs <= rhs); | 15393 return not (lhs <= rhs); |
15394 } | |
15395 | |
15396 /*! | |
15397 @brief comparison: greater than | |
15398 @copydoc operator>(const_reference, const_reference) | |
15399 */ | |
15400 template<typename ScalarType, typename std::enable_if< | |
15401 std::is_scalar<ScalarType>::value, int>::type = 0> | |
15402 friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept | |
15403 { | |
15404 return (lhs > basic_json(rhs)); | |
15405 } | |
15406 | |
15407 /*! | |
15408 @brief comparison: greater than | |
15409 @copydoc operator>(const_reference, const_reference) | |
15410 */ | |
15411 template<typename ScalarType, typename std::enable_if< | |
15412 std::is_scalar<ScalarType>::value, int>::type = 0> | |
15413 friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept | |
15414 { | |
15415 return (basic_json(lhs) > rhs); | |
6166 } | 15416 } |
6167 | 15417 |
6168 /*! | 15418 /*! |
6169 @brief comparison: greater than or equal | 15419 @brief comparison: greater than or equal |
6170 | 15420 |
6175 @param[in] rhs second JSON value to consider | 15425 @param[in] rhs second JSON value to consider |
6176 @return whether @a lhs is greater than or equal to @a rhs | 15426 @return whether @a lhs is greater than or equal to @a rhs |
6177 | 15427 |
6178 @complexity Linear. | 15428 @complexity Linear. |
6179 | 15429 |
15430 @exceptionsafety No-throw guarantee: this function never throws exceptions. | |
15431 | |
6180 @liveexample{The example demonstrates comparing several JSON | 15432 @liveexample{The example demonstrates comparing several JSON |
6181 types.,operator__greaterequal} | 15433 types.,operator__greaterequal} |
6182 | 15434 |
6183 @since version 1.0.0 | 15435 @since version 1.0.0 |
6184 */ | 15436 */ |
6185 friend bool operator>=(const_reference lhs, const_reference rhs) noexcept | 15437 friend bool operator>=(const_reference lhs, const_reference rhs) noexcept |
6186 { | 15438 { |
6187 return not (lhs < rhs); | 15439 return not (lhs < rhs); |
6188 } | 15440 } |
6189 | 15441 |
15442 /*! | |
15443 @brief comparison: greater than or equal | |
15444 @copydoc operator>=(const_reference, const_reference) | |
15445 */ | |
15446 template<typename ScalarType, typename std::enable_if< | |
15447 std::is_scalar<ScalarType>::value, int>::type = 0> | |
15448 friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept | |
15449 { | |
15450 return (lhs >= basic_json(rhs)); | |
15451 } | |
15452 | |
15453 /*! | |
15454 @brief comparison: greater than or equal | |
15455 @copydoc operator>=(const_reference, const_reference) | |
15456 */ | |
15457 template<typename ScalarType, typename std::enable_if< | |
15458 std::is_scalar<ScalarType>::value, int>::type = 0> | |
15459 friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept | |
15460 { | |
15461 return (basic_json(lhs) >= rhs); | |
15462 } | |
15463 | |
6190 /// @} | 15464 /// @} |
6191 | |
6192 | 15465 |
6193 /////////////////// | 15466 /////////////////// |
6194 // serialization // | 15467 // serialization // |
6195 /////////////////// | 15468 /////////////////// |
6196 | 15469 |
6199 | 15472 |
6200 /*! | 15473 /*! |
6201 @brief serialize to stream | 15474 @brief serialize to stream |
6202 | 15475 |
6203 Serialize the given JSON value @a j to the output stream @a o. The JSON | 15476 Serialize the given JSON value @a j to the output stream @a o. The JSON |
6204 value will be serialized using the @ref dump member function. The | 15477 value will be serialized using the @ref dump member function. |
6205 indentation of the output can be controlled with the member variable | 15478 |
6206 `width` of the output stream @a o. For instance, using the manipulator | 15479 - The indentation of the output can be controlled with the member variable |
6207 `std::setw(4)` on @a o sets the indentation level to `4` and the | 15480 `width` of the output stream @a o. For instance, using the manipulator |
6208 serialization result is the same as calling `dump(4)`. | 15481 `std::setw(4)` on @a o sets the indentation level to `4` and the |
15482 serialization result is the same as calling `dump(4)`. | |
15483 | |
15484 - The indentation character can be controlled with the member variable | |
15485 `fill` of the output stream @a o. For instance, the manipulator | |
15486 `std::setfill('\\t')` sets indentation to use a tab character rather than | |
15487 the default space character. | |
6209 | 15488 |
6210 @param[in,out] o stream to serialize to | 15489 @param[in,out] o stream to serialize to |
6211 @param[in] j JSON value to serialize | 15490 @param[in] j JSON value to serialize |
6212 | 15491 |
6213 @return the stream @a o | 15492 @return the stream @a o |
6214 | 15493 |
15494 @throw type_error.316 if a string stored inside the JSON value is not | |
15495 UTF-8 encoded | |
15496 | |
6215 @complexity Linear. | 15497 @complexity Linear. |
6216 | 15498 |
6217 @liveexample{The example below shows the serialization with different | 15499 @liveexample{The example below shows the serialization with different |
6218 parameters to `width` to adjust the indentation level.,operator_serialize} | 15500 parameters to `width` to adjust the indentation level.,operator_serialize} |
6219 | 15501 |
6220 @since version 1.0.0 | 15502 @since version 1.0.0; indentation character added in version 3.0.0 |
6221 */ | 15503 */ |
6222 friend std::ostream& operator<<(std::ostream& o, const basic_json& j) | 15504 friend std::ostream& operator<<(std::ostream& o, const basic_json& j) |
6223 { | 15505 { |
6224 // read width member and use it as indentation parameter if nonzero | 15506 // read width member and use it as indentation parameter if nonzero |
6225 const bool pretty_print = (o.width() > 0); | 15507 const bool pretty_print = (o.width() > 0); |
6227 | 15509 |
6228 // reset width to 0 for subsequent calls to this stream | 15510 // reset width to 0 for subsequent calls to this stream |
6229 o.width(0); | 15511 o.width(0); |
6230 | 15512 |
6231 // do the actual serialization | 15513 // do the actual serialization |
6232 j.dump(o, pretty_print, static_cast<unsigned int>(indentation)); | 15514 serializer s(detail::output_adapter<char>(o), o.fill()); |
6233 | 15515 s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation)); |
6234 return o; | 15516 return o; |
6235 } | 15517 } |
6236 | 15518 |
6237 /*! | 15519 /*! |
6238 @brief serialize to stream | 15520 @brief serialize to stream |
6239 @copydoc operator<<(std::ostream&, const basic_json&) | 15521 @deprecated This stream operator is deprecated and will be removed in |
6240 */ | 15522 future 4.0.0 of the library. Please use |
15523 @ref operator<<(std::ostream&, const basic_json&) | |
15524 instead; that is, replace calls like `j >> o;` with `o << j;`. | |
15525 @since version 1.0.0; deprecated since version 3.0.0 | |
15526 */ | |
15527 JSON_DEPRECATED | |
6241 friend std::ostream& operator>>(const basic_json& j, std::ostream& o) | 15528 friend std::ostream& operator>>(const basic_json& j, std::ostream& o) |
6242 { | 15529 { |
6243 return o << j; | 15530 return o << j; |
6244 } | 15531 } |
6245 | 15532 |
6252 | 15539 |
6253 /// @name deserialization | 15540 /// @name deserialization |
6254 /// @{ | 15541 /// @{ |
6255 | 15542 |
6256 /*! | 15543 /*! |
6257 @brief deserialize from an array | 15544 @brief deserialize from a compatible input |
6258 | 15545 |
6259 This function reads from an array of 1-byte values. | 15546 This function reads from a compatible input. Examples are: |
15547 - an array of 1-byte values | |
15548 - strings with character/literal type with size of 1 byte | |
15549 - input streams | |
15550 - container with contiguous storage of 1-byte values. Compatible container | |
15551 types include `std::vector`, `std::string`, `std::array`, | |
15552 `std::valarray`, and `std::initializer_list`. Furthermore, C-style | |
15553 arrays can be used with `std::begin()`/`std::end()`. User-defined | |
15554 containers can be used as long as they implement random-access iterators | |
15555 and a contiguous storage. | |
6260 | 15556 |
6261 @pre Each element of the container has a size of 1 byte. Violating this | 15557 @pre Each element of the container has a size of 1 byte. Violating this |
6262 precondition yields undefined behavior. **This precondition is enforced | 15558 precondition yields undefined behavior. **This precondition is enforced |
6263 with a static assertion.** | 15559 with a static assertion.** |
6264 | 15560 |
6265 @param[in] array array to read from | 15561 @pre The container storage is contiguous. Violating this precondition |
15562 yields undefined behavior. **This precondition is enforced with an | |
15563 assertion.** | |
15564 @pre Each element of the container has a size of 1 byte. Violating this | |
15565 precondition yields undefined behavior. **This precondition is enforced | |
15566 with a static assertion.** | |
15567 | |
15568 @warning There is no way to enforce all preconditions at compile-time. If | |
15569 the function is called with a noncompliant container and with | |
15570 assertions switched off, the behavior is undefined and will most | |
15571 likely yield segmentation violation. | |
15572 | |
15573 @param[in] i input to read from | |
6266 @param[in] cb a parser callback function of type @ref parser_callback_t | 15574 @param[in] cb a parser callback function of type @ref parser_callback_t |
6267 which is used to control the deserialization by filtering unwanted values | 15575 which is used to control the deserialization by filtering unwanted values |
6268 (optional) | 15576 (optional) |
6269 | 15577 |
6270 @return result of the deserialization | 15578 @return result of the deserialization |
6271 | 15579 |
15580 @throw parse_error.101 if a parse error occurs; example: `""unexpected end | |
15581 of input; expected string literal""` | |
15582 @throw parse_error.102 if to_unicode fails or surrogate error | |
15583 @throw parse_error.103 if to_unicode fails | |
15584 | |
6272 @complexity Linear in the length of the input. The parser is a predictive | 15585 @complexity Linear in the length of the input. The parser is a predictive |
6273 LL(1) parser. The complexity can be higher if the parser callback function | 15586 LL(1) parser. The complexity can be higher if the parser callback function |
6274 @a cb has a super-linear complexity. | 15587 @a cb has a super-linear complexity. |
6275 | 15588 |
6276 @note A UTF-8 byte order mark is silently ignored. | 15589 @note A UTF-8 byte order mark is silently ignored. |
6277 | 15590 |
6278 @liveexample{The example below demonstrates the `parse()` function reading | 15591 @liveexample{The example below demonstrates the `parse()` function reading |
6279 from an array.,parse__array__parser_callback_t} | 15592 from an array.,parse__array__parser_callback_t} |
6280 | 15593 |
6281 @since version 2.0.3 | |
6282 */ | |
6283 template<class T, std::size_t N> | |
6284 static basic_json parse(T (&array)[N], | |
6285 const parser_callback_t cb = nullptr) | |
6286 { | |
6287 // delegate the call to the iterator-range parse overload | |
6288 return parse(std::begin(array), std::end(array), cb); | |
6289 } | |
6290 | |
6291 /*! | |
6292 @brief deserialize from string literal | |
6293 | |
6294 @tparam CharT character/literal type with size of 1 byte | |
6295 @param[in] s string literal to read a serialized JSON value from | |
6296 @param[in] cb a parser callback function of type @ref parser_callback_t | |
6297 which is used to control the deserialization by filtering unwanted values | |
6298 (optional) | |
6299 | |
6300 @return result of the deserialization | |
6301 | |
6302 @complexity Linear in the length of the input. The parser is a predictive | |
6303 LL(1) parser. The complexity can be higher if the parser callback function | |
6304 @a cb has a super-linear complexity. | |
6305 | |
6306 @note A UTF-8 byte order mark is silently ignored. | |
6307 @note String containers like `std::string` or @ref string_t can be parsed | |
6308 with @ref parse(const ContiguousContainer&, const parser_callback_t) | |
6309 | |
6310 @liveexample{The example below demonstrates the `parse()` function with | 15594 @liveexample{The example below demonstrates the `parse()` function with |
6311 and without callback function.,parse__string__parser_callback_t} | 15595 and without callback function.,parse__string__parser_callback_t} |
6312 | 15596 |
6313 @sa @ref parse(std::istream&, const parser_callback_t) for a version that | |
6314 reads from an input stream | |
6315 | |
6316 @since version 1.0.0 (originally for @ref string_t) | |
6317 */ | |
6318 template<typename CharT, typename std::enable_if< | |
6319 std::is_pointer<CharT>::value and | |
6320 std::is_integral<typename std::remove_pointer<CharT>::type>::value and | |
6321 sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0> | |
6322 static basic_json parse(const CharT s, | |
6323 const parser_callback_t cb = nullptr) | |
6324 { | |
6325 return parser(reinterpret_cast<const char*>(s), cb).parse(); | |
6326 } | |
6327 | |
6328 /*! | |
6329 @brief deserialize from stream | |
6330 | |
6331 @param[in,out] i stream to read a serialized JSON value from | |
6332 @param[in] cb a parser callback function of type @ref parser_callback_t | |
6333 which is used to control the deserialization by filtering unwanted values | |
6334 (optional) | |
6335 | |
6336 @return result of the deserialization | |
6337 | |
6338 @complexity Linear in the length of the input. The parser is a predictive | |
6339 LL(1) parser. The complexity can be higher if the parser callback function | |
6340 @a cb has a super-linear complexity. | |
6341 | |
6342 @note A UTF-8 byte order mark is silently ignored. | |
6343 | |
6344 @liveexample{The example below demonstrates the `parse()` function with | 15597 @liveexample{The example below demonstrates the `parse()` function with |
6345 and without callback function.,parse__istream__parser_callback_t} | 15598 and without callback function.,parse__istream__parser_callback_t} |
6346 | 15599 |
6347 @sa @ref parse(const CharT, const parser_callback_t) for a version | 15600 @liveexample{The example below demonstrates the `parse()` function reading |
6348 that reads from a string | 15601 from a contiguous container.,parse__contiguouscontainer__parser_callback_t} |
6349 | 15602 |
6350 @since version 1.0.0 | 15603 @since version 2.0.3 (contiguous containers) |
6351 */ | 15604 */ |
6352 static basic_json parse(std::istream& i, | 15605 static basic_json parse(detail::input_adapter i, |
6353 const parser_callback_t cb = nullptr) | 15606 const parser_callback_t cb = nullptr, |
6354 { | 15607 const bool allow_exceptions = true) |
6355 return parser(i, cb).parse(); | 15608 { |
6356 } | 15609 basic_json result; |
6357 | 15610 parser(i, cb, allow_exceptions).parse(true, result); |
6358 /*! | 15611 return result; |
6359 @copydoc parse(std::istream&, const parser_callback_t) | 15612 } |
6360 */ | 15613 |
6361 static basic_json parse(std::istream&& i, | 15614 /*! |
6362 const parser_callback_t cb = nullptr) | 15615 @copydoc basic_json parse(detail::input_adapter, const parser_callback_t) |
6363 { | 15616 */ |
6364 return parser(i, cb).parse(); | 15617 static basic_json parse(detail::input_adapter& i, |
15618 const parser_callback_t cb = nullptr, | |
15619 const bool allow_exceptions = true) | |
15620 { | |
15621 basic_json result; | |
15622 parser(i, cb, allow_exceptions).parse(true, result); | |
15623 return result; | |
15624 } | |
15625 | |
15626 static bool accept(detail::input_adapter i) | |
15627 { | |
15628 return parser(i).accept(true); | |
15629 } | |
15630 | |
15631 static bool accept(detail::input_adapter& i) | |
15632 { | |
15633 return parser(i).accept(true); | |
6365 } | 15634 } |
6366 | 15635 |
6367 /*! | 15636 /*! |
6368 @brief deserialize from an iterator range with contiguous storage | 15637 @brief deserialize from an iterator range with contiguous storage |
6369 | 15638 |
6389 @param[in] first begin of the range to parse (included) | 15658 @param[in] first begin of the range to parse (included) |
6390 @param[in] last end of the range to parse (excluded) | 15659 @param[in] last end of the range to parse (excluded) |
6391 @param[in] cb a parser callback function of type @ref parser_callback_t | 15660 @param[in] cb a parser callback function of type @ref parser_callback_t |
6392 which is used to control the deserialization by filtering unwanted values | 15661 which is used to control the deserialization by filtering unwanted values |
6393 (optional) | 15662 (optional) |
15663 @param[in] allow_exceptions whether to throw exceptions in case of a | |
15664 parse error (optional, true by default) | |
6394 | 15665 |
6395 @return result of the deserialization | 15666 @return result of the deserialization |
15667 | |
15668 @throw parse_error.101 in case of an unexpected token | |
15669 @throw parse_error.102 if to_unicode fails or surrogate error | |
15670 @throw parse_error.103 if to_unicode fails | |
6396 | 15671 |
6397 @complexity Linear in the length of the input. The parser is a predictive | 15672 @complexity Linear in the length of the input. The parser is a predictive |
6398 LL(1) parser. The complexity can be higher if the parser callback function | 15673 LL(1) parser. The complexity can be higher if the parser callback function |
6399 @a cb has a super-linear complexity. | 15674 @a cb has a super-linear complexity. |
6400 | 15675 |
6408 template<class IteratorType, typename std::enable_if< | 15683 template<class IteratorType, typename std::enable_if< |
6409 std::is_base_of< | 15684 std::is_base_of< |
6410 std::random_access_iterator_tag, | 15685 std::random_access_iterator_tag, |
6411 typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0> | 15686 typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0> |
6412 static basic_json parse(IteratorType first, IteratorType last, | 15687 static basic_json parse(IteratorType first, IteratorType last, |
6413 const parser_callback_t cb = nullptr) | 15688 const parser_callback_t cb = nullptr, |
6414 { | 15689 const bool allow_exceptions = true) |
6415 // assertion to check that the iterator range is indeed contiguous, | 15690 { |
6416 // see http://stackoverflow.com/a/35008842/266378 for more discussion | 15691 basic_json result; |
6417 assert(std::accumulate(first, last, std::pair<bool, int>(true, 0), | 15692 parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result); |
6418 [&first](std::pair<bool, int> res, decltype(*first) val) | 15693 return result; |
6419 { | 15694 } |
6420 res.first &= (val == *(std::next(std::addressof(*first), res.second++))); | 15695 |
6421 return res; | 15696 template<class IteratorType, typename std::enable_if< |
6422 }).first); | |
6423 | |
6424 // assertion to check that each element is 1 byte long | |
6425 static_assert(sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1, | |
6426 "each element in the iterator range must have the size of 1 byte"); | |
6427 | |
6428 // if iterator range is empty, create a parser with an empty string | |
6429 // to generate "unexpected EOF" error message | |
6430 if (std::distance(first, last) <= 0) | |
6431 { | |
6432 return parser("").parse(); | |
6433 } | |
6434 | |
6435 return parser(first, last, cb).parse(); | |
6436 } | |
6437 | |
6438 /*! | |
6439 @brief deserialize from a container with contiguous storage | |
6440 | |
6441 This function reads from a container with contiguous storage of 1-byte | |
6442 values. Compatible container types include `std::vector`, `std::string`, | |
6443 `std::array`, and `std::initializer_list`. User-defined containers can be | |
6444 used as long as they implement random-access iterators and a contiguous | |
6445 storage. | |
6446 | |
6447 @pre The container storage is contiguous. Violating this precondition | |
6448 yields undefined behavior. **This precondition is enforced with an | |
6449 assertion.** | |
6450 @pre Each element of the container has a size of 1 byte. Violating this | |
6451 precondition yields undefined behavior. **This precondition is enforced | |
6452 with a static assertion.** | |
6453 | |
6454 @warning There is no way to enforce all preconditions at compile-time. If | |
6455 the function is called with a noncompliant container and with | |
6456 assertions switched off, the behavior is undefined and will most | |
6457 likely yield segmentation violation. | |
6458 | |
6459 @tparam ContiguousContainer container type with contiguous storage | |
6460 @param[in] c container to read from | |
6461 @param[in] cb a parser callback function of type @ref parser_callback_t | |
6462 which is used to control the deserialization by filtering unwanted values | |
6463 (optional) | |
6464 | |
6465 @return result of the deserialization | |
6466 | |
6467 @complexity Linear in the length of the input. The parser is a predictive | |
6468 LL(1) parser. The complexity can be higher if the parser callback function | |
6469 @a cb has a super-linear complexity. | |
6470 | |
6471 @note A UTF-8 byte order mark is silently ignored. | |
6472 | |
6473 @liveexample{The example below demonstrates the `parse()` function reading | |
6474 from a contiguous container.,parse__contiguouscontainer__parser_callback_t} | |
6475 | |
6476 @since version 2.0.3 | |
6477 */ | |
6478 template<class ContiguousContainer, typename std::enable_if< | |
6479 not std::is_pointer<ContiguousContainer>::value and | |
6480 std::is_base_of< | 15697 std::is_base_of< |
6481 std::random_access_iterator_tag, | 15698 std::random_access_iterator_tag, |
6482 typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value | 15699 typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0> |
6483 , int>::type = 0> | 15700 static bool accept(IteratorType first, IteratorType last) |
6484 static basic_json parse(const ContiguousContainer& c, | 15701 { |
6485 const parser_callback_t cb = nullptr) | 15702 return parser(detail::input_adapter(first, last)).accept(true); |
6486 { | 15703 } |
6487 // delegate the call to the iterator-range parse overload | 15704 |
6488 return parse(std::begin(c), std::end(c), cb); | 15705 /*! |
15706 @brief deserialize from stream | |
15707 @deprecated This stream operator is deprecated and will be removed in | |
15708 version 4.0.0 of the library. Please use | |
15709 @ref operator>>(std::istream&, basic_json&) | |
15710 instead; that is, replace calls like `j << i;` with `i >> j;`. | |
15711 @since version 1.0.0; deprecated since version 3.0.0 | |
15712 */ | |
15713 JSON_DEPRECATED | |
15714 friend std::istream& operator<<(basic_json& j, std::istream& i) | |
15715 { | |
15716 return operator>>(i, j); | |
6489 } | 15717 } |
6490 | 15718 |
6491 /*! | 15719 /*! |
6492 @brief deserialize from stream | 15720 @brief deserialize from stream |
6493 | 15721 |
6494 Deserializes an input stream to a JSON value. | 15722 Deserializes an input stream to a JSON value. |
6495 | 15723 |
6496 @param[in,out] i input stream to read a serialized JSON value from | 15724 @param[in,out] i input stream to read a serialized JSON value from |
6497 @param[in,out] j JSON value to write the deserialized input to | 15725 @param[in,out] j JSON value to write the deserialized input to |
6498 | 15726 |
6499 @throw std::invalid_argument in case of parse errors | 15727 @throw parse_error.101 in case of an unexpected token |
15728 @throw parse_error.102 if to_unicode fails or surrogate error | |
15729 @throw parse_error.103 if to_unicode fails | |
6500 | 15730 |
6501 @complexity Linear in the length of the input. The parser is a predictive | 15731 @complexity Linear in the length of the input. The parser is a predictive |
6502 LL(1) parser. | 15732 LL(1) parser. |
6503 | 15733 |
6504 @note A UTF-8 byte order mark is silently ignored. | 15734 @note A UTF-8 byte order mark is silently ignored. |
6509 @sa parse(std::istream&, const parser_callback_t) for a variant with a | 15739 @sa parse(std::istream&, const parser_callback_t) for a variant with a |
6510 parser callback function to filter values while parsing | 15740 parser callback function to filter values while parsing |
6511 | 15741 |
6512 @since version 1.0.0 | 15742 @since version 1.0.0 |
6513 */ | 15743 */ |
6514 friend std::istream& operator<<(basic_json& j, std::istream& i) | 15744 friend std::istream& operator>>(std::istream& i, basic_json& j) |
6515 { | 15745 { |
6516 j = parser(i).parse(); | 15746 parser(detail::input_adapter(i)).parse(false, j); |
6517 return i; | 15747 return i; |
6518 } | |
6519 | |
6520 /*! | |
6521 @brief deserialize from stream | |
6522 @copydoc operator<<(basic_json&, std::istream&) | |
6523 */ | |
6524 friend std::istream& operator>>(std::istream& i, basic_json& j) | |
6525 { | |
6526 j = parser(i).parse(); | |
6527 return i; | |
6528 } | |
6529 | |
6530 /// @} | |
6531 | |
6532 ////////////////////////////////////////// | |
6533 // binary serialization/deserialization // | |
6534 ////////////////////////////////////////// | |
6535 | |
6536 /// @name binary serialization/deserialization support | |
6537 /// @{ | |
6538 | |
6539 private: | |
6540 /*! | |
6541 @note Some code in the switch cases has been copied, because otherwise | |
6542 copilers would complain about implicit fallthrough and there is no | |
6543 portable attribute to mute such warnings. | |
6544 */ | |
6545 template<typename T> | |
6546 static void add_to_vector(std::vector<uint8_t>& vec, size_t bytes, const T number) | |
6547 { | |
6548 assert(bytes == 1 or bytes == 2 or bytes == 4 or bytes == 8); | |
6549 | |
6550 switch (bytes) | |
6551 { | |
6552 case 8: | |
6553 { | |
6554 vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 070) & 0xff)); | |
6555 vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 060) & 0xff)); | |
6556 vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 050) & 0xff)); | |
6557 vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 040) & 0xff)); | |
6558 vec.push_back(static_cast<uint8_t>((number >> 030) & 0xff)); | |
6559 vec.push_back(static_cast<uint8_t>((number >> 020) & 0xff)); | |
6560 vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff)); | |
6561 vec.push_back(static_cast<uint8_t>(number & 0xff)); | |
6562 break; | |
6563 } | |
6564 | |
6565 case 4: | |
6566 { | |
6567 vec.push_back(static_cast<uint8_t>((number >> 030) & 0xff)); | |
6568 vec.push_back(static_cast<uint8_t>((number >> 020) & 0xff)); | |
6569 vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff)); | |
6570 vec.push_back(static_cast<uint8_t>(number & 0xff)); | |
6571 break; | |
6572 } | |
6573 | |
6574 case 2: | |
6575 { | |
6576 vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff)); | |
6577 vec.push_back(static_cast<uint8_t>(number & 0xff)); | |
6578 break; | |
6579 } | |
6580 | |
6581 case 1: | |
6582 { | |
6583 vec.push_back(static_cast<uint8_t>(number & 0xff)); | |
6584 break; | |
6585 } | |
6586 } | |
6587 } | |
6588 | |
6589 /*! | |
6590 @brief take sufficient bytes from a vector to fill an integer variable | |
6591 | |
6592 In the context of binary serialization formats, we need to read several | |
6593 bytes from a byte vector and combine them to multi-byte integral data | |
6594 types. | |
6595 | |
6596 @param[in] vec byte vector to read from | |
6597 @param[in] current_index the position in the vector after which to read | |
6598 | |
6599 @return the next sizeof(T) bytes from @a vec, in reverse order as T | |
6600 | |
6601 @tparam T the integral return type | |
6602 | |
6603 @throw std::out_of_range if there are less than sizeof(T)+1 bytes in the | |
6604 vector @a vec to read | |
6605 | |
6606 In the for loop, the bytes from the vector are copied in reverse order into | |
6607 the return value. In the figures below, let sizeof(T)=4 and `i` be the loop | |
6608 variable. | |
6609 | |
6610 Precondition: | |
6611 | |
6612 vec: | | | a | b | c | d | T: | | | | | | |
6613 ^ ^ ^ ^ | |
6614 current_index i ptr sizeof(T) | |
6615 | |
6616 Postcondition: | |
6617 | |
6618 vec: | | | a | b | c | d | T: | d | c | b | a | | |
6619 ^ ^ ^ | |
6620 | i ptr | |
6621 current_index | |
6622 | |
6623 @sa Code adapted from <http://stackoverflow.com/a/41031865/266378>. | |
6624 */ | |
6625 template<typename T> | |
6626 static T get_from_vector(const std::vector<uint8_t>& vec, const size_t current_index) | |
6627 { | |
6628 if (current_index + sizeof(T) + 1 > vec.size()) | |
6629 { | |
6630 JSON_THROW(std::out_of_range("cannot read " + std::to_string(sizeof(T)) + " bytes from vector")); | |
6631 } | |
6632 | |
6633 T result; | |
6634 auto* ptr = reinterpret_cast<uint8_t*>(&result); | |
6635 for (size_t i = 0; i < sizeof(T); ++i) | |
6636 { | |
6637 *ptr++ = vec[current_index + sizeof(T) - i]; | |
6638 } | |
6639 return result; | |
6640 } | |
6641 | |
6642 /*! | |
6643 @brief create a MessagePack serialization of a given JSON value | |
6644 | |
6645 This is a straightforward implementation of the MessagePack specification. | |
6646 | |
6647 @param[in] j JSON value to serialize | |
6648 @param[in,out] v byte vector to write the serialization to | |
6649 | |
6650 @sa https://github.com/msgpack/msgpack/blob/master/spec.md | |
6651 */ | |
6652 static void to_msgpack_internal(const basic_json& j, std::vector<uint8_t>& v) | |
6653 { | |
6654 switch (j.type()) | |
6655 { | |
6656 case value_t::null: | |
6657 { | |
6658 // nil | |
6659 v.push_back(0xc0); | |
6660 break; | |
6661 } | |
6662 | |
6663 case value_t::boolean: | |
6664 { | |
6665 // true and false | |
6666 v.push_back(j.m_value.boolean ? 0xc3 : 0xc2); | |
6667 break; | |
6668 } | |
6669 | |
6670 case value_t::number_integer: | |
6671 { | |
6672 if (j.m_value.number_integer >= 0) | |
6673 { | |
6674 // MessagePack does not differentiate between positive | |
6675 // signed integers and unsigned integers. Therefore, we | |
6676 // used the code from the value_t::number_unsigned case | |
6677 // here. | |
6678 if (j.m_value.number_unsigned < 128) | |
6679 { | |
6680 // positive fixnum | |
6681 add_to_vector(v, 1, j.m_value.number_unsigned); | |
6682 } | |
6683 else if (j.m_value.number_unsigned <= std::numeric_limits<uint8_t>::max()) | |
6684 { | |
6685 // uint 8 | |
6686 v.push_back(0xcc); | |
6687 add_to_vector(v, 1, j.m_value.number_unsigned); | |
6688 } | |
6689 else if (j.m_value.number_unsigned <= std::numeric_limits<uint16_t>::max()) | |
6690 { | |
6691 // uint 16 | |
6692 v.push_back(0xcd); | |
6693 add_to_vector(v, 2, j.m_value.number_unsigned); | |
6694 } | |
6695 else if (j.m_value.number_unsigned <= std::numeric_limits<uint32_t>::max()) | |
6696 { | |
6697 // uint 32 | |
6698 v.push_back(0xce); | |
6699 add_to_vector(v, 4, j.m_value.number_unsigned); | |
6700 } | |
6701 else if (j.m_value.number_unsigned <= std::numeric_limits<uint64_t>::max()) | |
6702 { | |
6703 // uint 64 | |
6704 v.push_back(0xcf); | |
6705 add_to_vector(v, 8, j.m_value.number_unsigned); | |
6706 } | |
6707 } | |
6708 else | |
6709 { | |
6710 if (j.m_value.number_integer >= -32) | |
6711 { | |
6712 // negative fixnum | |
6713 add_to_vector(v, 1, j.m_value.number_integer); | |
6714 } | |
6715 else if (j.m_value.number_integer >= std::numeric_limits<int8_t>::min() and j.m_value.number_integer <= std::numeric_limits<int8_t>::max()) | |
6716 { | |
6717 // int 8 | |
6718 v.push_back(0xd0); | |
6719 add_to_vector(v, 1, j.m_value.number_integer); | |
6720 } | |
6721 else if (j.m_value.number_integer >= std::numeric_limits<int16_t>::min() and j.m_value.number_integer <= std::numeric_limits<int16_t>::max()) | |
6722 { | |
6723 // int 16 | |
6724 v.push_back(0xd1); | |
6725 add_to_vector(v, 2, j.m_value.number_integer); | |
6726 } | |
6727 else if (j.m_value.number_integer >= std::numeric_limits<int32_t>::min() and j.m_value.number_integer <= std::numeric_limits<int32_t>::max()) | |
6728 { | |
6729 // int 32 | |
6730 v.push_back(0xd2); | |
6731 add_to_vector(v, 4, j.m_value.number_integer); | |
6732 } | |
6733 else if (j.m_value.number_integer >= std::numeric_limits<int64_t>::min() and j.m_value.number_integer <= std::numeric_limits<int64_t>::max()) | |
6734 { | |
6735 // int 64 | |
6736 v.push_back(0xd3); | |
6737 add_to_vector(v, 8, j.m_value.number_integer); | |
6738 } | |
6739 } | |
6740 break; | |
6741 } | |
6742 | |
6743 case value_t::number_unsigned: | |
6744 { | |
6745 if (j.m_value.number_unsigned < 128) | |
6746 { | |
6747 // positive fixnum | |
6748 add_to_vector(v, 1, j.m_value.number_unsigned); | |
6749 } | |
6750 else if (j.m_value.number_unsigned <= std::numeric_limits<uint8_t>::max()) | |
6751 { | |
6752 // uint 8 | |
6753 v.push_back(0xcc); | |
6754 add_to_vector(v, 1, j.m_value.number_unsigned); | |
6755 } | |
6756 else if (j.m_value.number_unsigned <= std::numeric_limits<uint16_t>::max()) | |
6757 { | |
6758 // uint 16 | |
6759 v.push_back(0xcd); | |
6760 add_to_vector(v, 2, j.m_value.number_unsigned); | |
6761 } | |
6762 else if (j.m_value.number_unsigned <= std::numeric_limits<uint32_t>::max()) | |
6763 { | |
6764 // uint 32 | |
6765 v.push_back(0xce); | |
6766 add_to_vector(v, 4, j.m_value.number_unsigned); | |
6767 } | |
6768 else if (j.m_value.number_unsigned <= std::numeric_limits<uint64_t>::max()) | |
6769 { | |
6770 // uint 64 | |
6771 v.push_back(0xcf); | |
6772 add_to_vector(v, 8, j.m_value.number_unsigned); | |
6773 } | |
6774 break; | |
6775 } | |
6776 | |
6777 case value_t::number_float: | |
6778 { | |
6779 // float 64 | |
6780 v.push_back(0xcb); | |
6781 const auto* helper = reinterpret_cast<const uint8_t*>(&(j.m_value.number_float)); | |
6782 for (size_t i = 0; i < 8; ++i) | |
6783 { | |
6784 v.push_back(helper[7 - i]); | |
6785 } | |
6786 break; | |
6787 } | |
6788 | |
6789 case value_t::string: | |
6790 { | |
6791 const auto N = j.m_value.string->size(); | |
6792 if (N <= 31) | |
6793 { | |
6794 // fixstr | |
6795 v.push_back(static_cast<uint8_t>(0xa0 | N)); | |
6796 } | |
6797 else if (N <= 255) | |
6798 { | |
6799 // str 8 | |
6800 v.push_back(0xd9); | |
6801 add_to_vector(v, 1, N); | |
6802 } | |
6803 else if (N <= 65535) | |
6804 { | |
6805 // str 16 | |
6806 v.push_back(0xda); | |
6807 add_to_vector(v, 2, N); | |
6808 } | |
6809 else if (N <= 4294967295) | |
6810 { | |
6811 // str 32 | |
6812 v.push_back(0xdb); | |
6813 add_to_vector(v, 4, N); | |
6814 } | |
6815 | |
6816 // append string | |
6817 std::copy(j.m_value.string->begin(), j.m_value.string->end(), | |
6818 std::back_inserter(v)); | |
6819 break; | |
6820 } | |
6821 | |
6822 case value_t::array: | |
6823 { | |
6824 const auto N = j.m_value.array->size(); | |
6825 if (N <= 15) | |
6826 { | |
6827 // fixarray | |
6828 v.push_back(static_cast<uint8_t>(0x90 | N)); | |
6829 } | |
6830 else if (N <= 0xffff) | |
6831 { | |
6832 // array 16 | |
6833 v.push_back(0xdc); | |
6834 add_to_vector(v, 2, N); | |
6835 } | |
6836 else if (N <= 0xffffffff) | |
6837 { | |
6838 // array 32 | |
6839 v.push_back(0xdd); | |
6840 add_to_vector(v, 4, N); | |
6841 } | |
6842 | |
6843 // append each element | |
6844 for (const auto& el : *j.m_value.array) | |
6845 { | |
6846 to_msgpack_internal(el, v); | |
6847 } | |
6848 break; | |
6849 } | |
6850 | |
6851 case value_t::object: | |
6852 { | |
6853 const auto N = j.m_value.object->size(); | |
6854 if (N <= 15) | |
6855 { | |
6856 // fixmap | |
6857 v.push_back(static_cast<uint8_t>(0x80 | (N & 0xf))); | |
6858 } | |
6859 else if (N <= 65535) | |
6860 { | |
6861 // map 16 | |
6862 v.push_back(0xde); | |
6863 add_to_vector(v, 2, N); | |
6864 } | |
6865 else if (N <= 4294967295) | |
6866 { | |
6867 // map 32 | |
6868 v.push_back(0xdf); | |
6869 add_to_vector(v, 4, N); | |
6870 } | |
6871 | |
6872 // append each element | |
6873 for (const auto& el : *j.m_value.object) | |
6874 { | |
6875 to_msgpack_internal(el.first, v); | |
6876 to_msgpack_internal(el.second, v); | |
6877 } | |
6878 break; | |
6879 } | |
6880 | |
6881 default: | |
6882 { | |
6883 break; | |
6884 } | |
6885 } | |
6886 } | |
6887 | |
6888 /*! | |
6889 @brief create a CBOR serialization of a given JSON value | |
6890 | |
6891 This is a straightforward implementation of the CBOR specification. | |
6892 | |
6893 @param[in] j JSON value to serialize | |
6894 @param[in,out] v byte vector to write the serialization to | |
6895 | |
6896 @sa https://tools.ietf.org/html/rfc7049 | |
6897 */ | |
6898 static void to_cbor_internal(const basic_json& j, std::vector<uint8_t>& v) | |
6899 { | |
6900 switch (j.type()) | |
6901 { | |
6902 case value_t::null: | |
6903 { | |
6904 v.push_back(0xf6); | |
6905 break; | |
6906 } | |
6907 | |
6908 case value_t::boolean: | |
6909 { | |
6910 v.push_back(j.m_value.boolean ? 0xf5 : 0xf4); | |
6911 break; | |
6912 } | |
6913 | |
6914 case value_t::number_integer: | |
6915 { | |
6916 if (j.m_value.number_integer >= 0) | |
6917 { | |
6918 // CBOR does not differentiate between positive signed | |
6919 // integers and unsigned integers. Therefore, we used the | |
6920 // code from the value_t::number_unsigned case here. | |
6921 if (j.m_value.number_integer <= 0x17) | |
6922 { | |
6923 add_to_vector(v, 1, j.m_value.number_integer); | |
6924 } | |
6925 else if (j.m_value.number_integer <= std::numeric_limits<uint8_t>::max()) | |
6926 { | |
6927 v.push_back(0x18); | |
6928 // one-byte uint8_t | |
6929 add_to_vector(v, 1, j.m_value.number_integer); | |
6930 } | |
6931 else if (j.m_value.number_integer <= std::numeric_limits<uint16_t>::max()) | |
6932 { | |
6933 v.push_back(0x19); | |
6934 // two-byte uint16_t | |
6935 add_to_vector(v, 2, j.m_value.number_integer); | |
6936 } | |
6937 else if (j.m_value.number_integer <= std::numeric_limits<uint32_t>::max()) | |
6938 { | |
6939 v.push_back(0x1a); | |
6940 // four-byte uint32_t | |
6941 add_to_vector(v, 4, j.m_value.number_integer); | |
6942 } | |
6943 else | |
6944 { | |
6945 v.push_back(0x1b); | |
6946 // eight-byte uint64_t | |
6947 add_to_vector(v, 8, j.m_value.number_integer); | |
6948 } | |
6949 } | |
6950 else | |
6951 { | |
6952 // The conversions below encode the sign in the first | |
6953 // byte, and the value is converted to a positive number. | |
6954 const auto positive_number = -1 - j.m_value.number_integer; | |
6955 if (j.m_value.number_integer >= -24) | |
6956 { | |
6957 v.push_back(static_cast<uint8_t>(0x20 + positive_number)); | |
6958 } | |
6959 else if (positive_number <= std::numeric_limits<uint8_t>::max()) | |
6960 { | |
6961 // int 8 | |
6962 v.push_back(0x38); | |
6963 add_to_vector(v, 1, positive_number); | |
6964 } | |
6965 else if (positive_number <= std::numeric_limits<uint16_t>::max()) | |
6966 { | |
6967 // int 16 | |
6968 v.push_back(0x39); | |
6969 add_to_vector(v, 2, positive_number); | |
6970 } | |
6971 else if (positive_number <= std::numeric_limits<uint32_t>::max()) | |
6972 { | |
6973 // int 32 | |
6974 v.push_back(0x3a); | |
6975 add_to_vector(v, 4, positive_number); | |
6976 } | |
6977 else | |
6978 { | |
6979 // int 64 | |
6980 v.push_back(0x3b); | |
6981 add_to_vector(v, 8, positive_number); | |
6982 } | |
6983 } | |
6984 break; | |
6985 } | |
6986 | |
6987 case value_t::number_unsigned: | |
6988 { | |
6989 if (j.m_value.number_unsigned <= 0x17) | |
6990 { | |
6991 v.push_back(static_cast<uint8_t>(j.m_value.number_unsigned)); | |
6992 } | |
6993 else if (j.m_value.number_unsigned <= 0xff) | |
6994 { | |
6995 v.push_back(0x18); | |
6996 // one-byte uint8_t | |
6997 add_to_vector(v, 1, j.m_value.number_unsigned); | |
6998 } | |
6999 else if (j.m_value.number_unsigned <= 0xffff) | |
7000 { | |
7001 v.push_back(0x19); | |
7002 // two-byte uint16_t | |
7003 add_to_vector(v, 2, j.m_value.number_unsigned); | |
7004 } | |
7005 else if (j.m_value.number_unsigned <= 0xffffffff) | |
7006 { | |
7007 v.push_back(0x1a); | |
7008 // four-byte uint32_t | |
7009 add_to_vector(v, 4, j.m_value.number_unsigned); | |
7010 } | |
7011 else if (j.m_value.number_unsigned <= 0xffffffffffffffff) | |
7012 { | |
7013 v.push_back(0x1b); | |
7014 // eight-byte uint64_t | |
7015 add_to_vector(v, 8, j.m_value.number_unsigned); | |
7016 } | |
7017 break; | |
7018 } | |
7019 | |
7020 case value_t::number_float: | |
7021 { | |
7022 // Double-Precision Float | |
7023 v.push_back(0xfb); | |
7024 const auto* helper = reinterpret_cast<const uint8_t*>(&(j.m_value.number_float)); | |
7025 for (size_t i = 0; i < 8; ++i) | |
7026 { | |
7027 v.push_back(helper[7 - i]); | |
7028 } | |
7029 break; | |
7030 } | |
7031 | |
7032 case value_t::string: | |
7033 { | |
7034 const auto N = j.m_value.string->size(); | |
7035 if (N <= 0x17) | |
7036 { | |
7037 v.push_back(0x60 + static_cast<uint8_t>(N)); // 1 byte for string + size | |
7038 } | |
7039 else if (N <= 0xff) | |
7040 { | |
7041 v.push_back(0x78); // one-byte uint8_t for N | |
7042 add_to_vector(v, 1, N); | |
7043 } | |
7044 else if (N <= 0xffff) | |
7045 { | |
7046 v.push_back(0x79); // two-byte uint16_t for N | |
7047 add_to_vector(v, 2, N); | |
7048 } | |
7049 else if (N <= 0xffffffff) | |
7050 { | |
7051 v.push_back(0x7a); // four-byte uint32_t for N | |
7052 add_to_vector(v, 4, N); | |
7053 } | |
7054 // LCOV_EXCL_START | |
7055 else if (N <= 0xffffffffffffffff) | |
7056 { | |
7057 v.push_back(0x7b); // eight-byte uint64_t for N | |
7058 add_to_vector(v, 8, N); | |
7059 } | |
7060 // LCOV_EXCL_STOP | |
7061 | |
7062 // append string | |
7063 std::copy(j.m_value.string->begin(), j.m_value.string->end(), | |
7064 std::back_inserter(v)); | |
7065 break; | |
7066 } | |
7067 | |
7068 case value_t::array: | |
7069 { | |
7070 const auto N = j.m_value.array->size(); | |
7071 if (N <= 0x17) | |
7072 { | |
7073 v.push_back(0x80 + static_cast<uint8_t>(N)); // 1 byte for array + size | |
7074 } | |
7075 else if (N <= 0xff) | |
7076 { | |
7077 v.push_back(0x98); // one-byte uint8_t for N | |
7078 add_to_vector(v, 1, N); | |
7079 } | |
7080 else if (N <= 0xffff) | |
7081 { | |
7082 v.push_back(0x99); // two-byte uint16_t for N | |
7083 add_to_vector(v, 2, N); | |
7084 } | |
7085 else if (N <= 0xffffffff) | |
7086 { | |
7087 v.push_back(0x9a); // four-byte uint32_t for N | |
7088 add_to_vector(v, 4, N); | |
7089 } | |
7090 // LCOV_EXCL_START | |
7091 else if (N <= 0xffffffffffffffff) | |
7092 { | |
7093 v.push_back(0x9b); // eight-byte uint64_t for N | |
7094 add_to_vector(v, 8, N); | |
7095 } | |
7096 // LCOV_EXCL_STOP | |
7097 | |
7098 // append each element | |
7099 for (const auto& el : *j.m_value.array) | |
7100 { | |
7101 to_cbor_internal(el, v); | |
7102 } | |
7103 break; | |
7104 } | |
7105 | |
7106 case value_t::object: | |
7107 { | |
7108 const auto N = j.m_value.object->size(); | |
7109 if (N <= 0x17) | |
7110 { | |
7111 v.push_back(0xa0 + static_cast<uint8_t>(N)); // 1 byte for object + size | |
7112 } | |
7113 else if (N <= 0xff) | |
7114 { | |
7115 v.push_back(0xb8); | |
7116 add_to_vector(v, 1, N); // one-byte uint8_t for N | |
7117 } | |
7118 else if (N <= 0xffff) | |
7119 { | |
7120 v.push_back(0xb9); | |
7121 add_to_vector(v, 2, N); // two-byte uint16_t for N | |
7122 } | |
7123 else if (N <= 0xffffffff) | |
7124 { | |
7125 v.push_back(0xba); | |
7126 add_to_vector(v, 4, N); // four-byte uint32_t for N | |
7127 } | |
7128 // LCOV_EXCL_START | |
7129 else if (N <= 0xffffffffffffffff) | |
7130 { | |
7131 v.push_back(0xbb); | |
7132 add_to_vector(v, 8, N); // eight-byte uint64_t for N | |
7133 } | |
7134 // LCOV_EXCL_STOP | |
7135 | |
7136 // append each element | |
7137 for (const auto& el : *j.m_value.object) | |
7138 { | |
7139 to_cbor_internal(el.first, v); | |
7140 to_cbor_internal(el.second, v); | |
7141 } | |
7142 break; | |
7143 } | |
7144 | |
7145 default: | |
7146 { | |
7147 break; | |
7148 } | |
7149 } | |
7150 } | |
7151 | |
7152 | |
7153 /* | |
7154 @brief checks if given lengths do not exceed the size of a given vector | |
7155 | |
7156 To secure the access to the byte vector during CBOR/MessagePack | |
7157 deserialization, bytes are copied from the vector into buffers. This | |
7158 function checks if the number of bytes to copy (@a len) does not exceed | |
7159 the size @s size of the vector. Additionally, an @a offset is given from | |
7160 where to start reading the bytes. | |
7161 | |
7162 This function checks whether reading the bytes is safe; that is, offset is | |
7163 a valid index in the vector, offset+len | |
7164 | |
7165 @param[in] size size of the byte vector | |
7166 @param[in] len number of bytes to read | |
7167 @param[in] offset offset where to start reading | |
7168 | |
7169 vec: x x x x x X X X X X | |
7170 ^ ^ ^ | |
7171 0 offset len | |
7172 | |
7173 @throws out_of_range if `len > v.size()` | |
7174 */ | |
7175 static void check_length(const size_t size, const size_t len, const size_t offset) | |
7176 { | |
7177 // simple case: requested length is greater than the vector's length | |
7178 if (len > size or offset > size) | |
7179 { | |
7180 JSON_THROW(std::out_of_range("len out of range")); | |
7181 } | |
7182 | |
7183 // second case: adding offset would result in overflow | |
7184 if ((size > (std::numeric_limits<size_t>::max() - offset))) | |
7185 { | |
7186 JSON_THROW(std::out_of_range("len+offset out of range")); | |
7187 } | |
7188 | |
7189 // last case: reading past the end of the vector | |
7190 if (len + offset > size) | |
7191 { | |
7192 JSON_THROW(std::out_of_range("len+offset out of range")); | |
7193 } | |
7194 } | |
7195 | |
7196 /*! | |
7197 @brief create a JSON value from a given MessagePack vector | |
7198 | |
7199 @param[in] v MessagePack serialization | |
7200 @param[in] idx byte index to start reading from @a v | |
7201 | |
7202 @return deserialized JSON value | |
7203 | |
7204 @throw std::invalid_argument if unsupported features from MessagePack were | |
7205 used in the given vector @a v or if the input is not valid MessagePack | |
7206 @throw std::out_of_range if the given vector ends prematurely | |
7207 | |
7208 @sa https://github.com/msgpack/msgpack/blob/master/spec.md | |
7209 */ | |
7210 static basic_json from_msgpack_internal(const std::vector<uint8_t>& v, size_t& idx) | |
7211 { | |
7212 // make sure reading 1 byte is safe | |
7213 check_length(v.size(), 1, idx); | |
7214 | |
7215 // store and increment index | |
7216 const size_t current_idx = idx++; | |
7217 | |
7218 if (v[current_idx] <= 0xbf) | |
7219 { | |
7220 if (v[current_idx] <= 0x7f) // positive fixint | |
7221 { | |
7222 return v[current_idx]; | |
7223 } | |
7224 if (v[current_idx] <= 0x8f) // fixmap | |
7225 { | |
7226 basic_json result = value_t::object; | |
7227 const size_t len = v[current_idx] & 0x0f; | |
7228 for (size_t i = 0; i < len; ++i) | |
7229 { | |
7230 std::string key = from_msgpack_internal(v, idx); | |
7231 result[key] = from_msgpack_internal(v, idx); | |
7232 } | |
7233 return result; | |
7234 } | |
7235 else if (v[current_idx] <= 0x9f) // fixarray | |
7236 { | |
7237 basic_json result = value_t::array; | |
7238 const size_t len = v[current_idx] & 0x0f; | |
7239 for (size_t i = 0; i < len; ++i) | |
7240 { | |
7241 result.push_back(from_msgpack_internal(v, idx)); | |
7242 } | |
7243 return result; | |
7244 } | |
7245 else // fixstr | |
7246 { | |
7247 const size_t len = v[current_idx] & 0x1f; | |
7248 const size_t offset = current_idx + 1; | |
7249 idx += len; // skip content bytes | |
7250 check_length(v.size(), len, offset); | |
7251 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); | |
7252 } | |
7253 } | |
7254 else if (v[current_idx] >= 0xe0) // negative fixint | |
7255 { | |
7256 return static_cast<int8_t>(v[current_idx]); | |
7257 } | |
7258 else | |
7259 { | |
7260 switch (v[current_idx]) | |
7261 { | |
7262 case 0xc0: // nil | |
7263 { | |
7264 return value_t::null; | |
7265 } | |
7266 | |
7267 case 0xc2: // false | |
7268 { | |
7269 return false; | |
7270 } | |
7271 | |
7272 case 0xc3: // true | |
7273 { | |
7274 return true; | |
7275 } | |
7276 | |
7277 case 0xca: // float 32 | |
7278 { | |
7279 // copy bytes in reverse order into the double variable | |
7280 float res; | |
7281 for (size_t byte = 0; byte < sizeof(float); ++byte) | |
7282 { | |
7283 reinterpret_cast<uint8_t*>(&res)[sizeof(float) - byte - 1] = v.at(current_idx + 1 + byte); | |
7284 } | |
7285 idx += sizeof(float); // skip content bytes | |
7286 return res; | |
7287 } | |
7288 | |
7289 case 0xcb: // float 64 | |
7290 { | |
7291 // copy bytes in reverse order into the double variable | |
7292 double res; | |
7293 for (size_t byte = 0; byte < sizeof(double); ++byte) | |
7294 { | |
7295 reinterpret_cast<uint8_t*>(&res)[sizeof(double) - byte - 1] = v.at(current_idx + 1 + byte); | |
7296 } | |
7297 idx += sizeof(double); // skip content bytes | |
7298 return res; | |
7299 } | |
7300 | |
7301 case 0xcc: // uint 8 | |
7302 { | |
7303 idx += 1; // skip content byte | |
7304 return get_from_vector<uint8_t>(v, current_idx); | |
7305 } | |
7306 | |
7307 case 0xcd: // uint 16 | |
7308 { | |
7309 idx += 2; // skip 2 content bytes | |
7310 return get_from_vector<uint16_t>(v, current_idx); | |
7311 } | |
7312 | |
7313 case 0xce: // uint 32 | |
7314 { | |
7315 idx += 4; // skip 4 content bytes | |
7316 return get_from_vector<uint32_t>(v, current_idx); | |
7317 } | |
7318 | |
7319 case 0xcf: // uint 64 | |
7320 { | |
7321 idx += 8; // skip 8 content bytes | |
7322 return get_from_vector<uint64_t>(v, current_idx); | |
7323 } | |
7324 | |
7325 case 0xd0: // int 8 | |
7326 { | |
7327 idx += 1; // skip content byte | |
7328 return get_from_vector<int8_t>(v, current_idx); | |
7329 } | |
7330 | |
7331 case 0xd1: // int 16 | |
7332 { | |
7333 idx += 2; // skip 2 content bytes | |
7334 return get_from_vector<int16_t>(v, current_idx); | |
7335 } | |
7336 | |
7337 case 0xd2: // int 32 | |
7338 { | |
7339 idx += 4; // skip 4 content bytes | |
7340 return get_from_vector<int32_t>(v, current_idx); | |
7341 } | |
7342 | |
7343 case 0xd3: // int 64 | |
7344 { | |
7345 idx += 8; // skip 8 content bytes | |
7346 return get_from_vector<int64_t>(v, current_idx); | |
7347 } | |
7348 | |
7349 case 0xd9: // str 8 | |
7350 { | |
7351 const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx)); | |
7352 const size_t offset = current_idx + 2; | |
7353 idx += len + 1; // skip size byte + content bytes | |
7354 check_length(v.size(), len, offset); | |
7355 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); | |
7356 } | |
7357 | |
7358 case 0xda: // str 16 | |
7359 { | |
7360 const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx)); | |
7361 const size_t offset = current_idx + 3; | |
7362 idx += len + 2; // skip 2 size bytes + content bytes | |
7363 check_length(v.size(), len, offset); | |
7364 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); | |
7365 } | |
7366 | |
7367 case 0xdb: // str 32 | |
7368 { | |
7369 const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx)); | |
7370 const size_t offset = current_idx + 5; | |
7371 idx += len + 4; // skip 4 size bytes + content bytes | |
7372 check_length(v.size(), len, offset); | |
7373 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); | |
7374 } | |
7375 | |
7376 case 0xdc: // array 16 | |
7377 { | |
7378 basic_json result = value_t::array; | |
7379 const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx)); | |
7380 idx += 2; // skip 2 size bytes | |
7381 for (size_t i = 0; i < len; ++i) | |
7382 { | |
7383 result.push_back(from_msgpack_internal(v, idx)); | |
7384 } | |
7385 return result; | |
7386 } | |
7387 | |
7388 case 0xdd: // array 32 | |
7389 { | |
7390 basic_json result = value_t::array; | |
7391 const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx)); | |
7392 idx += 4; // skip 4 size bytes | |
7393 for (size_t i = 0; i < len; ++i) | |
7394 { | |
7395 result.push_back(from_msgpack_internal(v, idx)); | |
7396 } | |
7397 return result; | |
7398 } | |
7399 | |
7400 case 0xde: // map 16 | |
7401 { | |
7402 basic_json result = value_t::object; | |
7403 const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx)); | |
7404 idx += 2; // skip 2 size bytes | |
7405 for (size_t i = 0; i < len; ++i) | |
7406 { | |
7407 std::string key = from_msgpack_internal(v, idx); | |
7408 result[key] = from_msgpack_internal(v, idx); | |
7409 } | |
7410 return result; | |
7411 } | |
7412 | |
7413 case 0xdf: // map 32 | |
7414 { | |
7415 basic_json result = value_t::object; | |
7416 const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx)); | |
7417 idx += 4; // skip 4 size bytes | |
7418 for (size_t i = 0; i < len; ++i) | |
7419 { | |
7420 std::string key = from_msgpack_internal(v, idx); | |
7421 result[key] = from_msgpack_internal(v, idx); | |
7422 } | |
7423 return result; | |
7424 } | |
7425 | |
7426 default: | |
7427 { | |
7428 JSON_THROW(std::invalid_argument("error parsing a msgpack @ " + std::to_string(current_idx) + ": " + std::to_string(static_cast<int>(v[current_idx])))); | |
7429 } | |
7430 } | |
7431 } | |
7432 } | |
7433 | |
7434 /*! | |
7435 @brief create a JSON value from a given CBOR vector | |
7436 | |
7437 @param[in] v CBOR serialization | |
7438 @param[in] idx byte index to start reading from @a v | |
7439 | |
7440 @return deserialized JSON value | |
7441 | |
7442 @throw std::invalid_argument if unsupported features from CBOR were used in | |
7443 the given vector @a v or if the input is not valid CBOR | |
7444 @throw std::out_of_range if the given vector ends prematurely | |
7445 | |
7446 @sa https://tools.ietf.org/html/rfc7049 | |
7447 */ | |
7448 static basic_json from_cbor_internal(const std::vector<uint8_t>& v, size_t& idx) | |
7449 { | |
7450 // store and increment index | |
7451 const size_t current_idx = idx++; | |
7452 | |
7453 switch (v.at(current_idx)) | |
7454 { | |
7455 // Integer 0x00..0x17 (0..23) | |
7456 case 0x00: | |
7457 case 0x01: | |
7458 case 0x02: | |
7459 case 0x03: | |
7460 case 0x04: | |
7461 case 0x05: | |
7462 case 0x06: | |
7463 case 0x07: | |
7464 case 0x08: | |
7465 case 0x09: | |
7466 case 0x0a: | |
7467 case 0x0b: | |
7468 case 0x0c: | |
7469 case 0x0d: | |
7470 case 0x0e: | |
7471 case 0x0f: | |
7472 case 0x10: | |
7473 case 0x11: | |
7474 case 0x12: | |
7475 case 0x13: | |
7476 case 0x14: | |
7477 case 0x15: | |
7478 case 0x16: | |
7479 case 0x17: | |
7480 { | |
7481 return v[current_idx]; | |
7482 } | |
7483 | |
7484 case 0x18: // Unsigned integer (one-byte uint8_t follows) | |
7485 { | |
7486 idx += 1; // skip content byte | |
7487 return get_from_vector<uint8_t>(v, current_idx); | |
7488 } | |
7489 | |
7490 case 0x19: // Unsigned integer (two-byte uint16_t follows) | |
7491 { | |
7492 idx += 2; // skip 2 content bytes | |
7493 return get_from_vector<uint16_t>(v, current_idx); | |
7494 } | |
7495 | |
7496 case 0x1a: // Unsigned integer (four-byte uint32_t follows) | |
7497 { | |
7498 idx += 4; // skip 4 content bytes | |
7499 return get_from_vector<uint32_t>(v, current_idx); | |
7500 } | |
7501 | |
7502 case 0x1b: // Unsigned integer (eight-byte uint64_t follows) | |
7503 { | |
7504 idx += 8; // skip 8 content bytes | |
7505 return get_from_vector<uint64_t>(v, current_idx); | |
7506 } | |
7507 | |
7508 // Negative integer -1-0x00..-1-0x17 (-1..-24) | |
7509 case 0x20: | |
7510 case 0x21: | |
7511 case 0x22: | |
7512 case 0x23: | |
7513 case 0x24: | |
7514 case 0x25: | |
7515 case 0x26: | |
7516 case 0x27: | |
7517 case 0x28: | |
7518 case 0x29: | |
7519 case 0x2a: | |
7520 case 0x2b: | |
7521 case 0x2c: | |
7522 case 0x2d: | |
7523 case 0x2e: | |
7524 case 0x2f: | |
7525 case 0x30: | |
7526 case 0x31: | |
7527 case 0x32: | |
7528 case 0x33: | |
7529 case 0x34: | |
7530 case 0x35: | |
7531 case 0x36: | |
7532 case 0x37: | |
7533 { | |
7534 return static_cast<int8_t>(0x20 - 1 - v[current_idx]); | |
7535 } | |
7536 | |
7537 case 0x38: // Negative integer (one-byte uint8_t follows) | |
7538 { | |
7539 idx += 1; // skip content byte | |
7540 // must be uint8_t ! | |
7541 return static_cast<number_integer_t>(-1) - get_from_vector<uint8_t>(v, current_idx); | |
7542 } | |
7543 | |
7544 case 0x39: // Negative integer -1-n (two-byte uint16_t follows) | |
7545 { | |
7546 idx += 2; // skip 2 content bytes | |
7547 return static_cast<number_integer_t>(-1) - get_from_vector<uint16_t>(v, current_idx); | |
7548 } | |
7549 | |
7550 case 0x3a: // Negative integer -1-n (four-byte uint32_t follows) | |
7551 { | |
7552 idx += 4; // skip 4 content bytes | |
7553 return static_cast<number_integer_t>(-1) - get_from_vector<uint32_t>(v, current_idx); | |
7554 } | |
7555 | |
7556 case 0x3b: // Negative integer -1-n (eight-byte uint64_t follows) | |
7557 { | |
7558 idx += 8; // skip 8 content bytes | |
7559 return static_cast<number_integer_t>(-1) - static_cast<number_integer_t>(get_from_vector<uint64_t>(v, current_idx)); | |
7560 } | |
7561 | |
7562 // UTF-8 string (0x00..0x17 bytes follow) | |
7563 case 0x60: | |
7564 case 0x61: | |
7565 case 0x62: | |
7566 case 0x63: | |
7567 case 0x64: | |
7568 case 0x65: | |
7569 case 0x66: | |
7570 case 0x67: | |
7571 case 0x68: | |
7572 case 0x69: | |
7573 case 0x6a: | |
7574 case 0x6b: | |
7575 case 0x6c: | |
7576 case 0x6d: | |
7577 case 0x6e: | |
7578 case 0x6f: | |
7579 case 0x70: | |
7580 case 0x71: | |
7581 case 0x72: | |
7582 case 0x73: | |
7583 case 0x74: | |
7584 case 0x75: | |
7585 case 0x76: | |
7586 case 0x77: | |
7587 { | |
7588 const auto len = static_cast<size_t>(v[current_idx] - 0x60); | |
7589 const size_t offset = current_idx + 1; | |
7590 idx += len; // skip content bytes | |
7591 check_length(v.size(), len, offset); | |
7592 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); | |
7593 } | |
7594 | |
7595 case 0x78: // UTF-8 string (one-byte uint8_t for n follows) | |
7596 { | |
7597 const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx)); | |
7598 const size_t offset = current_idx + 2; | |
7599 idx += len + 1; // skip size byte + content bytes | |
7600 check_length(v.size(), len, offset); | |
7601 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); | |
7602 } | |
7603 | |
7604 case 0x79: // UTF-8 string (two-byte uint16_t for n follow) | |
7605 { | |
7606 const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx)); | |
7607 const size_t offset = current_idx + 3; | |
7608 idx += len + 2; // skip 2 size bytes + content bytes | |
7609 check_length(v.size(), len, offset); | |
7610 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); | |
7611 } | |
7612 | |
7613 case 0x7a: // UTF-8 string (four-byte uint32_t for n follow) | |
7614 { | |
7615 const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx)); | |
7616 const size_t offset = current_idx + 5; | |
7617 idx += len + 4; // skip 4 size bytes + content bytes | |
7618 check_length(v.size(), len, offset); | |
7619 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); | |
7620 } | |
7621 | |
7622 case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow) | |
7623 { | |
7624 const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx)); | |
7625 const size_t offset = current_idx + 9; | |
7626 idx += len + 8; // skip 8 size bytes + content bytes | |
7627 check_length(v.size(), len, offset); | |
7628 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); | |
7629 } | |
7630 | |
7631 case 0x7f: // UTF-8 string (indefinite length) | |
7632 { | |
7633 std::string result; | |
7634 while (v.at(idx) != 0xff) | |
7635 { | |
7636 string_t s = from_cbor_internal(v, idx); | |
7637 result += s; | |
7638 } | |
7639 // skip break byte (0xFF) | |
7640 idx += 1; | |
7641 return result; | |
7642 } | |
7643 | |
7644 // array (0x00..0x17 data items follow) | |
7645 case 0x80: | |
7646 case 0x81: | |
7647 case 0x82: | |
7648 case 0x83: | |
7649 case 0x84: | |
7650 case 0x85: | |
7651 case 0x86: | |
7652 case 0x87: | |
7653 case 0x88: | |
7654 case 0x89: | |
7655 case 0x8a: | |
7656 case 0x8b: | |
7657 case 0x8c: | |
7658 case 0x8d: | |
7659 case 0x8e: | |
7660 case 0x8f: | |
7661 case 0x90: | |
7662 case 0x91: | |
7663 case 0x92: | |
7664 case 0x93: | |
7665 case 0x94: | |
7666 case 0x95: | |
7667 case 0x96: | |
7668 case 0x97: | |
7669 { | |
7670 basic_json result = value_t::array; | |
7671 const auto len = static_cast<size_t>(v[current_idx] - 0x80); | |
7672 for (size_t i = 0; i < len; ++i) | |
7673 { | |
7674 result.push_back(from_cbor_internal(v, idx)); | |
7675 } | |
7676 return result; | |
7677 } | |
7678 | |
7679 case 0x98: // array (one-byte uint8_t for n follows) | |
7680 { | |
7681 basic_json result = value_t::array; | |
7682 const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx)); | |
7683 idx += 1; // skip 1 size byte | |
7684 for (size_t i = 0; i < len; ++i) | |
7685 { | |
7686 result.push_back(from_cbor_internal(v, idx)); | |
7687 } | |
7688 return result; | |
7689 } | |
7690 | |
7691 case 0x99: // array (two-byte uint16_t for n follow) | |
7692 { | |
7693 basic_json result = value_t::array; | |
7694 const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx)); | |
7695 idx += 2; // skip 4 size bytes | |
7696 for (size_t i = 0; i < len; ++i) | |
7697 { | |
7698 result.push_back(from_cbor_internal(v, idx)); | |
7699 } | |
7700 return result; | |
7701 } | |
7702 | |
7703 case 0x9a: // array (four-byte uint32_t for n follow) | |
7704 { | |
7705 basic_json result = value_t::array; | |
7706 const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx)); | |
7707 idx += 4; // skip 4 size bytes | |
7708 for (size_t i = 0; i < len; ++i) | |
7709 { | |
7710 result.push_back(from_cbor_internal(v, idx)); | |
7711 } | |
7712 return result; | |
7713 } | |
7714 | |
7715 case 0x9b: // array (eight-byte uint64_t for n follow) | |
7716 { | |
7717 basic_json result = value_t::array; | |
7718 const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx)); | |
7719 idx += 8; // skip 8 size bytes | |
7720 for (size_t i = 0; i < len; ++i) | |
7721 { | |
7722 result.push_back(from_cbor_internal(v, idx)); | |
7723 } | |
7724 return result; | |
7725 } | |
7726 | |
7727 case 0x9f: // array (indefinite length) | |
7728 { | |
7729 basic_json result = value_t::array; | |
7730 while (v.at(idx) != 0xff) | |
7731 { | |
7732 result.push_back(from_cbor_internal(v, idx)); | |
7733 } | |
7734 // skip break byte (0xFF) | |
7735 idx += 1; | |
7736 return result; | |
7737 } | |
7738 | |
7739 // map (0x00..0x17 pairs of data items follow) | |
7740 case 0xa0: | |
7741 case 0xa1: | |
7742 case 0xa2: | |
7743 case 0xa3: | |
7744 case 0xa4: | |
7745 case 0xa5: | |
7746 case 0xa6: | |
7747 case 0xa7: | |
7748 case 0xa8: | |
7749 case 0xa9: | |
7750 case 0xaa: | |
7751 case 0xab: | |
7752 case 0xac: | |
7753 case 0xad: | |
7754 case 0xae: | |
7755 case 0xaf: | |
7756 case 0xb0: | |
7757 case 0xb1: | |
7758 case 0xb2: | |
7759 case 0xb3: | |
7760 case 0xb4: | |
7761 case 0xb5: | |
7762 case 0xb6: | |
7763 case 0xb7: | |
7764 { | |
7765 basic_json result = value_t::object; | |
7766 const auto len = static_cast<size_t>(v[current_idx] - 0xa0); | |
7767 for (size_t i = 0; i < len; ++i) | |
7768 { | |
7769 std::string key = from_cbor_internal(v, idx); | |
7770 result[key] = from_cbor_internal(v, idx); | |
7771 } | |
7772 return result; | |
7773 } | |
7774 | |
7775 case 0xb8: // map (one-byte uint8_t for n follows) | |
7776 { | |
7777 basic_json result = value_t::object; | |
7778 const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx)); | |
7779 idx += 1; // skip 1 size byte | |
7780 for (size_t i = 0; i < len; ++i) | |
7781 { | |
7782 std::string key = from_cbor_internal(v, idx); | |
7783 result[key] = from_cbor_internal(v, idx); | |
7784 } | |
7785 return result; | |
7786 } | |
7787 | |
7788 case 0xb9: // map (two-byte uint16_t for n follow) | |
7789 { | |
7790 basic_json result = value_t::object; | |
7791 const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx)); | |
7792 idx += 2; // skip 2 size bytes | |
7793 for (size_t i = 0; i < len; ++i) | |
7794 { | |
7795 std::string key = from_cbor_internal(v, idx); | |
7796 result[key] = from_cbor_internal(v, idx); | |
7797 } | |
7798 return result; | |
7799 } | |
7800 | |
7801 case 0xba: // map (four-byte uint32_t for n follow) | |
7802 { | |
7803 basic_json result = value_t::object; | |
7804 const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx)); | |
7805 idx += 4; // skip 4 size bytes | |
7806 for (size_t i = 0; i < len; ++i) | |
7807 { | |
7808 std::string key = from_cbor_internal(v, idx); | |
7809 result[key] = from_cbor_internal(v, idx); | |
7810 } | |
7811 return result; | |
7812 } | |
7813 | |
7814 case 0xbb: // map (eight-byte uint64_t for n follow) | |
7815 { | |
7816 basic_json result = value_t::object; | |
7817 const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx)); | |
7818 idx += 8; // skip 8 size bytes | |
7819 for (size_t i = 0; i < len; ++i) | |
7820 { | |
7821 std::string key = from_cbor_internal(v, idx); | |
7822 result[key] = from_cbor_internal(v, idx); | |
7823 } | |
7824 return result; | |
7825 } | |
7826 | |
7827 case 0xbf: // map (indefinite length) | |
7828 { | |
7829 basic_json result = value_t::object; | |
7830 while (v.at(idx) != 0xff) | |
7831 { | |
7832 std::string key = from_cbor_internal(v, idx); | |
7833 result[key] = from_cbor_internal(v, idx); | |
7834 } | |
7835 // skip break byte (0xFF) | |
7836 idx += 1; | |
7837 return result; | |
7838 } | |
7839 | |
7840 case 0xf4: // false | |
7841 { | |
7842 return false; | |
7843 } | |
7844 | |
7845 case 0xf5: // true | |
7846 { | |
7847 return true; | |
7848 } | |
7849 | |
7850 case 0xf6: // null | |
7851 { | |
7852 return value_t::null; | |
7853 } | |
7854 | |
7855 case 0xf9: // Half-Precision Float (two-byte IEEE 754) | |
7856 { | |
7857 idx += 2; // skip two content bytes | |
7858 | |
7859 // code from RFC 7049, Appendix D, Figure 3: | |
7860 // As half-precision floating-point numbers were only added to | |
7861 // IEEE 754 in 2008, today's programming platforms often still | |
7862 // only have limited support for them. It is very easy to | |
7863 // include at least decoding support for them even without such | |
7864 // support. An example of a small decoder for half-precision | |
7865 // floating-point numbers in the C language is shown in Fig. 3. | |
7866 const int half = (v.at(current_idx + 1) << 8) + v.at(current_idx + 2); | |
7867 const int exp = (half >> 10) & 0x1f; | |
7868 const int mant = half & 0x3ff; | |
7869 double val; | |
7870 if (exp == 0) | |
7871 { | |
7872 val = std::ldexp(mant, -24); | |
7873 } | |
7874 else if (exp != 31) | |
7875 { | |
7876 val = std::ldexp(mant + 1024, exp - 25); | |
7877 } | |
7878 else | |
7879 { | |
7880 val = mant == 0 | |
7881 ? std::numeric_limits<double>::infinity() | |
7882 : std::numeric_limits<double>::quiet_NaN(); | |
7883 } | |
7884 return (half & 0x8000) != 0 ? -val : val; | |
7885 } | |
7886 | |
7887 case 0xfa: // Single-Precision Float (four-byte IEEE 754) | |
7888 { | |
7889 // copy bytes in reverse order into the float variable | |
7890 float res; | |
7891 for (size_t byte = 0; byte < sizeof(float); ++byte) | |
7892 { | |
7893 reinterpret_cast<uint8_t*>(&res)[sizeof(float) - byte - 1] = v.at(current_idx + 1 + byte); | |
7894 } | |
7895 idx += sizeof(float); // skip content bytes | |
7896 return res; | |
7897 } | |
7898 | |
7899 case 0xfb: // Double-Precision Float (eight-byte IEEE 754) | |
7900 { | |
7901 // copy bytes in reverse order into the double variable | |
7902 double res; | |
7903 for (size_t byte = 0; byte < sizeof(double); ++byte) | |
7904 { | |
7905 reinterpret_cast<uint8_t*>(&res)[sizeof(double) - byte - 1] = v.at(current_idx + 1 + byte); | |
7906 } | |
7907 idx += sizeof(double); // skip content bytes | |
7908 return res; | |
7909 } | |
7910 | |
7911 default: // anything else (0xFF is handled inside the other types) | |
7912 { | |
7913 JSON_THROW(std::invalid_argument("error parsing a CBOR @ " + std::to_string(current_idx) + ": " + std::to_string(static_cast<int>(v[current_idx])))); | |
7914 } | |
7915 } | |
7916 } | |
7917 | |
7918 public: | |
7919 /*! | |
7920 @brief create a MessagePack serialization of a given JSON value | |
7921 | |
7922 Serializes a given JSON value @a j to a byte vector using the MessagePack | |
7923 serialization format. MessagePack is a binary serialization format which | |
7924 aims to be more compact than JSON itself, yet more efficient to parse. | |
7925 | |
7926 @param[in] j JSON value to serialize | |
7927 @return MessagePack serialization as byte vector | |
7928 | |
7929 @complexity Linear in the size of the JSON value @a j. | |
7930 | |
7931 @liveexample{The example shows the serialization of a JSON value to a byte | |
7932 vector in MessagePack format.,to_msgpack} | |
7933 | |
7934 @sa http://msgpack.org | |
7935 @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the | |
7936 analogous deserialization | |
7937 @sa @ref to_cbor(const basic_json& for the related CBOR format | |
7938 | |
7939 @since version 2.0.9 | |
7940 */ | |
7941 static std::vector<uint8_t> to_msgpack(const basic_json& j) | |
7942 { | |
7943 std::vector<uint8_t> result; | |
7944 to_msgpack_internal(j, result); | |
7945 return result; | |
7946 } | |
7947 | |
7948 /*! | |
7949 @brief create a JSON value from a byte vector in MessagePack format | |
7950 | |
7951 Deserializes a given byte vector @a v to a JSON value using the MessagePack | |
7952 serialization format. | |
7953 | |
7954 @param[in] v a byte vector in MessagePack format | |
7955 @param[in] start_index the index to start reading from @a v (0 by default) | |
7956 @return deserialized JSON value | |
7957 | |
7958 @throw std::invalid_argument if unsupported features from MessagePack were | |
7959 used in the given vector @a v or if the input is not valid MessagePack | |
7960 @throw std::out_of_range if the given vector ends prematurely | |
7961 | |
7962 @complexity Linear in the size of the byte vector @a v. | |
7963 | |
7964 @liveexample{The example shows the deserialization of a byte vector in | |
7965 MessagePack format to a JSON value.,from_msgpack} | |
7966 | |
7967 @sa http://msgpack.org | |
7968 @sa @ref to_msgpack(const basic_json&) for the analogous serialization | |
7969 @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the | |
7970 related CBOR format | |
7971 | |
7972 @since version 2.0.9, parameter @a start_index since 2.1.1 | |
7973 */ | |
7974 static basic_json from_msgpack(const std::vector<uint8_t>& v, | |
7975 const size_t start_index = 0) | |
7976 { | |
7977 size_t i = start_index; | |
7978 return from_msgpack_internal(v, i); | |
7979 } | |
7980 | |
7981 /*! | |
7982 @brief create a MessagePack serialization of a given JSON value | |
7983 | |
7984 Serializes a given JSON value @a j to a byte vector using the CBOR (Concise | |
7985 Binary Object Representation) serialization format. CBOR is a binary | |
7986 serialization format which aims to be more compact than JSON itself, yet | |
7987 more efficient to parse. | |
7988 | |
7989 @param[in] j JSON value to serialize | |
7990 @return MessagePack serialization as byte vector | |
7991 | |
7992 @complexity Linear in the size of the JSON value @a j. | |
7993 | |
7994 @liveexample{The example shows the serialization of a JSON value to a byte | |
7995 vector in CBOR format.,to_cbor} | |
7996 | |
7997 @sa http://cbor.io | |
7998 @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the | |
7999 analogous deserialization | |
8000 @sa @ref to_msgpack(const basic_json& for the related MessagePack format | |
8001 | |
8002 @since version 2.0.9 | |
8003 */ | |
8004 static std::vector<uint8_t> to_cbor(const basic_json& j) | |
8005 { | |
8006 std::vector<uint8_t> result; | |
8007 to_cbor_internal(j, result); | |
8008 return result; | |
8009 } | |
8010 | |
8011 /*! | |
8012 @brief create a JSON value from a byte vector in CBOR format | |
8013 | |
8014 Deserializes a given byte vector @a v to a JSON value using the CBOR | |
8015 (Concise Binary Object Representation) serialization format. | |
8016 | |
8017 @param[in] v a byte vector in CBOR format | |
8018 @param[in] start_index the index to start reading from @a v (0 by default) | |
8019 @return deserialized JSON value | |
8020 | |
8021 @throw std::invalid_argument if unsupported features from CBOR were used in | |
8022 the given vector @a v or if the input is not valid MessagePack | |
8023 @throw std::out_of_range if the given vector ends prematurely | |
8024 | |
8025 @complexity Linear in the size of the byte vector @a v. | |
8026 | |
8027 @liveexample{The example shows the deserialization of a byte vector in CBOR | |
8028 format to a JSON value.,from_cbor} | |
8029 | |
8030 @sa http://cbor.io | |
8031 @sa @ref to_cbor(const basic_json&) for the analogous serialization | |
8032 @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the | |
8033 related MessagePack format | |
8034 | |
8035 @since version 2.0.9, parameter @a start_index since 2.1.1 | |
8036 */ | |
8037 static basic_json from_cbor(const std::vector<uint8_t>& v, | |
8038 const size_t start_index = 0) | |
8039 { | |
8040 size_t i = start_index; | |
8041 return from_cbor_internal(v, i); | |
8042 } | 15748 } |
8043 | 15749 |
8044 /// @} | 15750 /// @} |
8045 | 15751 |
8046 /////////////////////////// | 15752 /////////////////////////// |
8051 @brief return the type as string | 15757 @brief return the type as string |
8052 | 15758 |
8053 Returns the type name as string to be used in error messages - usually to | 15759 Returns the type name as string to be used in error messages - usually to |
8054 indicate that a function was called on a wrong JSON type. | 15760 indicate that a function was called on a wrong JSON type. |
8055 | 15761 |
8056 @return basically a string representation of a the @a m_type member | 15762 @return a string representation of a the @a m_type member: |
15763 Value type | return value | |
15764 ----------- | ------------- | |
15765 null | `"null"` | |
15766 boolean | `"boolean"` | |
15767 string | `"string"` | |
15768 number | `"number"` (for all number types) | |
15769 object | `"object"` | |
15770 array | `"array"` | |
15771 discarded | `"discarded"` | |
15772 | |
15773 @exceptionsafety No-throw guarantee: this function never throws exceptions. | |
8057 | 15774 |
8058 @complexity Constant. | 15775 @complexity Constant. |
8059 | 15776 |
8060 @liveexample{The following code exemplifies `type_name()` for all JSON | 15777 @liveexample{The following code exemplifies `type_name()` for all JSON |
8061 types.,type_name} | 15778 types.,type_name} |
8062 | 15779 |
8063 @since version 1.0.0, public since 2.1.0 | 15780 @sa @ref type() -- return the type of the JSON value |
8064 */ | 15781 @sa @ref operator value_t() -- return the type of the JSON value (implicit) |
8065 std::string type_name() const | 15782 |
15783 @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept` | |
15784 since 3.0.0 | |
15785 */ | |
15786 const char* type_name() const noexcept | |
8066 { | 15787 { |
8067 { | 15788 { |
8068 switch (m_type) | 15789 switch (m_type) |
8069 { | 15790 { |
8070 case value_t::null: | 15791 case value_t::null: |
8083 return "number"; | 15804 return "number"; |
8084 } | 15805 } |
8085 } | 15806 } |
8086 } | 15807 } |
8087 | 15808 |
8088 private: | |
8089 /*! | |
8090 @brief calculates the extra space to escape a JSON string | |
8091 | |
8092 @param[in] s the string to escape | |
8093 @return the number of characters required to escape string @a s | |
8094 | |
8095 @complexity Linear in the length of string @a s. | |
8096 */ | |
8097 static std::size_t extra_space(const string_t& s) noexcept | |
8098 { | |
8099 return std::accumulate(s.begin(), s.end(), size_t{}, | |
8100 [](size_t res, typename string_t::value_type c) | |
8101 { | |
8102 switch (c) | |
8103 { | |
8104 case '"': | |
8105 case '\\': | |
8106 case '\b': | |
8107 case '\f': | |
8108 case '\n': | |
8109 case '\r': | |
8110 case '\t': | |
8111 { | |
8112 // from c (1 byte) to \x (2 bytes) | |
8113 return res + 1; | |
8114 } | |
8115 | |
8116 default: | |
8117 { | |
8118 if (c >= 0x00 and c <= 0x1f) | |
8119 { | |
8120 // from c (1 byte) to \uxxxx (6 bytes) | |
8121 return res + 5; | |
8122 } | |
8123 | |
8124 return res; | |
8125 } | |
8126 } | |
8127 }); | |
8128 } | |
8129 | |
8130 /*! | |
8131 @brief escape a string | |
8132 | |
8133 Escape a string by replacing certain special characters by a sequence of | |
8134 an escape character (backslash) and another character and other control | |
8135 characters by a sequence of "\u" followed by a four-digit hex | |
8136 representation. | |
8137 | |
8138 @param[in] s the string to escape | |
8139 @return the escaped string | |
8140 | |
8141 @complexity Linear in the length of string @a s. | |
8142 */ | |
8143 static string_t escape_string(const string_t& s) | |
8144 { | |
8145 const auto space = extra_space(s); | |
8146 if (space == 0) | |
8147 { | |
8148 return s; | |
8149 } | |
8150 | |
8151 // create a result string of necessary size | |
8152 string_t result(s.size() + space, '\\'); | |
8153 std::size_t pos = 0; | |
8154 | |
8155 for (const auto& c : s) | |
8156 { | |
8157 switch (c) | |
8158 { | |
8159 // quotation mark (0x22) | |
8160 case '"': | |
8161 { | |
8162 result[pos + 1] = '"'; | |
8163 pos += 2; | |
8164 break; | |
8165 } | |
8166 | |
8167 // reverse solidus (0x5c) | |
8168 case '\\': | |
8169 { | |
8170 // nothing to change | |
8171 pos += 2; | |
8172 break; | |
8173 } | |
8174 | |
8175 // backspace (0x08) | |
8176 case '\b': | |
8177 { | |
8178 result[pos + 1] = 'b'; | |
8179 pos += 2; | |
8180 break; | |
8181 } | |
8182 | |
8183 // formfeed (0x0c) | |
8184 case '\f': | |
8185 { | |
8186 result[pos + 1] = 'f'; | |
8187 pos += 2; | |
8188 break; | |
8189 } | |
8190 | |
8191 // newline (0x0a) | |
8192 case '\n': | |
8193 { | |
8194 result[pos + 1] = 'n'; | |
8195 pos += 2; | |
8196 break; | |
8197 } | |
8198 | |
8199 // carriage return (0x0d) | |
8200 case '\r': | |
8201 { | |
8202 result[pos + 1] = 'r'; | |
8203 pos += 2; | |
8204 break; | |
8205 } | |
8206 | |
8207 // horizontal tab (0x09) | |
8208 case '\t': | |
8209 { | |
8210 result[pos + 1] = 't'; | |
8211 pos += 2; | |
8212 break; | |
8213 } | |
8214 | |
8215 default: | |
8216 { | |
8217 if (c >= 0x00 and c <= 0x1f) | |
8218 { | |
8219 // convert a number 0..15 to its hex representation | |
8220 // (0..f) | |
8221 static const char hexify[16] = | |
8222 { | |
8223 '0', '1', '2', '3', '4', '5', '6', '7', | |
8224 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' | |
8225 }; | |
8226 | |
8227 // print character c as \uxxxx | |
8228 for (const char m : | |
8229 { 'u', '0', '0', hexify[c >> 4], hexify[c & 0x0f] | |
8230 }) | |
8231 { | |
8232 result[++pos] = m; | |
8233 } | |
8234 | |
8235 ++pos; | |
8236 } | |
8237 else | |
8238 { | |
8239 // all other characters are added as-is | |
8240 result[pos++] = c; | |
8241 } | |
8242 break; | |
8243 } | |
8244 } | |
8245 } | |
8246 | |
8247 return result; | |
8248 } | |
8249 | |
8250 | |
8251 /*! | |
8252 @brief locale-independent serialization for built-in arithmetic types | |
8253 */ | |
8254 struct numtostr | |
8255 { | |
8256 public: | |
8257 template<typename NumberType> | |
8258 numtostr(NumberType value) | |
8259 { | |
8260 x_write(value, std::is_integral<NumberType>()); | |
8261 } | |
8262 | |
8263 const char* c_str() const | |
8264 { | |
8265 return m_buf.data(); | |
8266 } | |
8267 | |
8268 private: | |
8269 /// a (hopefully) large enough character buffer | |
8270 std::array < char, 64 > m_buf{{}}; | |
8271 | |
8272 template<typename NumberType> | |
8273 void x_write(NumberType x, /*is_integral=*/std::true_type) | |
8274 { | |
8275 // special case for "0" | |
8276 if (x == 0) | |
8277 { | |
8278 m_buf[0] = '0'; | |
8279 return; | |
8280 } | |
8281 | |
8282 const bool is_negative = x < 0; | |
8283 size_t i = 0; | |
8284 | |
8285 // spare 1 byte for '\0' | |
8286 while (x != 0 and i < m_buf.size() - 1) | |
8287 { | |
8288 const auto digit = std::labs(static_cast<long>(x % 10)); | |
8289 m_buf[i++] = static_cast<char>('0' + digit); | |
8290 x /= 10; | |
8291 } | |
8292 | |
8293 // make sure the number has been processed completely | |
8294 assert(x == 0); | |
8295 | |
8296 if (is_negative) | |
8297 { | |
8298 // make sure there is capacity for the '-' | |
8299 assert(i < m_buf.size() - 2); | |
8300 m_buf[i++] = '-'; | |
8301 } | |
8302 | |
8303 std::reverse(m_buf.begin(), m_buf.begin() + i); | |
8304 } | |
8305 | |
8306 template<typename NumberType> | |
8307 void x_write(NumberType x, /*is_integral=*/std::false_type) | |
8308 { | |
8309 // special case for 0.0 and -0.0 | |
8310 if (x == 0) | |
8311 { | |
8312 size_t i = 0; | |
8313 if (std::signbit(x)) | |
8314 { | |
8315 m_buf[i++] = '-'; | |
8316 } | |
8317 m_buf[i++] = '0'; | |
8318 m_buf[i++] = '.'; | |
8319 m_buf[i] = '0'; | |
8320 return; | |
8321 } | |
8322 | |
8323 // get number of digits for a text -> float -> text round-trip | |
8324 static constexpr auto d = std::numeric_limits<NumberType>::digits10; | |
8325 | |
8326 // the actual conversion | |
8327 const auto written_bytes = snprintf(m_buf.data(), m_buf.size(), "%.*g", d, x); | |
8328 | |
8329 // negative value indicates an error | |
8330 assert(written_bytes > 0); | |
8331 // check if buffer was large enough | |
8332 assert(static_cast<size_t>(written_bytes) < m_buf.size()); | |
8333 | |
8334 // read information from locale | |
8335 const auto loc = localeconv(); | |
8336 assert(loc != nullptr); | |
8337 const char thousands_sep = !loc->thousands_sep ? '\0' | |
8338 : loc->thousands_sep[0]; | |
8339 | |
8340 const char decimal_point = !loc->decimal_point ? '\0' | |
8341 : loc->decimal_point[0]; | |
8342 | |
8343 // erase thousands separator | |
8344 if (thousands_sep != '\0') | |
8345 { | |
8346 const auto end = std::remove(m_buf.begin(), m_buf.begin() + written_bytes, thousands_sep); | |
8347 std::fill(end, m_buf.end(), '\0'); | |
8348 } | |
8349 | |
8350 // convert decimal point to '.' | |
8351 if (decimal_point != '\0' and decimal_point != '.') | |
8352 { | |
8353 for (auto& c : m_buf) | |
8354 { | |
8355 if (c == decimal_point) | |
8356 { | |
8357 c = '.'; | |
8358 break; | |
8359 } | |
8360 } | |
8361 } | |
8362 | |
8363 // determine if need to append ".0" | |
8364 size_t i = 0; | |
8365 bool value_is_int_like = true; | |
8366 for (i = 0; i < m_buf.size(); ++i) | |
8367 { | |
8368 // break when end of number is reached | |
8369 if (m_buf[i] == '\0') | |
8370 { | |
8371 break; | |
8372 } | |
8373 | |
8374 // check if we find non-int character | |
8375 value_is_int_like = value_is_int_like and m_buf[i] != '.' and | |
8376 m_buf[i] != 'e' and m_buf[i] != 'E'; | |
8377 } | |
8378 | |
8379 if (value_is_int_like) | |
8380 { | |
8381 // there must be 2 bytes left for ".0" | |
8382 assert((i + 2) < m_buf.size()); | |
8383 // we write to the end of the number | |
8384 assert(m_buf[i] == '\0'); | |
8385 assert(m_buf[i - 1] != '\0'); | |
8386 | |
8387 // add ".0" | |
8388 m_buf[i] = '.'; | |
8389 m_buf[i + 1] = '0'; | |
8390 | |
8391 // the resulting string is properly terminated | |
8392 assert(m_buf[i + 2] == '\0'); | |
8393 } | |
8394 } | |
8395 }; | |
8396 | |
8397 | |
8398 /*! | |
8399 @brief internal implementation of the serialization function | |
8400 | |
8401 This function is called by the public member function dump and organizes | |
8402 the serialization internally. The indentation level is propagated as | |
8403 additional parameter. In case of arrays and objects, the function is | |
8404 called recursively. Note that | |
8405 | |
8406 - strings and object keys are escaped using `escape_string()` | |
8407 - integer numbers are converted implicitly via `operator<<` | |
8408 - floating-point numbers are converted to a string using `"%g"` format | |
8409 | |
8410 @param[out] o stream to write to | |
8411 @param[in] pretty_print whether the output shall be pretty-printed | |
8412 @param[in] indent_step the indent level | |
8413 @param[in] current_indent the current indent level (only used internally) | |
8414 */ | |
8415 void dump(std::ostream& o, | |
8416 const bool pretty_print, | |
8417 const unsigned int indent_step, | |
8418 const unsigned int current_indent = 0) const | |
8419 { | |
8420 // variable to hold indentation for recursive calls | |
8421 unsigned int new_indent = current_indent; | |
8422 | |
8423 switch (m_type) | |
8424 { | |
8425 case value_t::object: | |
8426 { | |
8427 if (m_value.object->empty()) | |
8428 { | |
8429 o << "{}"; | |
8430 return; | |
8431 } | |
8432 | |
8433 o << "{"; | |
8434 | |
8435 // increase indentation | |
8436 if (pretty_print) | |
8437 { | |
8438 new_indent += indent_step; | |
8439 o << "\n"; | |
8440 } | |
8441 | |
8442 for (auto i = m_value.object->cbegin(); i != m_value.object->cend(); ++i) | |
8443 { | |
8444 if (i != m_value.object->cbegin()) | |
8445 { | |
8446 o << (pretty_print ? ",\n" : ","); | |
8447 } | |
8448 o << string_t(new_indent, ' ') << "\"" | |
8449 << escape_string(i->first) << "\":" | |
8450 << (pretty_print ? " " : ""); | |
8451 i->second.dump(o, pretty_print, indent_step, new_indent); | |
8452 } | |
8453 | |
8454 // decrease indentation | |
8455 if (pretty_print) | |
8456 { | |
8457 new_indent -= indent_step; | |
8458 o << "\n"; | |
8459 } | |
8460 | |
8461 o << string_t(new_indent, ' ') + "}"; | |
8462 return; | |
8463 } | |
8464 | |
8465 case value_t::array: | |
8466 { | |
8467 if (m_value.array->empty()) | |
8468 { | |
8469 o << "[]"; | |
8470 return; | |
8471 } | |
8472 | |
8473 o << "["; | |
8474 | |
8475 // increase indentation | |
8476 if (pretty_print) | |
8477 { | |
8478 new_indent += indent_step; | |
8479 o << "\n"; | |
8480 } | |
8481 | |
8482 for (auto i = m_value.array->cbegin(); i != m_value.array->cend(); ++i) | |
8483 { | |
8484 if (i != m_value.array->cbegin()) | |
8485 { | |
8486 o << (pretty_print ? ",\n" : ","); | |
8487 } | |
8488 o << string_t(new_indent, ' '); | |
8489 i->dump(o, pretty_print, indent_step, new_indent); | |
8490 } | |
8491 | |
8492 // decrease indentation | |
8493 if (pretty_print) | |
8494 { | |
8495 new_indent -= indent_step; | |
8496 o << "\n"; | |
8497 } | |
8498 | |
8499 o << string_t(new_indent, ' ') << "]"; | |
8500 return; | |
8501 } | |
8502 | |
8503 case value_t::string: | |
8504 { | |
8505 o << string_t("\"") << escape_string(*m_value.string) << "\""; | |
8506 return; | |
8507 } | |
8508 | |
8509 case value_t::boolean: | |
8510 { | |
8511 o << (m_value.boolean ? "true" : "false"); | |
8512 return; | |
8513 } | |
8514 | |
8515 case value_t::number_integer: | |
8516 { | |
8517 o << numtostr(m_value.number_integer).c_str(); | |
8518 return; | |
8519 } | |
8520 | |
8521 case value_t::number_unsigned: | |
8522 { | |
8523 o << numtostr(m_value.number_unsigned).c_str(); | |
8524 return; | |
8525 } | |
8526 | |
8527 case value_t::number_float: | |
8528 { | |
8529 o << numtostr(m_value.number_float).c_str(); | |
8530 return; | |
8531 } | |
8532 | |
8533 case value_t::discarded: | |
8534 { | |
8535 o << "<discarded>"; | |
8536 return; | |
8537 } | |
8538 | |
8539 case value_t::null: | |
8540 { | |
8541 o << "null"; | |
8542 return; | |
8543 } | |
8544 } | |
8545 } | |
8546 | 15809 |
8547 private: | 15810 private: |
8548 ////////////////////// | 15811 ////////////////////// |
8549 // member variables // | 15812 // member variables // |
8550 ////////////////////// | 15813 ////////////////////// |
8553 value_t m_type = value_t::null; | 15816 value_t m_type = value_t::null; |
8554 | 15817 |
8555 /// the value of the current element | 15818 /// the value of the current element |
8556 json_value m_value = {}; | 15819 json_value m_value = {}; |
8557 | 15820 |
8558 | 15821 ////////////////////////////////////////// |
8559 private: | 15822 // binary serialization/deserialization // |
8560 /////////////// | 15823 ////////////////////////////////////////// |
8561 // iterators // | 15824 |
8562 /////////////// | 15825 /// @name binary serialization/deserialization support |
8563 | 15826 /// @{ |
8564 /*! | |
8565 @brief an iterator for primitive JSON types | |
8566 | |
8567 This class models an iterator for primitive JSON types (boolean, number, | |
8568 string). It's only purpose is to allow the iterator/const_iterator classes | |
8569 to "iterate" over primitive values. Internally, the iterator is modeled by | |
8570 a `difference_type` variable. Value begin_value (`0`) models the begin, | |
8571 end_value (`1`) models past the end. | |
8572 */ | |
8573 class primitive_iterator_t | |
8574 { | |
8575 public: | |
8576 | |
8577 difference_type get_value() const noexcept | |
8578 { | |
8579 return m_it; | |
8580 } | |
8581 /// set iterator to a defined beginning | |
8582 void set_begin() noexcept | |
8583 { | |
8584 m_it = begin_value; | |
8585 } | |
8586 | |
8587 /// set iterator to a defined past the end | |
8588 void set_end() noexcept | |
8589 { | |
8590 m_it = end_value; | |
8591 } | |
8592 | |
8593 /// return whether the iterator can be dereferenced | |
8594 constexpr bool is_begin() const noexcept | |
8595 { | |
8596 return (m_it == begin_value); | |
8597 } | |
8598 | |
8599 /// return whether the iterator is at end | |
8600 constexpr bool is_end() const noexcept | |
8601 { | |
8602 return (m_it == end_value); | |
8603 } | |
8604 | |
8605 friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept | |
8606 { | |
8607 return lhs.m_it == rhs.m_it; | |
8608 } | |
8609 | |
8610 friend constexpr bool operator!=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept | |
8611 { | |
8612 return !(lhs == rhs); | |
8613 } | |
8614 | |
8615 friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept | |
8616 { | |
8617 return lhs.m_it < rhs.m_it; | |
8618 } | |
8619 | |
8620 friend constexpr bool operator<=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept | |
8621 { | |
8622 return lhs.m_it <= rhs.m_it; | |
8623 } | |
8624 | |
8625 friend constexpr bool operator>(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept | |
8626 { | |
8627 return lhs.m_it > rhs.m_it; | |
8628 } | |
8629 | |
8630 friend constexpr bool operator>=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept | |
8631 { | |
8632 return lhs.m_it >= rhs.m_it; | |
8633 } | |
8634 | |
8635 primitive_iterator_t operator+(difference_type i) | |
8636 { | |
8637 auto result = *this; | |
8638 result += i; | |
8639 return result; | |
8640 } | |
8641 | |
8642 friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept | |
8643 { | |
8644 return lhs.m_it - rhs.m_it; | |
8645 } | |
8646 | |
8647 friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it) | |
8648 { | |
8649 return os << it.m_it; | |
8650 } | |
8651 | |
8652 primitive_iterator_t& operator++() | |
8653 { | |
8654 ++m_it; | |
8655 return *this; | |
8656 } | |
8657 | |
8658 primitive_iterator_t operator++(int) | |
8659 { | |
8660 auto result = *this; | |
8661 m_it++; | |
8662 return result; | |
8663 } | |
8664 | |
8665 primitive_iterator_t& operator--() | |
8666 { | |
8667 --m_it; | |
8668 return *this; | |
8669 } | |
8670 | |
8671 primitive_iterator_t operator--(int) | |
8672 { | |
8673 auto result = *this; | |
8674 m_it--; | |
8675 return result; | |
8676 } | |
8677 | |
8678 primitive_iterator_t& operator+=(difference_type n) | |
8679 { | |
8680 m_it += n; | |
8681 return *this; | |
8682 } | |
8683 | |
8684 primitive_iterator_t& operator-=(difference_type n) | |
8685 { | |
8686 m_it -= n; | |
8687 return *this; | |
8688 } | |
8689 | |
8690 private: | |
8691 static constexpr difference_type begin_value = 0; | |
8692 static constexpr difference_type end_value = begin_value + 1; | |
8693 | |
8694 /// iterator as signed integer type | |
8695 difference_type m_it = std::numeric_limits<std::ptrdiff_t>::denorm_min(); | |
8696 }; | |
8697 | |
8698 /*! | |
8699 @brief an iterator value | |
8700 | |
8701 @note This structure could easily be a union, but MSVC currently does not | |
8702 allow unions members with complex constructors, see | |
8703 https://github.com/nlohmann/json/pull/105. | |
8704 */ | |
8705 struct internal_iterator | |
8706 { | |
8707 /// iterator for JSON objects | |
8708 typename object_t::iterator object_iterator; | |
8709 /// iterator for JSON arrays | |
8710 typename array_t::iterator array_iterator; | |
8711 /// generic iterator for all other types | |
8712 primitive_iterator_t primitive_iterator; | |
8713 | |
8714 /// create an uninitialized internal_iterator | |
8715 internal_iterator() noexcept | |
8716 : object_iterator(), array_iterator(), primitive_iterator() | |
8717 {} | |
8718 }; | |
8719 | |
8720 /// proxy class for the iterator_wrapper functions | |
8721 template<typename IteratorType> | |
8722 class iteration_proxy | |
8723 { | |
8724 private: | |
8725 /// helper class for iteration | |
8726 class iteration_proxy_internal | |
8727 { | |
8728 private: | |
8729 /// the iterator | |
8730 IteratorType anchor; | |
8731 /// an index for arrays (used to create key names) | |
8732 size_t array_index = 0; | |
8733 | |
8734 public: | |
8735 explicit iteration_proxy_internal(IteratorType it) noexcept | |
8736 : anchor(it) | |
8737 {} | |
8738 | |
8739 /// dereference operator (needed for range-based for) | |
8740 iteration_proxy_internal& operator*() | |
8741 { | |
8742 return *this; | |
8743 } | |
8744 | |
8745 /// increment operator (needed for range-based for) | |
8746 iteration_proxy_internal& operator++() | |
8747 { | |
8748 ++anchor; | |
8749 ++array_index; | |
8750 | |
8751 return *this; | |
8752 } | |
8753 | |
8754 /// inequality operator (needed for range-based for) | |
8755 bool operator!= (const iteration_proxy_internal& o) const | |
8756 { | |
8757 return anchor != o.anchor; | |
8758 } | |
8759 | |
8760 /// return key of the iterator | |
8761 typename basic_json::string_t key() const | |
8762 { | |
8763 assert(anchor.m_object != nullptr); | |
8764 | |
8765 switch (anchor.m_object->type()) | |
8766 { | |
8767 // use integer array index as key | |
8768 case value_t::array: | |
8769 { | |
8770 return std::to_string(array_index); | |
8771 } | |
8772 | |
8773 // use key from the object | |
8774 case value_t::object: | |
8775 { | |
8776 return anchor.key(); | |
8777 } | |
8778 | |
8779 // use an empty key for all primitive types | |
8780 default: | |
8781 { | |
8782 return ""; | |
8783 } | |
8784 } | |
8785 } | |
8786 | |
8787 /// return value of the iterator | |
8788 typename IteratorType::reference value() const | |
8789 { | |
8790 return anchor.value(); | |
8791 } | |
8792 }; | |
8793 | |
8794 /// the container to iterate | |
8795 typename IteratorType::reference container; | |
8796 | |
8797 public: | |
8798 /// construct iteration proxy from a container | |
8799 explicit iteration_proxy(typename IteratorType::reference cont) | |
8800 : container(cont) | |
8801 {} | |
8802 | |
8803 /// return iterator begin (needed for range-based for) | |
8804 iteration_proxy_internal begin() noexcept | |
8805 { | |
8806 return iteration_proxy_internal(container.begin()); | |
8807 } | |
8808 | |
8809 /// return iterator end (needed for range-based for) | |
8810 iteration_proxy_internal end() noexcept | |
8811 { | |
8812 return iteration_proxy_internal(container.end()); | |
8813 } | |
8814 }; | |
8815 | 15827 |
8816 public: | 15828 public: |
8817 /*! | 15829 /*! |
8818 @brief a template for a random access iterator for the @ref basic_json class | 15830 @brief create a CBOR serialization of a given JSON value |
8819 | 15831 |
8820 This class implements a both iterators (iterator and const_iterator) for the | 15832 Serializes a given JSON value @a j to a byte vector using the CBOR (Concise |
8821 @ref basic_json class. | 15833 Binary Object Representation) serialization format. CBOR is a binary |
8822 | 15834 serialization format which aims to be more compact than JSON itself, yet |
8823 @note An iterator is called *initialized* when a pointer to a JSON value | 15835 more efficient to parse. |
8824 has been set (e.g., by a constructor or a copy assignment). If the | 15836 |
8825 iterator is default-constructed, it is *uninitialized* and most | 15837 The library uses the following mapping from JSON values types to |
8826 methods are undefined. **The library uses assertions to detect calls | 15838 CBOR types according to the CBOR specification (RFC 7049): |
8827 on uninitialized iterators.** | 15839 |
8828 | 15840 JSON value type | value/range | CBOR type | first byte |
8829 @requirement The class satisfies the following concept requirements: | 15841 --------------- | ------------------------------------------ | ---------------------------------- | --------------- |
8830 - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator): | 15842 null | `null` | Null | 0xF6 |
8831 The iterator that can be moved to point (forward and backward) to any | 15843 boolean | `true` | True | 0xF5 |
8832 element in constant time. | 15844 boolean | `false` | False | 0xF4 |
8833 | 15845 number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B |
8834 @since version 1.0.0, simplified in version 2.0.9 | 15846 number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A |
8835 */ | 15847 number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39 |
8836 template<typename U> | 15848 number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38 |
8837 class iter_impl : public std::iterator<std::random_access_iterator_tag, U> | 15849 number_integer | -24..-1 | Negative integer | 0x20..0x37 |
8838 { | 15850 number_integer | 0..23 | Integer | 0x00..0x17 |
8839 /// allow basic_json to access private members | 15851 number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18 |
8840 friend class basic_json; | 15852 number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 |
8841 | 15853 number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A |
8842 // make sure U is basic_json or const basic_json | 15854 number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B |
8843 static_assert(std::is_same<U, basic_json>::value | 15855 number_unsigned | 0..23 | Integer | 0x00..0x17 |
8844 or std::is_same<U, const basic_json>::value, | 15856 number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18 |
8845 "iter_impl only accepts (const) basic_json"); | 15857 number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 |
8846 | 15858 number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A |
8847 public: | 15859 number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B |
8848 /// the type of the values when the iterator is dereferenced | 15860 number_float | *any value* | Double-Precision Float | 0xFB |
8849 using value_type = typename basic_json::value_type; | 15861 string | *length*: 0..23 | UTF-8 string | 0x60..0x77 |
8850 /// a type to represent differences between iterators | 15862 string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78 |
8851 using difference_type = typename basic_json::difference_type; | 15863 string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79 |
8852 /// defines a pointer to the type iterated over (value_type) | 15864 string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A |
8853 using pointer = typename std::conditional<std::is_const<U>::value, | 15865 string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B |
8854 typename basic_json::const_pointer, | 15866 array | *size*: 0..23 | array | 0x80..0x97 |
8855 typename basic_json::pointer>::type; | 15867 array | *size*: 23..255 | array (1 byte follow) | 0x98 |
8856 /// defines a reference to the type iterated over (value_type) | 15868 array | *size*: 256..65535 | array (2 bytes follow) | 0x99 |
8857 using reference = typename std::conditional<std::is_const<U>::value, | 15869 array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A |
8858 typename basic_json::const_reference, | 15870 array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B |
8859 typename basic_json::reference>::type; | 15871 object | *size*: 0..23 | map | 0xA0..0xB7 |
8860 /// the category of the iterator | 15872 object | *size*: 23..255 | map (1 byte follow) | 0xB8 |
8861 using iterator_category = std::bidirectional_iterator_tag; | 15873 object | *size*: 256..65535 | map (2 bytes follow) | 0xB9 |
8862 | 15874 object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA |
8863 /// default constructor | 15875 object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB |
8864 iter_impl() = default; | 15876 |
8865 | 15877 @note The mapping is **complete** in the sense that any JSON value type |
8866 /*! | 15878 can be converted to a CBOR value. |
8867 @brief constructor for a given JSON instance | 15879 |
8868 @param[in] object pointer to a JSON object for this iterator | 15880 @note If NaN or Infinity are stored inside a JSON number, they are |
8869 @pre object != nullptr | 15881 serialized properly. This behavior differs from the @ref dump() |
8870 @post The iterator is initialized; i.e. `m_object != nullptr`. | 15882 function which serializes NaN or Infinity to `null`. |
8871 */ | 15883 |
8872 explicit iter_impl(pointer object) noexcept | 15884 @note The following CBOR types are not used in the conversion: |
8873 : m_object(object) | 15885 - byte strings (0x40..0x5F) |
8874 { | 15886 - UTF-8 strings terminated by "break" (0x7F) |
8875 assert(m_object != nullptr); | 15887 - arrays terminated by "break" (0x9F) |
8876 | 15888 - maps terminated by "break" (0xBF) |
8877 switch (m_object->m_type) | 15889 - date/time (0xC0..0xC1) |
8878 { | 15890 - bignum (0xC2..0xC3) |
8879 case basic_json::value_t::object: | 15891 - decimal fraction (0xC4) |
8880 { | 15892 - bigfloat (0xC5) |
8881 m_it.object_iterator = typename object_t::iterator(); | 15893 - tagged items (0xC6..0xD4, 0xD8..0xDB) |
8882 break; | 15894 - expected conversions (0xD5..0xD7) |
8883 } | 15895 - simple values (0xE0..0xF3, 0xF8) |
8884 | 15896 - undefined (0xF7) |
8885 case basic_json::value_t::array: | 15897 - half and single-precision floats (0xF9-0xFA) |
8886 { | 15898 - break (0xFF) |
8887 m_it.array_iterator = typename array_t::iterator(); | 15899 |
8888 break; | 15900 @param[in] j JSON value to serialize |
8889 } | 15901 @return MessagePack serialization as byte vector |
8890 | 15902 |
8891 default: | 15903 @complexity Linear in the size of the JSON value @a j. |
8892 { | 15904 |
8893 m_it.primitive_iterator = primitive_iterator_t(); | 15905 @liveexample{The example shows the serialization of a JSON value to a byte |
8894 break; | 15906 vector in CBOR format.,to_cbor} |
8895 } | 15907 |
8896 } | 15908 @sa http://cbor.io |
8897 } | 15909 @sa @ref from_cbor(detail::input_adapter, const bool strict) for the |
8898 | 15910 analogous deserialization |
8899 /* | 15911 @sa @ref to_msgpack(const basic_json&) for the related MessagePack format |
8900 Use operator `const_iterator` instead of `const_iterator(const iterator& | 15912 @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the |
8901 other) noexcept` to avoid two class definitions for @ref iterator and | 15913 related UBJSON format |
8902 @ref const_iterator. | 15914 |
8903 | 15915 @since version 2.0.9 |
8904 This function is only called if this class is an @ref iterator. If this | 15916 */ |
8905 class is a @ref const_iterator this function is not called. | 15917 static std::vector<uint8_t> to_cbor(const basic_json& j) |
8906 */ | 15918 { |
8907 operator const_iterator() const | 15919 std::vector<uint8_t> result; |
8908 { | 15920 to_cbor(j, result); |
8909 const_iterator ret; | 15921 return result; |
8910 | 15922 } |
8911 if (m_object) | 15923 |
8912 { | 15924 static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o) |
8913 ret.m_object = m_object; | 15925 { |
8914 ret.m_it = m_it; | 15926 binary_writer<uint8_t>(o).write_cbor(j); |
8915 } | 15927 } |
8916 | 15928 |
8917 return ret; | 15929 static void to_cbor(const basic_json& j, detail::output_adapter<char> o) |
8918 } | 15930 { |
8919 | 15931 binary_writer<char>(o).write_cbor(j); |
8920 /*! | 15932 } |
8921 @brief copy constructor | 15933 |
8922 @param[in] other iterator to copy from | 15934 /*! |
8923 @note It is not checked whether @a other is initialized. | 15935 @brief create a MessagePack serialization of a given JSON value |
8924 */ | 15936 |
8925 iter_impl(const iter_impl& other) noexcept | 15937 Serializes a given JSON value @a j to a byte vector using the MessagePack |
8926 : m_object(other.m_object), m_it(other.m_it) | 15938 serialization format. MessagePack is a binary serialization format which |
8927 {} | 15939 aims to be more compact than JSON itself, yet more efficient to parse. |
8928 | 15940 |
8929 /*! | 15941 The library uses the following mapping from JSON values types to |
8930 @brief copy assignment | 15942 MessagePack types according to the MessagePack specification: |
8931 @param[in,out] other iterator to copy from | 15943 |
8932 @note It is not checked whether @a other is initialized. | 15944 JSON value type | value/range | MessagePack type | first byte |
8933 */ | 15945 --------------- | --------------------------------- | ---------------- | ---------- |
8934 iter_impl& operator=(iter_impl other) noexcept( | 15946 null | `null` | nil | 0xC0 |
8935 std::is_nothrow_move_constructible<pointer>::value and | 15947 boolean | `true` | true | 0xC3 |
8936 std::is_nothrow_move_assignable<pointer>::value and | 15948 boolean | `false` | false | 0xC2 |
8937 std::is_nothrow_move_constructible<internal_iterator>::value and | 15949 number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3 |
8938 std::is_nothrow_move_assignable<internal_iterator>::value | 15950 number_integer | -2147483648..-32769 | int32 | 0xD2 |
8939 ) | 15951 number_integer | -32768..-129 | int16 | 0xD1 |
8940 { | 15952 number_integer | -128..-33 | int8 | 0xD0 |
8941 std::swap(m_object, other.m_object); | 15953 number_integer | -32..-1 | negative fixint | 0xE0..0xFF |
8942 std::swap(m_it, other.m_it); | 15954 number_integer | 0..127 | positive fixint | 0x00..0x7F |
8943 return *this; | 15955 number_integer | 128..255 | uint 8 | 0xCC |
8944 } | 15956 number_integer | 256..65535 | uint 16 | 0xCD |
8945 | 15957 number_integer | 65536..4294967295 | uint 32 | 0xCE |
8946 private: | 15958 number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF |
8947 /*! | 15959 number_unsigned | 0..127 | positive fixint | 0x00..0x7F |
8948 @brief set the iterator to the first value | 15960 number_unsigned | 128..255 | uint 8 | 0xCC |
8949 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 15961 number_unsigned | 256..65535 | uint 16 | 0xCD |
8950 */ | 15962 number_unsigned | 65536..4294967295 | uint 32 | 0xCE |
8951 void set_begin() noexcept | 15963 number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF |
8952 { | 15964 number_float | *any value* | float 64 | 0xCB |
8953 assert(m_object != nullptr); | 15965 string | *length*: 0..31 | fixstr | 0xA0..0xBF |
8954 | 15966 string | *length*: 32..255 | str 8 | 0xD9 |
8955 switch (m_object->m_type) | 15967 string | *length*: 256..65535 | str 16 | 0xDA |
8956 { | 15968 string | *length*: 65536..4294967295 | str 32 | 0xDB |
8957 case basic_json::value_t::object: | 15969 array | *size*: 0..15 | fixarray | 0x90..0x9F |
8958 { | 15970 array | *size*: 16..65535 | array 16 | 0xDC |
8959 m_it.object_iterator = m_object->m_value.object->begin(); | 15971 array | *size*: 65536..4294967295 | array 32 | 0xDD |
8960 break; | 15972 object | *size*: 0..15 | fix map | 0x80..0x8F |
8961 } | 15973 object | *size*: 16..65535 | map 16 | 0xDE |
8962 | 15974 object | *size*: 65536..4294967295 | map 32 | 0xDF |
8963 case basic_json::value_t::array: | 15975 |
8964 { | 15976 @note The mapping is **complete** in the sense that any JSON value type |
8965 m_it.array_iterator = m_object->m_value.array->begin(); | 15977 can be converted to a MessagePack value. |
8966 break; | 15978 |
8967 } | 15979 @note The following values can **not** be converted to a MessagePack value: |
8968 | 15980 - strings with more than 4294967295 bytes |
8969 case basic_json::value_t::null: | 15981 - arrays with more than 4294967295 elements |
8970 { | 15982 - objects with more than 4294967295 elements |
8971 // set to end so begin()==end() is true: null is empty | 15983 |
8972 m_it.primitive_iterator.set_end(); | 15984 @note The following MessagePack types are not used in the conversion: |
8973 break; | 15985 - bin 8 - bin 32 (0xC4..0xC6) |
8974 } | 15986 - ext 8 - ext 32 (0xC7..0xC9) |
8975 | 15987 - float 32 (0xCA) |
8976 default: | 15988 - fixext 1 - fixext 16 (0xD4..0xD8) |
8977 { | 15989 |
8978 m_it.primitive_iterator.set_begin(); | 15990 @note Any MessagePack output created @ref to_msgpack can be successfully |
8979 break; | 15991 parsed by @ref from_msgpack. |
8980 } | 15992 |
8981 } | 15993 @note If NaN or Infinity are stored inside a JSON number, they are |
8982 } | 15994 serialized properly. This behavior differs from the @ref dump() |
8983 | 15995 function which serializes NaN or Infinity to `null`. |
8984 /*! | 15996 |
8985 @brief set the iterator past the last value | 15997 @param[in] j JSON value to serialize |
8986 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 15998 @return MessagePack serialization as byte vector |
8987 */ | 15999 |
8988 void set_end() noexcept | 16000 @complexity Linear in the size of the JSON value @a j. |
8989 { | 16001 |
8990 assert(m_object != nullptr); | 16002 @liveexample{The example shows the serialization of a JSON value to a byte |
8991 | 16003 vector in MessagePack format.,to_msgpack} |
8992 switch (m_object->m_type) | 16004 |
8993 { | 16005 @sa http://msgpack.org |
8994 case basic_json::value_t::object: | 16006 @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the |
8995 { | 16007 analogous deserialization |
8996 m_it.object_iterator = m_object->m_value.object->end(); | 16008 @sa @ref to_cbor(const basic_json& for the related CBOR format |
8997 break; | 16009 @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the |
8998 } | 16010 related UBJSON format |
8999 | 16011 |
9000 case basic_json::value_t::array: | 16012 @since version 2.0.9 |
9001 { | 16013 */ |
9002 m_it.array_iterator = m_object->m_value.array->end(); | 16014 static std::vector<uint8_t> to_msgpack(const basic_json& j) |
9003 break; | 16015 { |
9004 } | 16016 std::vector<uint8_t> result; |
9005 | 16017 to_msgpack(j, result); |
9006 default: | 16018 return result; |
9007 { | 16019 } |
9008 m_it.primitive_iterator.set_end(); | 16020 |
9009 break; | 16021 static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o) |
9010 } | 16022 { |
9011 } | 16023 binary_writer<uint8_t>(o).write_msgpack(j); |
9012 } | 16024 } |
9013 | 16025 |
9014 public: | 16026 static void to_msgpack(const basic_json& j, detail::output_adapter<char> o) |
9015 /*! | 16027 { |
9016 @brief return a reference to the value pointed to by the iterator | 16028 binary_writer<char>(o).write_msgpack(j); |
9017 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16029 } |
9018 */ | 16030 |
9019 reference operator*() const | 16031 /*! |
9020 { | 16032 @brief create a UBJSON serialization of a given JSON value |
9021 assert(m_object != nullptr); | 16033 |
9022 | 16034 Serializes a given JSON value @a j to a byte vector using the UBJSON |
9023 switch (m_object->m_type) | 16035 (Universal Binary JSON) serialization format. UBJSON aims to be more compact |
9024 { | 16036 than JSON itself, yet more efficient to parse. |
9025 case basic_json::value_t::object: | 16037 |
9026 { | 16038 The library uses the following mapping from JSON values types to |
9027 assert(m_it.object_iterator != m_object->m_value.object->end()); | 16039 UBJSON types according to the UBJSON specification: |
9028 return m_it.object_iterator->second; | 16040 |
9029 } | 16041 JSON value type | value/range | UBJSON type | marker |
9030 | 16042 --------------- | --------------------------------- | ----------- | ------ |
9031 case basic_json::value_t::array: | 16043 null | `null` | null | `Z` |
9032 { | 16044 boolean | `true` | true | `T` |
9033 assert(m_it.array_iterator != m_object->m_value.array->end()); | 16045 boolean | `false` | false | `F` |
9034 return *m_it.array_iterator; | 16046 number_integer | -9223372036854775808..-2147483649 | int64 | `L` |
9035 } | 16047 number_integer | -2147483648..-32769 | int32 | `l` |
9036 | 16048 number_integer | -32768..-129 | int16 | `I` |
9037 case basic_json::value_t::null: | 16049 number_integer | -128..127 | int8 | `i` |
9038 { | 16050 number_integer | 128..255 | uint8 | `U` |
9039 JSON_THROW(std::out_of_range("cannot get value")); | 16051 number_integer | 256..32767 | int16 | `I` |
9040 } | 16052 number_integer | 32768..2147483647 | int32 | `l` |
9041 | 16053 number_integer | 2147483648..9223372036854775807 | int64 | `L` |
9042 default: | 16054 number_unsigned | 0..127 | int8 | `i` |
9043 { | 16055 number_unsigned | 128..255 | uint8 | `U` |
9044 if (m_it.primitive_iterator.is_begin()) | 16056 number_unsigned | 256..32767 | int16 | `I` |
9045 { | 16057 number_unsigned | 32768..2147483647 | int32 | `l` |
9046 return *m_object; | 16058 number_unsigned | 2147483648..9223372036854775807 | int64 | `L` |
9047 } | 16059 number_float | *any value* | float64 | `D` |
9048 | 16060 string | *with shortest length indicator* | string | `S` |
9049 JSON_THROW(std::out_of_range("cannot get value")); | 16061 array | *see notes on optimized format* | array | `[` |
9050 } | 16062 object | *see notes on optimized format* | map | `{` |
9051 } | 16063 |
9052 } | 16064 @note The mapping is **complete** in the sense that any JSON value type |
9053 | 16065 can be converted to a UBJSON value. |
9054 /*! | 16066 |
9055 @brief dereference the iterator | 16067 @note The following values can **not** be converted to a UBJSON value: |
9056 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16068 - strings with more than 9223372036854775807 bytes (theoretical) |
9057 */ | 16069 - unsigned integer numbers above 9223372036854775807 |
9058 pointer operator->() const | 16070 |
9059 { | 16071 @note The following markers are not used in the conversion: |
9060 assert(m_object != nullptr); | 16072 - `Z`: no-op values are not created. |
9061 | 16073 - `C`: single-byte strings are serialized with `S` markers. |
9062 switch (m_object->m_type) | 16074 |
9063 { | 16075 @note Any UBJSON output created @ref to_ubjson can be successfully parsed |
9064 case basic_json::value_t::object: | 16076 by @ref from_ubjson. |
9065 { | 16077 |
9066 assert(m_it.object_iterator != m_object->m_value.object->end()); | 16078 @note If NaN or Infinity are stored inside a JSON number, they are |
9067 return &(m_it.object_iterator->second); | 16079 serialized properly. This behavior differs from the @ref dump() |
9068 } | 16080 function which serializes NaN or Infinity to `null`. |
9069 | 16081 |
9070 case basic_json::value_t::array: | 16082 @note The optimized formats for containers are supported: Parameter |
9071 { | 16083 @a use_size adds size information to the beginning of a container and |
9072 assert(m_it.array_iterator != m_object->m_value.array->end()); | 16084 removes the closing marker. Parameter @a use_type further checks |
9073 return &*m_it.array_iterator; | 16085 whether all elements of a container have the same type and adds the |
9074 } | 16086 type marker to the beginning of the container. The @a use_type |
9075 | 16087 parameter must only be used together with @a use_size = true. Note |
9076 default: | 16088 that @a use_size = true alone may result in larger representations - |
9077 { | 16089 the benefit of this parameter is that the receiving side is |
9078 if (m_it.primitive_iterator.is_begin()) | 16090 immediately informed on the number of elements of the container. |
9079 { | 16091 |
9080 return m_object; | 16092 @param[in] j JSON value to serialize |
9081 } | 16093 @param[in] use_size whether to add size annotations to container types |
9082 | 16094 @param[in] use_type whether to add type annotations to container types |
9083 JSON_THROW(std::out_of_range("cannot get value")); | 16095 (must be combined with @a use_size = true) |
9084 } | 16096 @return UBJSON serialization as byte vector |
9085 } | 16097 |
9086 } | 16098 @complexity Linear in the size of the JSON value @a j. |
9087 | 16099 |
9088 /*! | 16100 @liveexample{The example shows the serialization of a JSON value to a byte |
9089 @brief post-increment (it++) | 16101 vector in UBJSON format.,to_ubjson} |
9090 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16102 |
9091 */ | 16103 @sa http://ubjson.org |
9092 iter_impl operator++(int) | 16104 @sa @ref from_ubjson(detail::input_adapter, const bool strict) for the |
9093 { | 16105 analogous deserialization |
9094 auto result = *this; | 16106 @sa @ref to_cbor(const basic_json& for the related CBOR format |
9095 ++(*this); | 16107 @sa @ref to_msgpack(const basic_json&) for the related MessagePack format |
9096 return result; | 16108 |
9097 } | 16109 @since version 3.1.0 |
9098 | 16110 */ |
9099 /*! | 16111 static std::vector<uint8_t> to_ubjson(const basic_json& j, |
9100 @brief pre-increment (++it) | 16112 const bool use_size = false, |
9101 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16113 const bool use_type = false) |
9102 */ | 16114 { |
9103 iter_impl& operator++() | 16115 std::vector<uint8_t> result; |
9104 { | 16116 to_ubjson(j, result, use_size, use_type); |
9105 assert(m_object != nullptr); | 16117 return result; |
9106 | 16118 } |
9107 switch (m_object->m_type) | 16119 |
9108 { | 16120 static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o, |
9109 case basic_json::value_t::object: | 16121 const bool use_size = false, const bool use_type = false) |
9110 { | 16122 { |
9111 std::advance(m_it.object_iterator, 1); | 16123 binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type); |
9112 break; | 16124 } |
9113 } | 16125 |
9114 | 16126 static void to_ubjson(const basic_json& j, detail::output_adapter<char> o, |
9115 case basic_json::value_t::array: | 16127 const bool use_size = false, const bool use_type = false) |
9116 { | 16128 { |
9117 std::advance(m_it.array_iterator, 1); | 16129 binary_writer<char>(o).write_ubjson(j, use_size, use_type); |
9118 break; | 16130 } |
9119 } | 16131 |
9120 | 16132 /*! |
9121 default: | 16133 @brief create a JSON value from an input in CBOR format |
9122 { | 16134 |
9123 ++m_it.primitive_iterator; | 16135 Deserializes a given input @a i to a JSON value using the CBOR (Concise |
9124 break; | 16136 Binary Object Representation) serialization format. |
9125 } | 16137 |
9126 } | 16138 The library maps CBOR types to JSON value types as follows: |
9127 | 16139 |
9128 return *this; | 16140 CBOR type | JSON value type | first byte |
9129 } | 16141 ---------------------- | --------------- | ---------- |
9130 | 16142 Integer | number_unsigned | 0x00..0x17 |
9131 /*! | 16143 Unsigned integer | number_unsigned | 0x18 |
9132 @brief post-decrement (it--) | 16144 Unsigned integer | number_unsigned | 0x19 |
9133 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16145 Unsigned integer | number_unsigned | 0x1A |
9134 */ | 16146 Unsigned integer | number_unsigned | 0x1B |
9135 iter_impl operator--(int) | 16147 Negative integer | number_integer | 0x20..0x37 |
9136 { | 16148 Negative integer | number_integer | 0x38 |
9137 auto result = *this; | 16149 Negative integer | number_integer | 0x39 |
9138 --(*this); | 16150 Negative integer | number_integer | 0x3A |
9139 return result; | 16151 Negative integer | number_integer | 0x3B |
9140 } | 16152 Negative integer | number_integer | 0x40..0x57 |
9141 | 16153 UTF-8 string | string | 0x60..0x77 |
9142 /*! | 16154 UTF-8 string | string | 0x78 |
9143 @brief pre-decrement (--it) | 16155 UTF-8 string | string | 0x79 |
9144 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16156 UTF-8 string | string | 0x7A |
9145 */ | 16157 UTF-8 string | string | 0x7B |
9146 iter_impl& operator--() | 16158 UTF-8 string | string | 0x7F |
9147 { | 16159 array | array | 0x80..0x97 |
9148 assert(m_object != nullptr); | 16160 array | array | 0x98 |
9149 | 16161 array | array | 0x99 |
9150 switch (m_object->m_type) | 16162 array | array | 0x9A |
9151 { | 16163 array | array | 0x9B |
9152 case basic_json::value_t::object: | 16164 array | array | 0x9F |
9153 { | 16165 map | object | 0xA0..0xB7 |
9154 std::advance(m_it.object_iterator, -1); | 16166 map | object | 0xB8 |
9155 break; | 16167 map | object | 0xB9 |
9156 } | 16168 map | object | 0xBA |
9157 | 16169 map | object | 0xBB |
9158 case basic_json::value_t::array: | 16170 map | object | 0xBF |
9159 { | 16171 False | `false` | 0xF4 |
9160 std::advance(m_it.array_iterator, -1); | 16172 True | `true` | 0xF5 |
9161 break; | 16173 Nill | `null` | 0xF6 |
9162 } | 16174 Half-Precision Float | number_float | 0xF9 |
9163 | 16175 Single-Precision Float | number_float | 0xFA |
9164 default: | 16176 Double-Precision Float | number_float | 0xFB |
9165 { | 16177 |
9166 --m_it.primitive_iterator; | 16178 @warning The mapping is **incomplete** in the sense that not all CBOR |
9167 break; | 16179 types can be converted to a JSON value. The following CBOR types |
9168 } | 16180 are not supported and will yield parse errors (parse_error.112): |
9169 } | 16181 - byte strings (0x40..0x5F) |
9170 | 16182 - date/time (0xC0..0xC1) |
9171 return *this; | 16183 - bignum (0xC2..0xC3) |
9172 } | 16184 - decimal fraction (0xC4) |
9173 | 16185 - bigfloat (0xC5) |
9174 /*! | 16186 - tagged items (0xC6..0xD4, 0xD8..0xDB) |
9175 @brief comparison: equal | 16187 - expected conversions (0xD5..0xD7) |
9176 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16188 - simple values (0xE0..0xF3, 0xF8) |
9177 */ | 16189 - undefined (0xF7) |
9178 bool operator==(const iter_impl& other) const | 16190 |
9179 { | 16191 @warning CBOR allows map keys of any type, whereas JSON only allows |
9180 // if objects are not the same, the comparison is undefined | 16192 strings as keys in object values. Therefore, CBOR maps with keys |
9181 if (m_object != other.m_object) | 16193 other than UTF-8 strings are rejected (parse_error.113). |
9182 { | 16194 |
9183 JSON_THROW(std::domain_error("cannot compare iterators of different containers")); | 16195 @note Any CBOR output created @ref to_cbor can be successfully parsed by |
9184 } | 16196 @ref from_cbor. |
9185 | 16197 |
9186 assert(m_object != nullptr); | 16198 @param[in] i an input in CBOR format convertible to an input adapter |
9187 | 16199 @param[in] strict whether to expect the input to be consumed until EOF |
9188 switch (m_object->m_type) | 16200 (true by default) |
9189 { | 16201 @return deserialized JSON value |
9190 case basic_json::value_t::object: | 16202 |
9191 { | 16203 @throw parse_error.110 if the given input ends prematurely or the end of |
9192 return (m_it.object_iterator == other.m_it.object_iterator); | 16204 file was not reached when @a strict was set to true |
9193 } | 16205 @throw parse_error.112 if unsupported features from CBOR were |
9194 | 16206 used in the given input @a v or if the input is not valid CBOR |
9195 case basic_json::value_t::array: | 16207 @throw parse_error.113 if a string was expected as map key, but not found |
9196 { | 16208 |
9197 return (m_it.array_iterator == other.m_it.array_iterator); | 16209 @complexity Linear in the size of the input @a i. |
9198 } | 16210 |
9199 | 16211 @liveexample{The example shows the deserialization of a byte vector in CBOR |
9200 default: | 16212 format to a JSON value.,from_cbor} |
9201 { | 16213 |
9202 return (m_it.primitive_iterator == other.m_it.primitive_iterator); | 16214 @sa http://cbor.io |
9203 } | 16215 @sa @ref to_cbor(const basic_json&) for the analogous serialization |
9204 } | 16216 @sa @ref from_msgpack(detail::input_adapter, const bool) for the |
9205 } | 16217 related MessagePack format |
9206 | 16218 @sa @ref from_ubjson(detail::input_adapter, const bool) for the related |
9207 /*! | 16219 UBJSON format |
9208 @brief comparison: not equal | 16220 |
9209 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16221 @since version 2.0.9; parameter @a start_index since 2.1.1; changed to |
9210 */ | 16222 consume input adapters, removed start_index parameter, and added |
9211 bool operator!=(const iter_impl& other) const | 16223 @a strict parameter since 3.0.0 |
9212 { | 16224 */ |
9213 return not operator==(other); | 16225 static basic_json from_cbor(detail::input_adapter i, |
9214 } | 16226 const bool strict = true) |
9215 | 16227 { |
9216 /*! | 16228 return binary_reader(i).parse_cbor(strict); |
9217 @brief comparison: smaller | 16229 } |
9218 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16230 |
9219 */ | 16231 /*! |
9220 bool operator<(const iter_impl& other) const | 16232 @copydoc from_cbor(detail::input_adapter, const bool) |
9221 { | 16233 */ |
9222 // if objects are not the same, the comparison is undefined | 16234 template<typename A1, typename A2, |
9223 if (m_object != other.m_object) | 16235 detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0> |
9224 { | 16236 static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true) |
9225 JSON_THROW(std::domain_error("cannot compare iterators of different containers")); | 16237 { |
9226 } | 16238 return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_cbor(strict); |
9227 | 16239 } |
9228 assert(m_object != nullptr); | 16240 |
9229 | 16241 /*! |
9230 switch (m_object->m_type) | 16242 @brief create a JSON value from an input in MessagePack format |
9231 { | 16243 |
9232 case basic_json::value_t::object: | 16244 Deserializes a given input @a i to a JSON value using the MessagePack |
9233 { | 16245 serialization format. |
9234 JSON_THROW(std::domain_error("cannot compare order of object iterators")); | 16246 |
9235 } | 16247 The library maps MessagePack types to JSON value types as follows: |
9236 | 16248 |
9237 case basic_json::value_t::array: | 16249 MessagePack type | JSON value type | first byte |
9238 { | 16250 ---------------- | --------------- | ---------- |
9239 return (m_it.array_iterator < other.m_it.array_iterator); | 16251 positive fixint | number_unsigned | 0x00..0x7F |
9240 } | 16252 fixmap | object | 0x80..0x8F |
9241 | 16253 fixarray | array | 0x90..0x9F |
9242 default: | 16254 fixstr | string | 0xA0..0xBF |
9243 { | 16255 nil | `null` | 0xC0 |
9244 return (m_it.primitive_iterator < other.m_it.primitive_iterator); | 16256 false | `false` | 0xC2 |
9245 } | 16257 true | `true` | 0xC3 |
9246 } | 16258 float 32 | number_float | 0xCA |
9247 } | 16259 float 64 | number_float | 0xCB |
9248 | 16260 uint 8 | number_unsigned | 0xCC |
9249 /*! | 16261 uint 16 | number_unsigned | 0xCD |
9250 @brief comparison: less than or equal | 16262 uint 32 | number_unsigned | 0xCE |
9251 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16263 uint 64 | number_unsigned | 0xCF |
9252 */ | 16264 int 8 | number_integer | 0xD0 |
9253 bool operator<=(const iter_impl& other) const | 16265 int 16 | number_integer | 0xD1 |
9254 { | 16266 int 32 | number_integer | 0xD2 |
9255 return not other.operator < (*this); | 16267 int 64 | number_integer | 0xD3 |
9256 } | 16268 str 8 | string | 0xD9 |
9257 | 16269 str 16 | string | 0xDA |
9258 /*! | 16270 str 32 | string | 0xDB |
9259 @brief comparison: greater than | 16271 array 16 | array | 0xDC |
9260 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16272 array 32 | array | 0xDD |
9261 */ | 16273 map 16 | object | 0xDE |
9262 bool operator>(const iter_impl& other) const | 16274 map 32 | object | 0xDF |
9263 { | 16275 negative fixint | number_integer | 0xE0-0xFF |
9264 return not operator<=(other); | 16276 |
9265 } | 16277 @warning The mapping is **incomplete** in the sense that not all |
9266 | 16278 MessagePack types can be converted to a JSON value. The following |
9267 /*! | 16279 MessagePack types are not supported and will yield parse errors: |
9268 @brief comparison: greater than or equal | 16280 - bin 8 - bin 32 (0xC4..0xC6) |
9269 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16281 - ext 8 - ext 32 (0xC7..0xC9) |
9270 */ | 16282 - fixext 1 - fixext 16 (0xD4..0xD8) |
9271 bool operator>=(const iter_impl& other) const | 16283 |
9272 { | 16284 @note Any MessagePack output created @ref to_msgpack can be successfully |
9273 return not operator<(other); | 16285 parsed by @ref from_msgpack. |
9274 } | 16286 |
9275 | 16287 @param[in] i an input in MessagePack format convertible to an input |
9276 /*! | 16288 adapter |
9277 @brief add to iterator | 16289 @param[in] strict whether to expect the input to be consumed until EOF |
9278 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16290 (true by default) |
9279 */ | 16291 |
9280 iter_impl& operator+=(difference_type i) | 16292 @throw parse_error.110 if the given input ends prematurely or the end of |
9281 { | 16293 file was not reached when @a strict was set to true |
9282 assert(m_object != nullptr); | 16294 @throw parse_error.112 if unsupported features from MessagePack were |
9283 | 16295 used in the given input @a i or if the input is not valid MessagePack |
9284 switch (m_object->m_type) | 16296 @throw parse_error.113 if a string was expected as map key, but not found |
9285 { | 16297 |
9286 case basic_json::value_t::object: | 16298 @complexity Linear in the size of the input @a i. |
9287 { | 16299 |
9288 JSON_THROW(std::domain_error("cannot use offsets with object iterators")); | 16300 @liveexample{The example shows the deserialization of a byte vector in |
9289 } | 16301 MessagePack format to a JSON value.,from_msgpack} |
9290 | 16302 |
9291 case basic_json::value_t::array: | 16303 @sa http://msgpack.org |
9292 { | 16304 @sa @ref to_msgpack(const basic_json&) for the analogous serialization |
9293 std::advance(m_it.array_iterator, i); | 16305 @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR |
9294 break; | 16306 format |
9295 } | 16307 @sa @ref from_ubjson(detail::input_adapter, const bool) for the related |
9296 | 16308 UBJSON format |
9297 default: | 16309 |
9298 { | 16310 @since version 2.0.9; parameter @a start_index since 2.1.1; changed to |
9299 m_it.primitive_iterator += i; | 16311 consume input adapters, removed start_index parameter, and added |
9300 break; | 16312 @a strict parameter since 3.0.0 |
9301 } | 16313 */ |
9302 } | 16314 static basic_json from_msgpack(detail::input_adapter i, |
9303 | 16315 const bool strict = true) |
9304 return *this; | 16316 { |
9305 } | 16317 return binary_reader(i).parse_msgpack(strict); |
9306 | 16318 } |
9307 /*! | 16319 |
9308 @brief subtract from iterator | 16320 /*! |
9309 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16321 @copydoc from_msgpack(detail::input_adapter, const bool) |
9310 */ | 16322 */ |
9311 iter_impl& operator-=(difference_type i) | 16323 template<typename A1, typename A2, |
9312 { | 16324 detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0> |
9313 return operator+=(-i); | 16325 static basic_json from_msgpack(A1 && a1, A2 && a2, const bool strict = true) |
9314 } | 16326 { |
9315 | 16327 return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_msgpack(strict); |
9316 /*! | 16328 } |
9317 @brief add to iterator | 16329 |
9318 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16330 /*! |
9319 */ | 16331 @brief create a JSON value from an input in UBJSON format |
9320 iter_impl operator+(difference_type i) | 16332 |
9321 { | 16333 Deserializes a given input @a i to a JSON value using the UBJSON (Universal |
9322 auto result = *this; | 16334 Binary JSON) serialization format. |
9323 result += i; | 16335 |
9324 return result; | 16336 The library maps UBJSON types to JSON value types as follows: |
9325 } | 16337 |
9326 | 16338 UBJSON type | JSON value type | marker |
9327 /*! | 16339 ----------- | --------------------------------------- | ------ |
9328 @brief subtract from iterator | 16340 no-op | *no value, next value is read* | `N` |
9329 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16341 null | `null` | `Z` |
9330 */ | 16342 false | `false` | `F` |
9331 iter_impl operator-(difference_type i) | 16343 true | `true` | `T` |
9332 { | 16344 float32 | number_float | `d` |
9333 auto result = *this; | 16345 float64 | number_float | `D` |
9334 result -= i; | 16346 uint8 | number_unsigned | `U` |
9335 return result; | 16347 int8 | number_integer | `i` |
9336 } | 16348 int16 | number_integer | `I` |
9337 | 16349 int32 | number_integer | `l` |
9338 /*! | 16350 int64 | number_integer | `L` |
9339 @brief return difference | 16351 string | string | `S` |
9340 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16352 char | string | `C` |
9341 */ | 16353 array | array (optimized values are supported) | `[` |
9342 difference_type operator-(const iter_impl& other) const | 16354 object | object (optimized values are supported) | `{` |
9343 { | 16355 |
9344 assert(m_object != nullptr); | 16356 @note The mapping is **complete** in the sense that any UBJSON value can |
9345 | 16357 be converted to a JSON value. |
9346 switch (m_object->m_type) | 16358 |
9347 { | 16359 @param[in] i an input in UBJSON format convertible to an input adapter |
9348 case basic_json::value_t::object: | 16360 @param[in] strict whether to expect the input to be consumed until EOF |
9349 { | 16361 (true by default) |
9350 JSON_THROW(std::domain_error("cannot use offsets with object iterators")); | 16362 |
9351 } | 16363 @throw parse_error.110 if the given input ends prematurely or the end of |
9352 | 16364 file was not reached when @a strict was set to true |
9353 case basic_json::value_t::array: | 16365 @throw parse_error.112 if a parse error occurs |
9354 { | 16366 @throw parse_error.113 if a string could not be parsed successfully |
9355 return m_it.array_iterator - other.m_it.array_iterator; | 16367 |
9356 } | 16368 @complexity Linear in the size of the input @a i. |
9357 | 16369 |
9358 default: | 16370 @liveexample{The example shows the deserialization of a byte vector in |
9359 { | 16371 UBJSON format to a JSON value.,from_ubjson} |
9360 return m_it.primitive_iterator - other.m_it.primitive_iterator; | 16372 |
9361 } | 16373 @sa http://ubjson.org |
9362 } | 16374 @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the |
9363 } | 16375 analogous serialization |
9364 | 16376 @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR |
9365 /*! | 16377 format |
9366 @brief access to successor | 16378 @sa @ref from_msgpack(detail::input_adapter, const bool) for the related |
9367 @pre The iterator is initialized; i.e. `m_object != nullptr`. | 16379 MessagePack format |
9368 */ | 16380 |
9369 reference operator[](difference_type n) const | 16381 @since version 3.1.0 |
9370 { | 16382 */ |
9371 assert(m_object != nullptr); | 16383 static basic_json from_ubjson(detail::input_adapter i, |
9372 | 16384 const bool strict = true) |
9373 switch (m_object->m_type) | 16385 { |
9374 { | 16386 return binary_reader(i).parse_ubjson(strict); |
9375 case basic_json::value_t::object: | 16387 } |
9376 { | 16388 |
9377 JSON_THROW(std::domain_error("cannot use operator[] for object iterators")); | 16389 template<typename A1, typename A2, |
9378 } | 16390 detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0> |
9379 | 16391 static basic_json from_ubjson(A1 && a1, A2 && a2, const bool strict = true) |
9380 case basic_json::value_t::array: | 16392 { |
9381 { | 16393 return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_ubjson(strict); |
9382 return *std::next(m_it.array_iterator, n); | 16394 } |
9383 } | 16395 |
9384 | 16396 /// @} |
9385 case basic_json::value_t::null: | |
9386 { | |
9387 JSON_THROW(std::out_of_range("cannot get value")); | |
9388 } | |
9389 | |
9390 default: | |
9391 { | |
9392 if (m_it.primitive_iterator.get_value() == -n) | |
9393 { | |
9394 return *m_object; | |
9395 } | |
9396 | |
9397 JSON_THROW(std::out_of_range("cannot get value")); | |
9398 } | |
9399 } | |
9400 } | |
9401 | |
9402 /*! | |
9403 @brief return the key of an object iterator | |
9404 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
9405 */ | |
9406 typename object_t::key_type key() const | |
9407 { | |
9408 assert(m_object != nullptr); | |
9409 | |
9410 if (m_object->is_object()) | |
9411 { | |
9412 return m_it.object_iterator->first; | |
9413 } | |
9414 | |
9415 JSON_THROW(std::domain_error("cannot use key() for non-object iterators")); | |
9416 } | |
9417 | |
9418 /*! | |
9419 @brief return the value of an iterator | |
9420 @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
9421 */ | |
9422 reference value() const | |
9423 { | |
9424 return operator*(); | |
9425 } | |
9426 | |
9427 private: | |
9428 /// associated JSON instance | |
9429 pointer m_object = nullptr; | |
9430 /// the actual iterator of the associated instance | |
9431 internal_iterator m_it = internal_iterator(); | |
9432 }; | |
9433 | |
9434 /*! | |
9435 @brief a template for a reverse iterator class | |
9436 | |
9437 @tparam Base the base iterator type to reverse. Valid types are @ref | |
9438 iterator (to create @ref reverse_iterator) and @ref const_iterator (to | |
9439 create @ref const_reverse_iterator). | |
9440 | |
9441 @requirement The class satisfies the following concept requirements: | |
9442 - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator): | |
9443 The iterator that can be moved to point (forward and backward) to any | |
9444 element in constant time. | |
9445 - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator): | |
9446 It is possible to write to the pointed-to element (only if @a Base is | |
9447 @ref iterator). | |
9448 | |
9449 @since version 1.0.0 | |
9450 */ | |
9451 template<typename Base> | |
9452 class json_reverse_iterator : public std::reverse_iterator<Base> | |
9453 { | |
9454 public: | |
9455 /// shortcut to the reverse iterator adaptor | |
9456 using base_iterator = std::reverse_iterator<Base>; | |
9457 /// the reference type for the pointed-to element | |
9458 using reference = typename Base::reference; | |
9459 | |
9460 /// create reverse iterator from iterator | |
9461 json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept | |
9462 : base_iterator(it) | |
9463 {} | |
9464 | |
9465 /// create reverse iterator from base class | |
9466 json_reverse_iterator(const base_iterator& it) noexcept | |
9467 : base_iterator(it) | |
9468 {} | |
9469 | |
9470 /// post-increment (it++) | |
9471 json_reverse_iterator operator++(int) | |
9472 { | |
9473 return base_iterator::operator++(1); | |
9474 } | |
9475 | |
9476 /// pre-increment (++it) | |
9477 json_reverse_iterator& operator++() | |
9478 { | |
9479 base_iterator::operator++(); | |
9480 return *this; | |
9481 } | |
9482 | |
9483 /// post-decrement (it--) | |
9484 json_reverse_iterator operator--(int) | |
9485 { | |
9486 return base_iterator::operator--(1); | |
9487 } | |
9488 | |
9489 /// pre-decrement (--it) | |
9490 json_reverse_iterator& operator--() | |
9491 { | |
9492 base_iterator::operator--(); | |
9493 return *this; | |
9494 } | |
9495 | |
9496 /// add to iterator | |
9497 json_reverse_iterator& operator+=(difference_type i) | |
9498 { | |
9499 base_iterator::operator+=(i); | |
9500 return *this; | |
9501 } | |
9502 | |
9503 /// add to iterator | |
9504 json_reverse_iterator operator+(difference_type i) const | |
9505 { | |
9506 auto result = *this; | |
9507 result += i; | |
9508 return result; | |
9509 } | |
9510 | |
9511 /// subtract from iterator | |
9512 json_reverse_iterator operator-(difference_type i) const | |
9513 { | |
9514 auto result = *this; | |
9515 result -= i; | |
9516 return result; | |
9517 } | |
9518 | |
9519 /// return difference | |
9520 difference_type operator-(const json_reverse_iterator& other) const | |
9521 { | |
9522 return this->base() - other.base(); | |
9523 } | |
9524 | |
9525 /// access to successor | |
9526 reference operator[](difference_type n) const | |
9527 { | |
9528 return *(this->operator+(n)); | |
9529 } | |
9530 | |
9531 /// return the key of an object iterator | |
9532 typename object_t::key_type key() const | |
9533 { | |
9534 auto it = --this->base(); | |
9535 return it.key(); | |
9536 } | |
9537 | |
9538 /// return the value of an iterator | |
9539 reference value() const | |
9540 { | |
9541 auto it = --this->base(); | |
9542 return it.operator * (); | |
9543 } | |
9544 }; | |
9545 | |
9546 | |
9547 private: | |
9548 ////////////////////// | |
9549 // lexer and parser // | |
9550 ////////////////////// | |
9551 | |
9552 /*! | |
9553 @brief lexical analysis | |
9554 | |
9555 This class organizes the lexical analysis during JSON deserialization. The | |
9556 core of it is a scanner generated by [re2c](http://re2c.org) that | |
9557 processes a buffer and recognizes tokens according to RFC 7159. | |
9558 */ | |
9559 class lexer | |
9560 { | |
9561 public: | |
9562 /// token types for the parser | |
9563 enum class token_type | |
9564 { | |
9565 uninitialized, ///< indicating the scanner is uninitialized | |
9566 literal_true, ///< the `true` literal | |
9567 literal_false, ///< the `false` literal | |
9568 literal_null, ///< the `null` literal | |
9569 value_string, ///< a string -- use get_string() for actual value | |
9570 value_unsigned, ///< an unsigned integer -- use get_number() for actual value | |
9571 value_integer, ///< a signed integer -- use get_number() for actual value | |
9572 value_float, ///< an floating point number -- use get_number() for actual value | |
9573 begin_array, ///< the character for array begin `[` | |
9574 begin_object, ///< the character for object begin `{` | |
9575 end_array, ///< the character for array end `]` | |
9576 end_object, ///< the character for object end `}` | |
9577 name_separator, ///< the name separator `:` | |
9578 value_separator, ///< the value separator `,` | |
9579 parse_error, ///< indicating a parse error | |
9580 end_of_input ///< indicating the end of the input buffer | |
9581 }; | |
9582 | |
9583 /// the char type to use in the lexer | |
9584 using lexer_char_t = unsigned char; | |
9585 | |
9586 /// a lexer from a buffer with given length | |
9587 lexer(const lexer_char_t* buff, const size_t len) noexcept | |
9588 : m_content(buff) | |
9589 { | |
9590 assert(m_content != nullptr); | |
9591 m_start = m_cursor = m_content; | |
9592 m_limit = m_content + len; | |
9593 } | |
9594 | |
9595 /// a lexer from an input stream | |
9596 explicit lexer(std::istream& s) | |
9597 : m_stream(&s), m_line_buffer() | |
9598 { | |
9599 // immediately abort if stream is erroneous | |
9600 if (s.fail()) | |
9601 { | |
9602 JSON_THROW(std::invalid_argument("stream error")); | |
9603 } | |
9604 | |
9605 // fill buffer | |
9606 fill_line_buffer(); | |
9607 | |
9608 // skip UTF-8 byte-order mark | |
9609 if (m_line_buffer.size() >= 3 and m_line_buffer.substr(0, 3) == "\xEF\xBB\xBF") | |
9610 { | |
9611 m_line_buffer[0] = ' '; | |
9612 m_line_buffer[1] = ' '; | |
9613 m_line_buffer[2] = ' '; | |
9614 } | |
9615 } | |
9616 | |
9617 // switch off unwanted functions (due to pointer members) | |
9618 lexer() = delete; | |
9619 lexer(const lexer&) = delete; | |
9620 lexer operator=(const lexer&) = delete; | |
9621 | |
9622 /*! | |
9623 @brief create a string from one or two Unicode code points | |
9624 | |
9625 There are two cases: (1) @a codepoint1 is in the Basic Multilingual | |
9626 Plane (U+0000 through U+FFFF) and @a codepoint2 is 0, or (2) | |
9627 @a codepoint1 and @a codepoint2 are a UTF-16 surrogate pair to | |
9628 represent a code point above U+FFFF. | |
9629 | |
9630 @param[in] codepoint1 the code point (can be high surrogate) | |
9631 @param[in] codepoint2 the code point (can be low surrogate or 0) | |
9632 | |
9633 @return string representation of the code point; the length of the | |
9634 result string is between 1 and 4 characters. | |
9635 | |
9636 @throw std::out_of_range if code point is > 0x10ffff; example: `"code | |
9637 points above 0x10FFFF are invalid"` | |
9638 @throw std::invalid_argument if the low surrogate is invalid; example: | |
9639 `""missing or wrong low surrogate""` | |
9640 | |
9641 @complexity Constant. | |
9642 | |
9643 @see <http://en.wikipedia.org/wiki/UTF-8#Sample_code> | |
9644 */ | |
9645 static string_t to_unicode(const std::size_t codepoint1, | |
9646 const std::size_t codepoint2 = 0) | |
9647 { | |
9648 // calculate the code point from the given code points | |
9649 std::size_t codepoint = codepoint1; | |
9650 | |
9651 // check if codepoint1 is a high surrogate | |
9652 if (codepoint1 >= 0xD800 and codepoint1 <= 0xDBFF) | |
9653 { | |
9654 // check if codepoint2 is a low surrogate | |
9655 if (codepoint2 >= 0xDC00 and codepoint2 <= 0xDFFF) | |
9656 { | |
9657 codepoint = | |
9658 // high surrogate occupies the most significant 22 bits | |
9659 (codepoint1 << 10) | |
9660 // low surrogate occupies the least significant 15 bits | |
9661 + codepoint2 | |
9662 // there is still the 0xD800, 0xDC00 and 0x10000 noise | |
9663 // in the result so we have to subtract with: | |
9664 // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 | |
9665 - 0x35FDC00; | |
9666 } | |
9667 else | |
9668 { | |
9669 JSON_THROW(std::invalid_argument("missing or wrong low surrogate")); | |
9670 } | |
9671 } | |
9672 | |
9673 string_t result; | |
9674 | |
9675 if (codepoint < 0x80) | |
9676 { | |
9677 // 1-byte characters: 0xxxxxxx (ASCII) | |
9678 result.append(1, static_cast<typename string_t::value_type>(codepoint)); | |
9679 } | |
9680 else if (codepoint <= 0x7ff) | |
9681 { | |
9682 // 2-byte characters: 110xxxxx 10xxxxxx | |
9683 result.append(1, static_cast<typename string_t::value_type>(0xC0 | ((codepoint >> 6) & 0x1F))); | |
9684 result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F))); | |
9685 } | |
9686 else if (codepoint <= 0xffff) | |
9687 { | |
9688 // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx | |
9689 result.append(1, static_cast<typename string_t::value_type>(0xE0 | ((codepoint >> 12) & 0x0F))); | |
9690 result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F))); | |
9691 result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F))); | |
9692 } | |
9693 else if (codepoint <= 0x10ffff) | |
9694 { | |
9695 // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx | |
9696 result.append(1, static_cast<typename string_t::value_type>(0xF0 | ((codepoint >> 18) & 0x07))); | |
9697 result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 12) & 0x3F))); | |
9698 result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F))); | |
9699 result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F))); | |
9700 } | |
9701 else | |
9702 { | |
9703 JSON_THROW(std::out_of_range("code points above 0x10FFFF are invalid")); | |
9704 } | |
9705 | |
9706 return result; | |
9707 } | |
9708 | |
9709 /// return name of values of type token_type (only used for errors) | |
9710 static std::string token_type_name(const token_type t) | |
9711 { | |
9712 switch (t) | |
9713 { | |
9714 case token_type::uninitialized: | |
9715 return "<uninitialized>"; | |
9716 case token_type::literal_true: | |
9717 return "true literal"; | |
9718 case token_type::literal_false: | |
9719 return "false literal"; | |
9720 case token_type::literal_null: | |
9721 return "null literal"; | |
9722 case token_type::value_string: | |
9723 return "string literal"; | |
9724 case lexer::token_type::value_unsigned: | |
9725 case lexer::token_type::value_integer: | |
9726 case lexer::token_type::value_float: | |
9727 return "number literal"; | |
9728 case token_type::begin_array: | |
9729 return "'['"; | |
9730 case token_type::begin_object: | |
9731 return "'{'"; | |
9732 case token_type::end_array: | |
9733 return "']'"; | |
9734 case token_type::end_object: | |
9735 return "'}'"; | |
9736 case token_type::name_separator: | |
9737 return "':'"; | |
9738 case token_type::value_separator: | |
9739 return "','"; | |
9740 case token_type::parse_error: | |
9741 return "<parse error>"; | |
9742 case token_type::end_of_input: | |
9743 return "end of input"; | |
9744 default: | |
9745 { | |
9746 // catch non-enum values | |
9747 return "unknown token"; // LCOV_EXCL_LINE | |
9748 } | |
9749 } | |
9750 } | |
9751 | |
9752 /*! | |
9753 This function implements a scanner for JSON. It is specified using | |
9754 regular expressions that try to follow RFC 7159 as close as possible. | |
9755 These regular expressions are then translated into a minimized | |
9756 deterministic finite automaton (DFA) by the tool | |
9757 [re2c](http://re2c.org). As a result, the translated code for this | |
9758 function consists of a large block of code with `goto` jumps. | |
9759 | |
9760 @return the class of the next token read from the buffer | |
9761 | |
9762 @complexity Linear in the length of the input.\n | |
9763 | |
9764 Proposition: The loop below will always terminate for finite input.\n | |
9765 | |
9766 Proof (by contradiction): Assume a finite input. To loop forever, the | |
9767 loop must never hit code with a `break` statement. The only code | |
9768 snippets without a `break` statement are the continue statements for | |
9769 whitespace and byte-order-marks. To loop forever, the input must be an | |
9770 infinite sequence of whitespace or byte-order-marks. This contradicts | |
9771 the assumption of finite input, q.e.d. | |
9772 */ | |
9773 token_type scan() | |
9774 { | |
9775 while (true) | |
9776 { | |
9777 // pointer for backtracking information | |
9778 m_marker = nullptr; | |
9779 | |
9780 // remember the begin of the token | |
9781 m_start = m_cursor; | |
9782 assert(m_start != nullptr); | |
9783 | |
9784 | |
9785 { | |
9786 lexer_char_t yych; | |
9787 unsigned int yyaccept = 0; | |
9788 static const unsigned char yybm[] = | |
9789 { | |
9790 0, 0, 0, 0, 0, 0, 0, 0, | |
9791 0, 32, 32, 0, 0, 32, 0, 0, | |
9792 0, 0, 0, 0, 0, 0, 0, 0, | |
9793 0, 0, 0, 0, 0, 0, 0, 0, | |
9794 160, 128, 0, 128, 128, 128, 128, 128, | |
9795 128, 128, 128, 128, 128, 128, 128, 128, | |
9796 192, 192, 192, 192, 192, 192, 192, 192, | |
9797 192, 192, 128, 128, 128, 128, 128, 128, | |
9798 128, 128, 128, 128, 128, 128, 128, 128, | |
9799 128, 128, 128, 128, 128, 128, 128, 128, | |
9800 128, 128, 128, 128, 128, 128, 128, 128, | |
9801 128, 128, 128, 128, 0, 128, 128, 128, | |
9802 128, 128, 128, 128, 128, 128, 128, 128, | |
9803 128, 128, 128, 128, 128, 128, 128, 128, | |
9804 128, 128, 128, 128, 128, 128, 128, 128, | |
9805 128, 128, 128, 128, 128, 128, 128, 128, | |
9806 0, 0, 0, 0, 0, 0, 0, 0, | |
9807 0, 0, 0, 0, 0, 0, 0, 0, | |
9808 0, 0, 0, 0, 0, 0, 0, 0, | |
9809 0, 0, 0, 0, 0, 0, 0, 0, | |
9810 0, 0, 0, 0, 0, 0, 0, 0, | |
9811 0, 0, 0, 0, 0, 0, 0, 0, | |
9812 0, 0, 0, 0, 0, 0, 0, 0, | |
9813 0, 0, 0, 0, 0, 0, 0, 0, | |
9814 0, 0, 0, 0, 0, 0, 0, 0, | |
9815 0, 0, 0, 0, 0, 0, 0, 0, | |
9816 0, 0, 0, 0, 0, 0, 0, 0, | |
9817 0, 0, 0, 0, 0, 0, 0, 0, | |
9818 0, 0, 0, 0, 0, 0, 0, 0, | |
9819 0, 0, 0, 0, 0, 0, 0, 0, | |
9820 0, 0, 0, 0, 0, 0, 0, 0, | |
9821 0, 0, 0, 0, 0, 0, 0, 0, | |
9822 }; | |
9823 if ((m_limit - m_cursor) < 5) | |
9824 { | |
9825 fill_line_buffer(5); // LCOV_EXCL_LINE | |
9826 } | |
9827 yych = *m_cursor; | |
9828 if (yybm[0 + yych] & 32) | |
9829 { | |
9830 goto basic_json_parser_6; | |
9831 } | |
9832 if (yych <= '[') | |
9833 { | |
9834 if (yych <= '-') | |
9835 { | |
9836 if (yych <= '"') | |
9837 { | |
9838 if (yych <= 0x00) | |
9839 { | |
9840 goto basic_json_parser_2; | |
9841 } | |
9842 if (yych <= '!') | |
9843 { | |
9844 goto basic_json_parser_4; | |
9845 } | |
9846 goto basic_json_parser_9; | |
9847 } | |
9848 else | |
9849 { | |
9850 if (yych <= '+') | |
9851 { | |
9852 goto basic_json_parser_4; | |
9853 } | |
9854 if (yych <= ',') | |
9855 { | |
9856 goto basic_json_parser_10; | |
9857 } | |
9858 goto basic_json_parser_12; | |
9859 } | |
9860 } | |
9861 else | |
9862 { | |
9863 if (yych <= '9') | |
9864 { | |
9865 if (yych <= '/') | |
9866 { | |
9867 goto basic_json_parser_4; | |
9868 } | |
9869 if (yych <= '0') | |
9870 { | |
9871 goto basic_json_parser_13; | |
9872 } | |
9873 goto basic_json_parser_15; | |
9874 } | |
9875 else | |
9876 { | |
9877 if (yych <= ':') | |
9878 { | |
9879 goto basic_json_parser_17; | |
9880 } | |
9881 if (yych <= 'Z') | |
9882 { | |
9883 goto basic_json_parser_4; | |
9884 } | |
9885 goto basic_json_parser_19; | |
9886 } | |
9887 } | |
9888 } | |
9889 else | |
9890 { | |
9891 if (yych <= 'n') | |
9892 { | |
9893 if (yych <= 'e') | |
9894 { | |
9895 if (yych == ']') | |
9896 { | |
9897 goto basic_json_parser_21; | |
9898 } | |
9899 goto basic_json_parser_4; | |
9900 } | |
9901 else | |
9902 { | |
9903 if (yych <= 'f') | |
9904 { | |
9905 goto basic_json_parser_23; | |
9906 } | |
9907 if (yych <= 'm') | |
9908 { | |
9909 goto basic_json_parser_4; | |
9910 } | |
9911 goto basic_json_parser_24; | |
9912 } | |
9913 } | |
9914 else | |
9915 { | |
9916 if (yych <= 'z') | |
9917 { | |
9918 if (yych == 't') | |
9919 { | |
9920 goto basic_json_parser_25; | |
9921 } | |
9922 goto basic_json_parser_4; | |
9923 } | |
9924 else | |
9925 { | |
9926 if (yych <= '{') | |
9927 { | |
9928 goto basic_json_parser_26; | |
9929 } | |
9930 if (yych == '}') | |
9931 { | |
9932 goto basic_json_parser_28; | |
9933 } | |
9934 goto basic_json_parser_4; | |
9935 } | |
9936 } | |
9937 } | |
9938 basic_json_parser_2: | |
9939 ++m_cursor; | |
9940 { | |
9941 last_token_type = token_type::end_of_input; | |
9942 break; | |
9943 } | |
9944 basic_json_parser_4: | |
9945 ++m_cursor; | |
9946 basic_json_parser_5: | |
9947 { | |
9948 last_token_type = token_type::parse_error; | |
9949 break; | |
9950 } | |
9951 basic_json_parser_6: | |
9952 ++m_cursor; | |
9953 if (m_limit <= m_cursor) | |
9954 { | |
9955 fill_line_buffer(1); // LCOV_EXCL_LINE | |
9956 } | |
9957 yych = *m_cursor; | |
9958 if (yybm[0 + yych] & 32) | |
9959 { | |
9960 goto basic_json_parser_6; | |
9961 } | |
9962 { | |
9963 continue; | |
9964 } | |
9965 basic_json_parser_9: | |
9966 yyaccept = 0; | |
9967 yych = *(m_marker = ++m_cursor); | |
9968 if (yych <= 0x1F) | |
9969 { | |
9970 goto basic_json_parser_5; | |
9971 } | |
9972 if (yych <= 0x7F) | |
9973 { | |
9974 goto basic_json_parser_31; | |
9975 } | |
9976 if (yych <= 0xC1) | |
9977 { | |
9978 goto basic_json_parser_5; | |
9979 } | |
9980 if (yych <= 0xF4) | |
9981 { | |
9982 goto basic_json_parser_31; | |
9983 } | |
9984 goto basic_json_parser_5; | |
9985 basic_json_parser_10: | |
9986 ++m_cursor; | |
9987 { | |
9988 last_token_type = token_type::value_separator; | |
9989 break; | |
9990 } | |
9991 basic_json_parser_12: | |
9992 yych = *++m_cursor; | |
9993 if (yych <= '/') | |
9994 { | |
9995 goto basic_json_parser_5; | |
9996 } | |
9997 if (yych <= '0') | |
9998 { | |
9999 goto basic_json_parser_43; | |
10000 } | |
10001 if (yych <= '9') | |
10002 { | |
10003 goto basic_json_parser_45; | |
10004 } | |
10005 goto basic_json_parser_5; | |
10006 basic_json_parser_13: | |
10007 yyaccept = 1; | |
10008 yych = *(m_marker = ++m_cursor); | |
10009 if (yych <= '9') | |
10010 { | |
10011 if (yych == '.') | |
10012 { | |
10013 goto basic_json_parser_47; | |
10014 } | |
10015 if (yych >= '0') | |
10016 { | |
10017 goto basic_json_parser_48; | |
10018 } | |
10019 } | |
10020 else | |
10021 { | |
10022 if (yych <= 'E') | |
10023 { | |
10024 if (yych >= 'E') | |
10025 { | |
10026 goto basic_json_parser_51; | |
10027 } | |
10028 } | |
10029 else | |
10030 { | |
10031 if (yych == 'e') | |
10032 { | |
10033 goto basic_json_parser_51; | |
10034 } | |
10035 } | |
10036 } | |
10037 basic_json_parser_14: | |
10038 { | |
10039 last_token_type = token_type::value_unsigned; | |
10040 break; | |
10041 } | |
10042 basic_json_parser_15: | |
10043 yyaccept = 1; | |
10044 m_marker = ++m_cursor; | |
10045 if ((m_limit - m_cursor) < 3) | |
10046 { | |
10047 fill_line_buffer(3); // LCOV_EXCL_LINE | |
10048 } | |
10049 yych = *m_cursor; | |
10050 if (yybm[0 + yych] & 64) | |
10051 { | |
10052 goto basic_json_parser_15; | |
10053 } | |
10054 if (yych <= 'D') | |
10055 { | |
10056 if (yych == '.') | |
10057 { | |
10058 goto basic_json_parser_47; | |
10059 } | |
10060 goto basic_json_parser_14; | |
10061 } | |
10062 else | |
10063 { | |
10064 if (yych <= 'E') | |
10065 { | |
10066 goto basic_json_parser_51; | |
10067 } | |
10068 if (yych == 'e') | |
10069 { | |
10070 goto basic_json_parser_51; | |
10071 } | |
10072 goto basic_json_parser_14; | |
10073 } | |
10074 basic_json_parser_17: | |
10075 ++m_cursor; | |
10076 { | |
10077 last_token_type = token_type::name_separator; | |
10078 break; | |
10079 } | |
10080 basic_json_parser_19: | |
10081 ++m_cursor; | |
10082 { | |
10083 last_token_type = token_type::begin_array; | |
10084 break; | |
10085 } | |
10086 basic_json_parser_21: | |
10087 ++m_cursor; | |
10088 { | |
10089 last_token_type = token_type::end_array; | |
10090 break; | |
10091 } | |
10092 basic_json_parser_23: | |
10093 yyaccept = 0; | |
10094 yych = *(m_marker = ++m_cursor); | |
10095 if (yych == 'a') | |
10096 { | |
10097 goto basic_json_parser_52; | |
10098 } | |
10099 goto basic_json_parser_5; | |
10100 basic_json_parser_24: | |
10101 yyaccept = 0; | |
10102 yych = *(m_marker = ++m_cursor); | |
10103 if (yych == 'u') | |
10104 { | |
10105 goto basic_json_parser_53; | |
10106 } | |
10107 goto basic_json_parser_5; | |
10108 basic_json_parser_25: | |
10109 yyaccept = 0; | |
10110 yych = *(m_marker = ++m_cursor); | |
10111 if (yych == 'r') | |
10112 { | |
10113 goto basic_json_parser_54; | |
10114 } | |
10115 goto basic_json_parser_5; | |
10116 basic_json_parser_26: | |
10117 ++m_cursor; | |
10118 { | |
10119 last_token_type = token_type::begin_object; | |
10120 break; | |
10121 } | |
10122 basic_json_parser_28: | |
10123 ++m_cursor; | |
10124 { | |
10125 last_token_type = token_type::end_object; | |
10126 break; | |
10127 } | |
10128 basic_json_parser_30: | |
10129 ++m_cursor; | |
10130 if (m_limit <= m_cursor) | |
10131 { | |
10132 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10133 } | |
10134 yych = *m_cursor; | |
10135 basic_json_parser_31: | |
10136 if (yybm[0 + yych] & 128) | |
10137 { | |
10138 goto basic_json_parser_30; | |
10139 } | |
10140 if (yych <= 0xE0) | |
10141 { | |
10142 if (yych <= '\\') | |
10143 { | |
10144 if (yych <= 0x1F) | |
10145 { | |
10146 goto basic_json_parser_32; | |
10147 } | |
10148 if (yych <= '"') | |
10149 { | |
10150 goto basic_json_parser_33; | |
10151 } | |
10152 goto basic_json_parser_35; | |
10153 } | |
10154 else | |
10155 { | |
10156 if (yych <= 0xC1) | |
10157 { | |
10158 goto basic_json_parser_32; | |
10159 } | |
10160 if (yych <= 0xDF) | |
10161 { | |
10162 goto basic_json_parser_36; | |
10163 } | |
10164 goto basic_json_parser_37; | |
10165 } | |
10166 } | |
10167 else | |
10168 { | |
10169 if (yych <= 0xEF) | |
10170 { | |
10171 if (yych == 0xED) | |
10172 { | |
10173 goto basic_json_parser_39; | |
10174 } | |
10175 goto basic_json_parser_38; | |
10176 } | |
10177 else | |
10178 { | |
10179 if (yych <= 0xF0) | |
10180 { | |
10181 goto basic_json_parser_40; | |
10182 } | |
10183 if (yych <= 0xF3) | |
10184 { | |
10185 goto basic_json_parser_41; | |
10186 } | |
10187 if (yych <= 0xF4) | |
10188 { | |
10189 goto basic_json_parser_42; | |
10190 } | |
10191 } | |
10192 } | |
10193 basic_json_parser_32: | |
10194 m_cursor = m_marker; | |
10195 if (yyaccept <= 1) | |
10196 { | |
10197 if (yyaccept == 0) | |
10198 { | |
10199 goto basic_json_parser_5; | |
10200 } | |
10201 else | |
10202 { | |
10203 goto basic_json_parser_14; | |
10204 } | |
10205 } | |
10206 else | |
10207 { | |
10208 if (yyaccept == 2) | |
10209 { | |
10210 goto basic_json_parser_44; | |
10211 } | |
10212 else | |
10213 { | |
10214 goto basic_json_parser_58; | |
10215 } | |
10216 } | |
10217 basic_json_parser_33: | |
10218 ++m_cursor; | |
10219 { | |
10220 last_token_type = token_type::value_string; | |
10221 break; | |
10222 } | |
10223 basic_json_parser_35: | |
10224 ++m_cursor; | |
10225 if (m_limit <= m_cursor) | |
10226 { | |
10227 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10228 } | |
10229 yych = *m_cursor; | |
10230 if (yych <= 'e') | |
10231 { | |
10232 if (yych <= '/') | |
10233 { | |
10234 if (yych == '"') | |
10235 { | |
10236 goto basic_json_parser_30; | |
10237 } | |
10238 if (yych <= '.') | |
10239 { | |
10240 goto basic_json_parser_32; | |
10241 } | |
10242 goto basic_json_parser_30; | |
10243 } | |
10244 else | |
10245 { | |
10246 if (yych <= '\\') | |
10247 { | |
10248 if (yych <= '[') | |
10249 { | |
10250 goto basic_json_parser_32; | |
10251 } | |
10252 goto basic_json_parser_30; | |
10253 } | |
10254 else | |
10255 { | |
10256 if (yych == 'b') | |
10257 { | |
10258 goto basic_json_parser_30; | |
10259 } | |
10260 goto basic_json_parser_32; | |
10261 } | |
10262 } | |
10263 } | |
10264 else | |
10265 { | |
10266 if (yych <= 'q') | |
10267 { | |
10268 if (yych <= 'f') | |
10269 { | |
10270 goto basic_json_parser_30; | |
10271 } | |
10272 if (yych == 'n') | |
10273 { | |
10274 goto basic_json_parser_30; | |
10275 } | |
10276 goto basic_json_parser_32; | |
10277 } | |
10278 else | |
10279 { | |
10280 if (yych <= 's') | |
10281 { | |
10282 if (yych <= 'r') | |
10283 { | |
10284 goto basic_json_parser_30; | |
10285 } | |
10286 goto basic_json_parser_32; | |
10287 } | |
10288 else | |
10289 { | |
10290 if (yych <= 't') | |
10291 { | |
10292 goto basic_json_parser_30; | |
10293 } | |
10294 if (yych <= 'u') | |
10295 { | |
10296 goto basic_json_parser_55; | |
10297 } | |
10298 goto basic_json_parser_32; | |
10299 } | |
10300 } | |
10301 } | |
10302 basic_json_parser_36: | |
10303 ++m_cursor; | |
10304 if (m_limit <= m_cursor) | |
10305 { | |
10306 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10307 } | |
10308 yych = *m_cursor; | |
10309 if (yych <= 0x7F) | |
10310 { | |
10311 goto basic_json_parser_32; | |
10312 } | |
10313 if (yych <= 0xBF) | |
10314 { | |
10315 goto basic_json_parser_30; | |
10316 } | |
10317 goto basic_json_parser_32; | |
10318 basic_json_parser_37: | |
10319 ++m_cursor; | |
10320 if (m_limit <= m_cursor) | |
10321 { | |
10322 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10323 } | |
10324 yych = *m_cursor; | |
10325 if (yych <= 0x9F) | |
10326 { | |
10327 goto basic_json_parser_32; | |
10328 } | |
10329 if (yych <= 0xBF) | |
10330 { | |
10331 goto basic_json_parser_36; | |
10332 } | |
10333 goto basic_json_parser_32; | |
10334 basic_json_parser_38: | |
10335 ++m_cursor; | |
10336 if (m_limit <= m_cursor) | |
10337 { | |
10338 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10339 } | |
10340 yych = *m_cursor; | |
10341 if (yych <= 0x7F) | |
10342 { | |
10343 goto basic_json_parser_32; | |
10344 } | |
10345 if (yych <= 0xBF) | |
10346 { | |
10347 goto basic_json_parser_36; | |
10348 } | |
10349 goto basic_json_parser_32; | |
10350 basic_json_parser_39: | |
10351 ++m_cursor; | |
10352 if (m_limit <= m_cursor) | |
10353 { | |
10354 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10355 } | |
10356 yych = *m_cursor; | |
10357 if (yych <= 0x7F) | |
10358 { | |
10359 goto basic_json_parser_32; | |
10360 } | |
10361 if (yych <= 0x9F) | |
10362 { | |
10363 goto basic_json_parser_36; | |
10364 } | |
10365 goto basic_json_parser_32; | |
10366 basic_json_parser_40: | |
10367 ++m_cursor; | |
10368 if (m_limit <= m_cursor) | |
10369 { | |
10370 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10371 } | |
10372 yych = *m_cursor; | |
10373 if (yych <= 0x8F) | |
10374 { | |
10375 goto basic_json_parser_32; | |
10376 } | |
10377 if (yych <= 0xBF) | |
10378 { | |
10379 goto basic_json_parser_38; | |
10380 } | |
10381 goto basic_json_parser_32; | |
10382 basic_json_parser_41: | |
10383 ++m_cursor; | |
10384 if (m_limit <= m_cursor) | |
10385 { | |
10386 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10387 } | |
10388 yych = *m_cursor; | |
10389 if (yych <= 0x7F) | |
10390 { | |
10391 goto basic_json_parser_32; | |
10392 } | |
10393 if (yych <= 0xBF) | |
10394 { | |
10395 goto basic_json_parser_38; | |
10396 } | |
10397 goto basic_json_parser_32; | |
10398 basic_json_parser_42: | |
10399 ++m_cursor; | |
10400 if (m_limit <= m_cursor) | |
10401 { | |
10402 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10403 } | |
10404 yych = *m_cursor; | |
10405 if (yych <= 0x7F) | |
10406 { | |
10407 goto basic_json_parser_32; | |
10408 } | |
10409 if (yych <= 0x8F) | |
10410 { | |
10411 goto basic_json_parser_38; | |
10412 } | |
10413 goto basic_json_parser_32; | |
10414 basic_json_parser_43: | |
10415 yyaccept = 2; | |
10416 yych = *(m_marker = ++m_cursor); | |
10417 if (yych <= '9') | |
10418 { | |
10419 if (yych == '.') | |
10420 { | |
10421 goto basic_json_parser_47; | |
10422 } | |
10423 if (yych >= '0') | |
10424 { | |
10425 goto basic_json_parser_48; | |
10426 } | |
10427 } | |
10428 else | |
10429 { | |
10430 if (yych <= 'E') | |
10431 { | |
10432 if (yych >= 'E') | |
10433 { | |
10434 goto basic_json_parser_51; | |
10435 } | |
10436 } | |
10437 else | |
10438 { | |
10439 if (yych == 'e') | |
10440 { | |
10441 goto basic_json_parser_51; | |
10442 } | |
10443 } | |
10444 } | |
10445 basic_json_parser_44: | |
10446 { | |
10447 last_token_type = token_type::value_integer; | |
10448 break; | |
10449 } | |
10450 basic_json_parser_45: | |
10451 yyaccept = 2; | |
10452 m_marker = ++m_cursor; | |
10453 if ((m_limit - m_cursor) < 3) | |
10454 { | |
10455 fill_line_buffer(3); // LCOV_EXCL_LINE | |
10456 } | |
10457 yych = *m_cursor; | |
10458 if (yych <= '9') | |
10459 { | |
10460 if (yych == '.') | |
10461 { | |
10462 goto basic_json_parser_47; | |
10463 } | |
10464 if (yych <= '/') | |
10465 { | |
10466 goto basic_json_parser_44; | |
10467 } | |
10468 goto basic_json_parser_45; | |
10469 } | |
10470 else | |
10471 { | |
10472 if (yych <= 'E') | |
10473 { | |
10474 if (yych <= 'D') | |
10475 { | |
10476 goto basic_json_parser_44; | |
10477 } | |
10478 goto basic_json_parser_51; | |
10479 } | |
10480 else | |
10481 { | |
10482 if (yych == 'e') | |
10483 { | |
10484 goto basic_json_parser_51; | |
10485 } | |
10486 goto basic_json_parser_44; | |
10487 } | |
10488 } | |
10489 basic_json_parser_47: | |
10490 yych = *++m_cursor; | |
10491 if (yych <= '/') | |
10492 { | |
10493 goto basic_json_parser_32; | |
10494 } | |
10495 if (yych <= '9') | |
10496 { | |
10497 goto basic_json_parser_56; | |
10498 } | |
10499 goto basic_json_parser_32; | |
10500 basic_json_parser_48: | |
10501 ++m_cursor; | |
10502 if (m_limit <= m_cursor) | |
10503 { | |
10504 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10505 } | |
10506 yych = *m_cursor; | |
10507 if (yych <= '/') | |
10508 { | |
10509 goto basic_json_parser_50; | |
10510 } | |
10511 if (yych <= '9') | |
10512 { | |
10513 goto basic_json_parser_48; | |
10514 } | |
10515 basic_json_parser_50: | |
10516 { | |
10517 last_token_type = token_type::parse_error; | |
10518 break; | |
10519 } | |
10520 basic_json_parser_51: | |
10521 yych = *++m_cursor; | |
10522 if (yych <= ',') | |
10523 { | |
10524 if (yych == '+') | |
10525 { | |
10526 goto basic_json_parser_59; | |
10527 } | |
10528 goto basic_json_parser_32; | |
10529 } | |
10530 else | |
10531 { | |
10532 if (yych <= '-') | |
10533 { | |
10534 goto basic_json_parser_59; | |
10535 } | |
10536 if (yych <= '/') | |
10537 { | |
10538 goto basic_json_parser_32; | |
10539 } | |
10540 if (yych <= '9') | |
10541 { | |
10542 goto basic_json_parser_60; | |
10543 } | |
10544 goto basic_json_parser_32; | |
10545 } | |
10546 basic_json_parser_52: | |
10547 yych = *++m_cursor; | |
10548 if (yych == 'l') | |
10549 { | |
10550 goto basic_json_parser_62; | |
10551 } | |
10552 goto basic_json_parser_32; | |
10553 basic_json_parser_53: | |
10554 yych = *++m_cursor; | |
10555 if (yych == 'l') | |
10556 { | |
10557 goto basic_json_parser_63; | |
10558 } | |
10559 goto basic_json_parser_32; | |
10560 basic_json_parser_54: | |
10561 yych = *++m_cursor; | |
10562 if (yych == 'u') | |
10563 { | |
10564 goto basic_json_parser_64; | |
10565 } | |
10566 goto basic_json_parser_32; | |
10567 basic_json_parser_55: | |
10568 ++m_cursor; | |
10569 if (m_limit <= m_cursor) | |
10570 { | |
10571 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10572 } | |
10573 yych = *m_cursor; | |
10574 if (yych <= '@') | |
10575 { | |
10576 if (yych <= '/') | |
10577 { | |
10578 goto basic_json_parser_32; | |
10579 } | |
10580 if (yych <= '9') | |
10581 { | |
10582 goto basic_json_parser_65; | |
10583 } | |
10584 goto basic_json_parser_32; | |
10585 } | |
10586 else | |
10587 { | |
10588 if (yych <= 'F') | |
10589 { | |
10590 goto basic_json_parser_65; | |
10591 } | |
10592 if (yych <= '`') | |
10593 { | |
10594 goto basic_json_parser_32; | |
10595 } | |
10596 if (yych <= 'f') | |
10597 { | |
10598 goto basic_json_parser_65; | |
10599 } | |
10600 goto basic_json_parser_32; | |
10601 } | |
10602 basic_json_parser_56: | |
10603 yyaccept = 3; | |
10604 m_marker = ++m_cursor; | |
10605 if ((m_limit - m_cursor) < 3) | |
10606 { | |
10607 fill_line_buffer(3); // LCOV_EXCL_LINE | |
10608 } | |
10609 yych = *m_cursor; | |
10610 if (yych <= 'D') | |
10611 { | |
10612 if (yych <= '/') | |
10613 { | |
10614 goto basic_json_parser_58; | |
10615 } | |
10616 if (yych <= '9') | |
10617 { | |
10618 goto basic_json_parser_56; | |
10619 } | |
10620 } | |
10621 else | |
10622 { | |
10623 if (yych <= 'E') | |
10624 { | |
10625 goto basic_json_parser_51; | |
10626 } | |
10627 if (yych == 'e') | |
10628 { | |
10629 goto basic_json_parser_51; | |
10630 } | |
10631 } | |
10632 basic_json_parser_58: | |
10633 { | |
10634 last_token_type = token_type::value_float; | |
10635 break; | |
10636 } | |
10637 basic_json_parser_59: | |
10638 yych = *++m_cursor; | |
10639 if (yych <= '/') | |
10640 { | |
10641 goto basic_json_parser_32; | |
10642 } | |
10643 if (yych >= ':') | |
10644 { | |
10645 goto basic_json_parser_32; | |
10646 } | |
10647 basic_json_parser_60: | |
10648 ++m_cursor; | |
10649 if (m_limit <= m_cursor) | |
10650 { | |
10651 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10652 } | |
10653 yych = *m_cursor; | |
10654 if (yych <= '/') | |
10655 { | |
10656 goto basic_json_parser_58; | |
10657 } | |
10658 if (yych <= '9') | |
10659 { | |
10660 goto basic_json_parser_60; | |
10661 } | |
10662 goto basic_json_parser_58; | |
10663 basic_json_parser_62: | |
10664 yych = *++m_cursor; | |
10665 if (yych == 's') | |
10666 { | |
10667 goto basic_json_parser_66; | |
10668 } | |
10669 goto basic_json_parser_32; | |
10670 basic_json_parser_63: | |
10671 yych = *++m_cursor; | |
10672 if (yych == 'l') | |
10673 { | |
10674 goto basic_json_parser_67; | |
10675 } | |
10676 goto basic_json_parser_32; | |
10677 basic_json_parser_64: | |
10678 yych = *++m_cursor; | |
10679 if (yych == 'e') | |
10680 { | |
10681 goto basic_json_parser_69; | |
10682 } | |
10683 goto basic_json_parser_32; | |
10684 basic_json_parser_65: | |
10685 ++m_cursor; | |
10686 if (m_limit <= m_cursor) | |
10687 { | |
10688 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10689 } | |
10690 yych = *m_cursor; | |
10691 if (yych <= '@') | |
10692 { | |
10693 if (yych <= '/') | |
10694 { | |
10695 goto basic_json_parser_32; | |
10696 } | |
10697 if (yych <= '9') | |
10698 { | |
10699 goto basic_json_parser_71; | |
10700 } | |
10701 goto basic_json_parser_32; | |
10702 } | |
10703 else | |
10704 { | |
10705 if (yych <= 'F') | |
10706 { | |
10707 goto basic_json_parser_71; | |
10708 } | |
10709 if (yych <= '`') | |
10710 { | |
10711 goto basic_json_parser_32; | |
10712 } | |
10713 if (yych <= 'f') | |
10714 { | |
10715 goto basic_json_parser_71; | |
10716 } | |
10717 goto basic_json_parser_32; | |
10718 } | |
10719 basic_json_parser_66: | |
10720 yych = *++m_cursor; | |
10721 if (yych == 'e') | |
10722 { | |
10723 goto basic_json_parser_72; | |
10724 } | |
10725 goto basic_json_parser_32; | |
10726 basic_json_parser_67: | |
10727 ++m_cursor; | |
10728 { | |
10729 last_token_type = token_type::literal_null; | |
10730 break; | |
10731 } | |
10732 basic_json_parser_69: | |
10733 ++m_cursor; | |
10734 { | |
10735 last_token_type = token_type::literal_true; | |
10736 break; | |
10737 } | |
10738 basic_json_parser_71: | |
10739 ++m_cursor; | |
10740 if (m_limit <= m_cursor) | |
10741 { | |
10742 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10743 } | |
10744 yych = *m_cursor; | |
10745 if (yych <= '@') | |
10746 { | |
10747 if (yych <= '/') | |
10748 { | |
10749 goto basic_json_parser_32; | |
10750 } | |
10751 if (yych <= '9') | |
10752 { | |
10753 goto basic_json_parser_74; | |
10754 } | |
10755 goto basic_json_parser_32; | |
10756 } | |
10757 else | |
10758 { | |
10759 if (yych <= 'F') | |
10760 { | |
10761 goto basic_json_parser_74; | |
10762 } | |
10763 if (yych <= '`') | |
10764 { | |
10765 goto basic_json_parser_32; | |
10766 } | |
10767 if (yych <= 'f') | |
10768 { | |
10769 goto basic_json_parser_74; | |
10770 } | |
10771 goto basic_json_parser_32; | |
10772 } | |
10773 basic_json_parser_72: | |
10774 ++m_cursor; | |
10775 { | |
10776 last_token_type = token_type::literal_false; | |
10777 break; | |
10778 } | |
10779 basic_json_parser_74: | |
10780 ++m_cursor; | |
10781 if (m_limit <= m_cursor) | |
10782 { | |
10783 fill_line_buffer(1); // LCOV_EXCL_LINE | |
10784 } | |
10785 yych = *m_cursor; | |
10786 if (yych <= '@') | |
10787 { | |
10788 if (yych <= '/') | |
10789 { | |
10790 goto basic_json_parser_32; | |
10791 } | |
10792 if (yych <= '9') | |
10793 { | |
10794 goto basic_json_parser_30; | |
10795 } | |
10796 goto basic_json_parser_32; | |
10797 } | |
10798 else | |
10799 { | |
10800 if (yych <= 'F') | |
10801 { | |
10802 goto basic_json_parser_30; | |
10803 } | |
10804 if (yych <= '`') | |
10805 { | |
10806 goto basic_json_parser_32; | |
10807 } | |
10808 if (yych <= 'f') | |
10809 { | |
10810 goto basic_json_parser_30; | |
10811 } | |
10812 goto basic_json_parser_32; | |
10813 } | |
10814 } | |
10815 | |
10816 } | |
10817 | |
10818 return last_token_type; | |
10819 } | |
10820 | |
10821 /*! | |
10822 @brief append data from the stream to the line buffer | |
10823 | |
10824 This function is called by the scan() function when the end of the | |
10825 buffer (`m_limit`) is reached and the `m_cursor` pointer cannot be | |
10826 incremented without leaving the limits of the line buffer. Note re2c | |
10827 decides when to call this function. | |
10828 | |
10829 If the lexer reads from contiguous storage, there is no trailing null | |
10830 byte. Therefore, this function must make sure to add these padding | |
10831 null bytes. | |
10832 | |
10833 If the lexer reads from an input stream, this function reads the next | |
10834 line of the input. | |
10835 | |
10836 @pre | |
10837 p p p p p p u u u u u x . . . . . . | |
10838 ^ ^ ^ ^ | |
10839 m_content m_start | m_limit | |
10840 m_cursor | |
10841 | |
10842 @post | |
10843 u u u u u x x x x x x x . . . . . . | |
10844 ^ ^ ^ | |
10845 | m_cursor m_limit | |
10846 m_start | |
10847 m_content | |
10848 */ | |
10849 void fill_line_buffer(size_t n = 0) | |
10850 { | |
10851 // if line buffer is used, m_content points to its data | |
10852 assert(m_line_buffer.empty() | |
10853 or m_content == reinterpret_cast<const lexer_char_t*>(m_line_buffer.data())); | |
10854 | |
10855 // if line buffer is used, m_limit is set past the end of its data | |
10856 assert(m_line_buffer.empty() | |
10857 or m_limit == m_content + m_line_buffer.size()); | |
10858 | |
10859 // pointer relationships | |
10860 assert(m_content <= m_start); | |
10861 assert(m_start <= m_cursor); | |
10862 assert(m_cursor <= m_limit); | |
10863 assert(m_marker == nullptr or m_marker <= m_limit); | |
10864 | |
10865 // number of processed characters (p) | |
10866 const auto num_processed_chars = static_cast<size_t>(m_start - m_content); | |
10867 // offset for m_marker wrt. to m_start | |
10868 const auto offset_marker = (m_marker == nullptr) ? 0 : m_marker - m_start; | |
10869 // number of unprocessed characters (u) | |
10870 const auto offset_cursor = m_cursor - m_start; | |
10871 | |
10872 // no stream is used or end of file is reached | |
10873 if (m_stream == nullptr or m_stream->eof()) | |
10874 { | |
10875 // m_start may or may not be pointing into m_line_buffer at | |
10876 // this point. We trust the standard library to do the right | |
10877 // thing. See http://stackoverflow.com/q/28142011/266378 | |
10878 m_line_buffer.assign(m_start, m_limit); | |
10879 | |
10880 // append n characters to make sure that there is sufficient | |
10881 // space between m_cursor and m_limit | |
10882 m_line_buffer.append(1, '\x00'); | |
10883 if (n > 0) | |
10884 { | |
10885 m_line_buffer.append(n - 1, '\x01'); | |
10886 } | |
10887 } | |
10888 else | |
10889 { | |
10890 // delete processed characters from line buffer | |
10891 m_line_buffer.erase(0, num_processed_chars); | |
10892 // read next line from input stream | |
10893 m_line_buffer_tmp.clear(); | |
10894 std::getline(*m_stream, m_line_buffer_tmp, '\n'); | |
10895 | |
10896 // add line with newline symbol to the line buffer | |
10897 m_line_buffer += m_line_buffer_tmp; | |
10898 m_line_buffer.push_back('\n'); | |
10899 } | |
10900 | |
10901 // set pointers | |
10902 m_content = reinterpret_cast<const lexer_char_t*>(m_line_buffer.data()); | |
10903 assert(m_content != nullptr); | |
10904 m_start = m_content; | |
10905 m_marker = m_start + offset_marker; | |
10906 m_cursor = m_start + offset_cursor; | |
10907 m_limit = m_start + m_line_buffer.size(); | |
10908 } | |
10909 | |
10910 /// return string representation of last read token | |
10911 string_t get_token_string() const | |
10912 { | |
10913 assert(m_start != nullptr); | |
10914 return string_t(reinterpret_cast<typename string_t::const_pointer>(m_start), | |
10915 static_cast<size_t>(m_cursor - m_start)); | |
10916 } | |
10917 | |
10918 /*! | |
10919 @brief return string value for string tokens | |
10920 | |
10921 The function iterates the characters between the opening and closing | |
10922 quotes of the string value. The complete string is the range | |
10923 [m_start,m_cursor). Consequently, we iterate from m_start+1 to | |
10924 m_cursor-1. | |
10925 | |
10926 We differentiate two cases: | |
10927 | |
10928 1. Escaped characters. In this case, a new character is constructed | |
10929 according to the nature of the escape. Some escapes create new | |
10930 characters (e.g., `"\\n"` is replaced by `"\n"`), some are copied | |
10931 as is (e.g., `"\\\\"`). Furthermore, Unicode escapes of the shape | |
10932 `"\\uxxxx"` need special care. In this case, to_unicode takes care | |
10933 of the construction of the values. | |
10934 2. Unescaped characters are copied as is. | |
10935 | |
10936 @pre `m_cursor - m_start >= 2`, meaning the length of the last token | |
10937 is at least 2 bytes which is trivially true for any string (which | |
10938 consists of at least two quotes). | |
10939 | |
10940 " c1 c2 c3 ... " | |
10941 ^ ^ | |
10942 m_start m_cursor | |
10943 | |
10944 @complexity Linear in the length of the string.\n | |
10945 | |
10946 Lemma: The loop body will always terminate.\n | |
10947 | |
10948 Proof (by contradiction): Assume the loop body does not terminate. As | |
10949 the loop body does not contain another loop, one of the called | |
10950 functions must never return. The called functions are `std::strtoul` | |
10951 and to_unicode. Neither function can loop forever, so the loop body | |
10952 will never loop forever which contradicts the assumption that the loop | |
10953 body does not terminate, q.e.d.\n | |
10954 | |
10955 Lemma: The loop condition for the for loop is eventually false.\n | |
10956 | |
10957 Proof (by contradiction): Assume the loop does not terminate. Due to | |
10958 the above lemma, this can only be due to a tautological loop | |
10959 condition; that is, the loop condition i < m_cursor - 1 must always be | |
10960 true. Let x be the change of i for any loop iteration. Then | |
10961 m_start + 1 + x < m_cursor - 1 must hold to loop indefinitely. This | |
10962 can be rephrased to m_cursor - m_start - 2 > x. With the | |
10963 precondition, we x <= 0, meaning that the loop condition holds | |
10964 indefinitely if i is always decreased. However, observe that the value | |
10965 of i is strictly increasing with each iteration, as it is incremented | |
10966 by 1 in the iteration expression and never decremented inside the loop | |
10967 body. Hence, the loop condition will eventually be false which | |
10968 contradicts the assumption that the loop condition is a tautology, | |
10969 q.e.d. | |
10970 | |
10971 @return string value of current token without opening and closing | |
10972 quotes | |
10973 @throw std::out_of_range if to_unicode fails | |
10974 */ | |
10975 string_t get_string() const | |
10976 { | |
10977 assert(m_cursor - m_start >= 2); | |
10978 | |
10979 string_t result; | |
10980 result.reserve(static_cast<size_t>(m_cursor - m_start - 2)); | |
10981 | |
10982 // iterate the result between the quotes | |
10983 for (const lexer_char_t* i = m_start + 1; i < m_cursor - 1; ++i) | |
10984 { | |
10985 // find next escape character | |
10986 auto e = std::find(i, m_cursor - 1, '\\'); | |
10987 if (e != i) | |
10988 { | |
10989 // see https://github.com/nlohmann/json/issues/365#issuecomment-262874705 | |
10990 for (auto k = i; k < e; k++) | |
10991 { | |
10992 result.push_back(static_cast<typename string_t::value_type>(*k)); | |
10993 } | |
10994 i = e - 1; // -1 because of ++i | |
10995 } | |
10996 else | |
10997 { | |
10998 // processing escaped character | |
10999 // read next character | |
11000 ++i; | |
11001 | |
11002 switch (*i) | |
11003 { | |
11004 // the default escapes | |
11005 case 't': | |
11006 { | |
11007 result += "\t"; | |
11008 break; | |
11009 } | |
11010 case 'b': | |
11011 { | |
11012 result += "\b"; | |
11013 break; | |
11014 } | |
11015 case 'f': | |
11016 { | |
11017 result += "\f"; | |
11018 break; | |
11019 } | |
11020 case 'n': | |
11021 { | |
11022 result += "\n"; | |
11023 break; | |
11024 } | |
11025 case 'r': | |
11026 { | |
11027 result += "\r"; | |
11028 break; | |
11029 } | |
11030 case '\\': | |
11031 { | |
11032 result += "\\"; | |
11033 break; | |
11034 } | |
11035 case '/': | |
11036 { | |
11037 result += "/"; | |
11038 break; | |
11039 } | |
11040 case '"': | |
11041 { | |
11042 result += "\""; | |
11043 break; | |
11044 } | |
11045 | |
11046 // unicode | |
11047 case 'u': | |
11048 { | |
11049 // get code xxxx from uxxxx | |
11050 auto codepoint = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>(i + 1), | |
11051 4).c_str(), nullptr, 16); | |
11052 | |
11053 // check if codepoint is a high surrogate | |
11054 if (codepoint >= 0xD800 and codepoint <= 0xDBFF) | |
11055 { | |
11056 // make sure there is a subsequent unicode | |
11057 if ((i + 6 >= m_limit) or * (i + 5) != '\\' or * (i + 6) != 'u') | |
11058 { | |
11059 JSON_THROW(std::invalid_argument("missing low surrogate")); | |
11060 } | |
11061 | |
11062 // get code yyyy from uxxxx\uyyyy | |
11063 auto codepoint2 = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer> | |
11064 (i + 7), 4).c_str(), nullptr, 16); | |
11065 result += to_unicode(codepoint, codepoint2); | |
11066 // skip the next 10 characters (xxxx\uyyyy) | |
11067 i += 10; | |
11068 } | |
11069 else if (codepoint >= 0xDC00 and codepoint <= 0xDFFF) | |
11070 { | |
11071 // we found a lone low surrogate | |
11072 JSON_THROW(std::invalid_argument("missing high surrogate")); | |
11073 } | |
11074 else | |
11075 { | |
11076 // add unicode character(s) | |
11077 result += to_unicode(codepoint); | |
11078 // skip the next four characters (xxxx) | |
11079 i += 4; | |
11080 } | |
11081 break; | |
11082 } | |
11083 } | |
11084 } | |
11085 } | |
11086 | |
11087 return result; | |
11088 } | |
11089 | |
11090 | |
11091 /*! | |
11092 @brief parse string into a built-in arithmetic type as if the current | |
11093 locale is POSIX. | |
11094 | |
11095 @note in floating-point case strtod may parse past the token's end - | |
11096 this is not an error | |
11097 | |
11098 @note any leading blanks are not handled | |
11099 */ | |
11100 struct strtonum | |
11101 { | |
11102 public: | |
11103 strtonum(const char* start, const char* end) | |
11104 : m_start(start), m_end(end) | |
11105 {} | |
11106 | |
11107 /*! | |
11108 @return true iff parsed successfully as number of type T | |
11109 | |
11110 @param[in,out] val shall contain parsed value, or undefined value | |
11111 if could not parse | |
11112 */ | |
11113 template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value>::type> | |
11114 bool to(T& val) const | |
11115 { | |
11116 return parse(val, std::is_integral<T>()); | |
11117 } | |
11118 | |
11119 private: | |
11120 const char* const m_start = nullptr; | |
11121 const char* const m_end = nullptr; | |
11122 | |
11123 // floating-point conversion | |
11124 | |
11125 // overloaded wrappers for strtod/strtof/strtold | |
11126 // that will be called from parse<floating_point_t> | |
11127 static void strtof(float& f, const char* str, char** endptr) | |
11128 { | |
11129 f = std::strtof(str, endptr); | |
11130 } | |
11131 | |
11132 static void strtof(double& f, const char* str, char** endptr) | |
11133 { | |
11134 f = std::strtod(str, endptr); | |
11135 } | |
11136 | |
11137 static void strtof(long double& f, const char* str, char** endptr) | |
11138 { | |
11139 f = std::strtold(str, endptr); | |
11140 } | |
11141 | |
11142 template<typename T> | |
11143 bool parse(T& value, /*is_integral=*/std::false_type) const | |
11144 { | |
11145 // replace decimal separator with locale-specific version, | |
11146 // when necessary; data will point to either the original | |
11147 // string, or buf, or tempstr containing the fixed string. | |
11148 std::string tempstr; | |
11149 std::array<char, 64> buf; | |
11150 const size_t len = static_cast<size_t>(m_end - m_start); | |
11151 | |
11152 // lexer will reject empty numbers | |
11153 assert(len > 0); | |
11154 | |
11155 // since dealing with strtod family of functions, we're | |
11156 // getting the decimal point char from the C locale facilities | |
11157 // instead of C++'s numpunct facet of the current std::locale | |
11158 const auto loc = localeconv(); | |
11159 assert(loc != nullptr); | |
11160 const char decimal_point_char = (loc->decimal_point == nullptr) ? '.' : loc->decimal_point[0]; | |
11161 | |
11162 const char* data = m_start; | |
11163 | |
11164 if (decimal_point_char != '.') | |
11165 { | |
11166 const size_t ds_pos = static_cast<size_t>(std::find(m_start, m_end, '.') - m_start); | |
11167 | |
11168 if (ds_pos != len) | |
11169 { | |
11170 // copy the data into the local buffer or tempstr, if | |
11171 // buffer is too small; replace decimal separator, and | |
11172 // update data to point to the modified bytes | |
11173 if ((len + 1) < buf.size()) | |
11174 { | |
11175 std::copy(m_start, m_end, buf.begin()); | |
11176 buf[len] = 0; | |
11177 buf[ds_pos] = decimal_point_char; | |
11178 data = buf.data(); | |
11179 } | |
11180 else | |
11181 { | |
11182 tempstr.assign(m_start, m_end); | |
11183 tempstr[ds_pos] = decimal_point_char; | |
11184 data = tempstr.c_str(); | |
11185 } | |
11186 } | |
11187 } | |
11188 | |
11189 char* endptr = nullptr; | |
11190 value = 0; | |
11191 // this calls appropriate overload depending on T | |
11192 strtof(value, data, &endptr); | |
11193 | |
11194 // parsing was successful iff strtof parsed exactly the number | |
11195 // of characters determined by the lexer (len) | |
11196 const bool ok = (endptr == (data + len)); | |
11197 | |
11198 if (ok and (value == static_cast<T>(0.0)) and (*data == '-')) | |
11199 { | |
11200 // some implementations forget to negate the zero | |
11201 value = -0.0; | |
11202 } | |
11203 | |
11204 return ok; | |
11205 } | |
11206 | |
11207 // integral conversion | |
11208 | |
11209 signed long long parse_integral(char** endptr, /*is_signed*/std::true_type) const | |
11210 { | |
11211 return std::strtoll(m_start, endptr, 10); | |
11212 } | |
11213 | |
11214 unsigned long long parse_integral(char** endptr, /*is_signed*/std::false_type) const | |
11215 { | |
11216 return std::strtoull(m_start, endptr, 10); | |
11217 } | |
11218 | |
11219 template<typename T> | |
11220 bool parse(T& value, /*is_integral=*/std::true_type) const | |
11221 { | |
11222 char* endptr = nullptr; | |
11223 errno = 0; // these are thread-local | |
11224 const auto x = parse_integral(&endptr, std::is_signed<T>()); | |
11225 | |
11226 // called right overload? | |
11227 static_assert(std::is_signed<T>() == std::is_signed<decltype(x)>(), ""); | |
11228 | |
11229 value = static_cast<T>(x); | |
11230 | |
11231 return (x == static_cast<decltype(x)>(value)) // x fits into destination T | |
11232 and (x < 0) == (value < 0) // preserved sign | |
11233 //and ((x != 0) or is_integral()) // strto[u]ll did nto fail | |
11234 and (errno == 0) // strto[u]ll did not overflow | |
11235 and (m_start < m_end) // token was not empty | |
11236 and (endptr == m_end); // parsed entire token exactly | |
11237 } | |
11238 }; | |
11239 | |
11240 /*! | |
11241 @brief return number value for number tokens | |
11242 | |
11243 This function translates the last token into the most appropriate | |
11244 number type (either integer, unsigned integer or floating point), | |
11245 which is passed back to the caller via the result parameter. | |
11246 | |
11247 integral numbers that don't fit into the the range of the respective | |
11248 type are parsed as number_float_t | |
11249 | |
11250 floating-point values do not satisfy std::isfinite predicate | |
11251 are converted to value_t::null | |
11252 | |
11253 throws if the entire string [m_start .. m_cursor) cannot be | |
11254 interpreted as a number | |
11255 | |
11256 @param[out] result @ref basic_json object to receive the number. | |
11257 @param[in] token the type of the number token | |
11258 */ | |
11259 bool get_number(basic_json& result, const token_type token) const | |
11260 { | |
11261 assert(m_start != nullptr); | |
11262 assert(m_start < m_cursor); | |
11263 assert((token == token_type::value_unsigned) or | |
11264 (token == token_type::value_integer) or | |
11265 (token == token_type::value_float)); | |
11266 | |
11267 strtonum num_converter(reinterpret_cast<const char*>(m_start), | |
11268 reinterpret_cast<const char*>(m_cursor)); | |
11269 | |
11270 switch (token) | |
11271 { | |
11272 case lexer::token_type::value_unsigned: | |
11273 { | |
11274 number_unsigned_t val; | |
11275 if (num_converter.to(val)) | |
11276 { | |
11277 // parsing successful | |
11278 result.m_type = value_t::number_unsigned; | |
11279 result.m_value = val; | |
11280 return true; | |
11281 } | |
11282 break; | |
11283 } | |
11284 | |
11285 case lexer::token_type::value_integer: | |
11286 { | |
11287 number_integer_t val; | |
11288 if (num_converter.to(val)) | |
11289 { | |
11290 // parsing successful | |
11291 result.m_type = value_t::number_integer; | |
11292 result.m_value = val; | |
11293 return true; | |
11294 } | |
11295 break; | |
11296 } | |
11297 | |
11298 default: | |
11299 { | |
11300 break; | |
11301 } | |
11302 } | |
11303 | |
11304 // parse float (either explicitly or because a previous conversion | |
11305 // failed) | |
11306 number_float_t val; | |
11307 if (num_converter.to(val)) | |
11308 { | |
11309 // parsing successful | |
11310 result.m_type = value_t::number_float; | |
11311 result.m_value = val; | |
11312 | |
11313 // replace infinity and NAN by null | |
11314 if (not std::isfinite(result.m_value.number_float)) | |
11315 { | |
11316 result.m_type = value_t::null; | |
11317 result.m_value = basic_json::json_value(); | |
11318 } | |
11319 | |
11320 return true; | |
11321 } | |
11322 | |
11323 // couldn't parse number in any format | |
11324 return false; | |
11325 } | |
11326 | |
11327 private: | |
11328 /// optional input stream | |
11329 std::istream* m_stream = nullptr; | |
11330 /// line buffer buffer for m_stream | |
11331 string_t m_line_buffer {}; | |
11332 /// used for filling m_line_buffer | |
11333 string_t m_line_buffer_tmp {}; | |
11334 /// the buffer pointer | |
11335 const lexer_char_t* m_content = nullptr; | |
11336 /// pointer to the beginning of the current symbol | |
11337 const lexer_char_t* m_start = nullptr; | |
11338 /// pointer for backtracking information | |
11339 const lexer_char_t* m_marker = nullptr; | |
11340 /// pointer to the current symbol | |
11341 const lexer_char_t* m_cursor = nullptr; | |
11342 /// pointer to the end of the buffer | |
11343 const lexer_char_t* m_limit = nullptr; | |
11344 /// the last token type | |
11345 token_type last_token_type = token_type::end_of_input; | |
11346 }; | |
11347 | |
11348 /*! | |
11349 @brief syntax analysis | |
11350 | |
11351 This class implements a recursive decent parser. | |
11352 */ | |
11353 class parser | |
11354 { | |
11355 public: | |
11356 /// a parser reading from a string literal | |
11357 parser(const char* buff, const parser_callback_t cb = nullptr) | |
11358 : callback(cb), | |
11359 m_lexer(reinterpret_cast<const typename lexer::lexer_char_t*>(buff), std::strlen(buff)) | |
11360 {} | |
11361 | |
11362 /// a parser reading from an input stream | |
11363 parser(std::istream& is, const parser_callback_t cb = nullptr) | |
11364 : callback(cb), m_lexer(is) | |
11365 {} | |
11366 | |
11367 /// a parser reading from an iterator range with contiguous storage | |
11368 template<class IteratorType, typename std::enable_if< | |
11369 std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value | |
11370 , int>::type | |
11371 = 0> | |
11372 parser(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr) | |
11373 : callback(cb), | |
11374 m_lexer(reinterpret_cast<const typename lexer::lexer_char_t*>(&(*first)), | |
11375 static_cast<size_t>(std::distance(first, last))) | |
11376 {} | |
11377 | |
11378 /// public parser interface | |
11379 basic_json parse() | |
11380 { | |
11381 // read first token | |
11382 get_token(); | |
11383 | |
11384 basic_json result = parse_internal(true); | |
11385 result.assert_invariant(); | |
11386 | |
11387 expect(lexer::token_type::end_of_input); | |
11388 | |
11389 // return parser result and replace it with null in case the | |
11390 // top-level value was discarded by the callback function | |
11391 return result.is_discarded() ? basic_json() : std::move(result); | |
11392 } | |
11393 | |
11394 private: | |
11395 /// the actual parser | |
11396 basic_json parse_internal(bool keep) | |
11397 { | |
11398 auto result = basic_json(value_t::discarded); | |
11399 | |
11400 switch (last_token) | |
11401 { | |
11402 case lexer::token_type::begin_object: | |
11403 { | |
11404 if (keep and (not callback | |
11405 or ((keep = callback(depth++, parse_event_t::object_start, result)) != 0))) | |
11406 { | |
11407 // explicitly set result to object to cope with {} | |
11408 result.m_type = value_t::object; | |
11409 result.m_value = value_t::object; | |
11410 } | |
11411 | |
11412 // read next token | |
11413 get_token(); | |
11414 | |
11415 // closing } -> we are done | |
11416 if (last_token == lexer::token_type::end_object) | |
11417 { | |
11418 get_token(); | |
11419 if (keep and callback and not callback(--depth, parse_event_t::object_end, result)) | |
11420 { | |
11421 result = basic_json(value_t::discarded); | |
11422 } | |
11423 return result; | |
11424 } | |
11425 | |
11426 // no comma is expected here | |
11427 unexpect(lexer::token_type::value_separator); | |
11428 | |
11429 // otherwise: parse key-value pairs | |
11430 do | |
11431 { | |
11432 // ugly, but could be fixed with loop reorganization | |
11433 if (last_token == lexer::token_type::value_separator) | |
11434 { | |
11435 get_token(); | |
11436 } | |
11437 | |
11438 // store key | |
11439 expect(lexer::token_type::value_string); | |
11440 const auto key = m_lexer.get_string(); | |
11441 | |
11442 bool keep_tag = false; | |
11443 if (keep) | |
11444 { | |
11445 if (callback) | |
11446 { | |
11447 basic_json k(key); | |
11448 keep_tag = callback(depth, parse_event_t::key, k); | |
11449 } | |
11450 else | |
11451 { | |
11452 keep_tag = true; | |
11453 } | |
11454 } | |
11455 | |
11456 // parse separator (:) | |
11457 get_token(); | |
11458 expect(lexer::token_type::name_separator); | |
11459 | |
11460 // parse and add value | |
11461 get_token(); | |
11462 auto value = parse_internal(keep); | |
11463 if (keep and keep_tag and not value.is_discarded()) | |
11464 { | |
11465 result[key] = std::move(value); | |
11466 } | |
11467 } | |
11468 while (last_token == lexer::token_type::value_separator); | |
11469 | |
11470 // closing } | |
11471 expect(lexer::token_type::end_object); | |
11472 get_token(); | |
11473 if (keep and callback and not callback(--depth, parse_event_t::object_end, result)) | |
11474 { | |
11475 result = basic_json(value_t::discarded); | |
11476 } | |
11477 | |
11478 return result; | |
11479 } | |
11480 | |
11481 case lexer::token_type::begin_array: | |
11482 { | |
11483 if (keep and (not callback | |
11484 or ((keep = callback(depth++, parse_event_t::array_start, result)) != 0))) | |
11485 { | |
11486 // explicitly set result to object to cope with [] | |
11487 result.m_type = value_t::array; | |
11488 result.m_value = value_t::array; | |
11489 } | |
11490 | |
11491 // read next token | |
11492 get_token(); | |
11493 | |
11494 // closing ] -> we are done | |
11495 if (last_token == lexer::token_type::end_array) | |
11496 { | |
11497 get_token(); | |
11498 if (callback and not callback(--depth, parse_event_t::array_end, result)) | |
11499 { | |
11500 result = basic_json(value_t::discarded); | |
11501 } | |
11502 return result; | |
11503 } | |
11504 | |
11505 // no comma is expected here | |
11506 unexpect(lexer::token_type::value_separator); | |
11507 | |
11508 // otherwise: parse values | |
11509 do | |
11510 { | |
11511 // ugly, but could be fixed with loop reorganization | |
11512 if (last_token == lexer::token_type::value_separator) | |
11513 { | |
11514 get_token(); | |
11515 } | |
11516 | |
11517 // parse value | |
11518 auto value = parse_internal(keep); | |
11519 if (keep and not value.is_discarded()) | |
11520 { | |
11521 result.push_back(std::move(value)); | |
11522 } | |
11523 } | |
11524 while (last_token == lexer::token_type::value_separator); | |
11525 | |
11526 // closing ] | |
11527 expect(lexer::token_type::end_array); | |
11528 get_token(); | |
11529 if (keep and callback and not callback(--depth, parse_event_t::array_end, result)) | |
11530 { | |
11531 result = basic_json(value_t::discarded); | |
11532 } | |
11533 | |
11534 return result; | |
11535 } | |
11536 | |
11537 case lexer::token_type::literal_null: | |
11538 { | |
11539 get_token(); | |
11540 result.m_type = value_t::null; | |
11541 break; | |
11542 } | |
11543 | |
11544 case lexer::token_type::value_string: | |
11545 { | |
11546 const auto s = m_lexer.get_string(); | |
11547 get_token(); | |
11548 result = basic_json(s); | |
11549 break; | |
11550 } | |
11551 | |
11552 case lexer::token_type::literal_true: | |
11553 { | |
11554 get_token(); | |
11555 result.m_type = value_t::boolean; | |
11556 result.m_value = true; | |
11557 break; | |
11558 } | |
11559 | |
11560 case lexer::token_type::literal_false: | |
11561 { | |
11562 get_token(); | |
11563 result.m_type = value_t::boolean; | |
11564 result.m_value = false; | |
11565 break; | |
11566 } | |
11567 | |
11568 case lexer::token_type::value_unsigned: | |
11569 case lexer::token_type::value_integer: | |
11570 case lexer::token_type::value_float: | |
11571 { | |
11572 m_lexer.get_number(result, last_token); | |
11573 get_token(); | |
11574 break; | |
11575 } | |
11576 | |
11577 default: | |
11578 { | |
11579 // the last token was unexpected | |
11580 unexpect(last_token); | |
11581 } | |
11582 } | |
11583 | |
11584 if (keep and callback and not callback(depth, parse_event_t::value, result)) | |
11585 { | |
11586 result = basic_json(value_t::discarded); | |
11587 } | |
11588 return result; | |
11589 } | |
11590 | |
11591 /// get next token from lexer | |
11592 typename lexer::token_type get_token() | |
11593 { | |
11594 last_token = m_lexer.scan(); | |
11595 return last_token; | |
11596 } | |
11597 | |
11598 void expect(typename lexer::token_type t) const | |
11599 { | |
11600 if (t != last_token) | |
11601 { | |
11602 std::string error_msg = "parse error - unexpected "; | |
11603 error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() + | |
11604 "'") : | |
11605 lexer::token_type_name(last_token)); | |
11606 error_msg += "; expected " + lexer::token_type_name(t); | |
11607 JSON_THROW(std::invalid_argument(error_msg)); | |
11608 } | |
11609 } | |
11610 | |
11611 void unexpect(typename lexer::token_type t) const | |
11612 { | |
11613 if (t == last_token) | |
11614 { | |
11615 std::string error_msg = "parse error - unexpected "; | |
11616 error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() + | |
11617 "'") : | |
11618 lexer::token_type_name(last_token)); | |
11619 JSON_THROW(std::invalid_argument(error_msg)); | |
11620 } | |
11621 } | |
11622 | |
11623 private: | |
11624 /// current level of recursion | |
11625 int depth = 0; | |
11626 /// callback function | |
11627 const parser_callback_t callback = nullptr; | |
11628 /// the type of the last read token | |
11629 typename lexer::token_type last_token = lexer::token_type::uninitialized; | |
11630 /// the lexer | |
11631 lexer m_lexer; | |
11632 }; | |
11633 | |
11634 public: | |
11635 /*! | |
11636 @brief JSON Pointer | |
11637 | |
11638 A JSON pointer defines a string syntax for identifying a specific value | |
11639 within a JSON document. It can be used with functions `at` and | |
11640 `operator[]`. Furthermore, JSON pointers are the base for JSON patches. | |
11641 | |
11642 @sa [RFC 6901](https://tools.ietf.org/html/rfc6901) | |
11643 | |
11644 @since version 2.0.0 | |
11645 */ | |
11646 class json_pointer | |
11647 { | |
11648 /// allow basic_json to access private members | |
11649 friend class basic_json; | |
11650 | |
11651 public: | |
11652 /*! | |
11653 @brief create JSON pointer | |
11654 | |
11655 Create a JSON pointer according to the syntax described in | |
11656 [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). | |
11657 | |
11658 @param[in] s string representing the JSON pointer; if omitted, the | |
11659 empty string is assumed which references the whole JSON | |
11660 value | |
11661 | |
11662 @throw std::domain_error if reference token is nonempty and does not | |
11663 begin with a slash (`/`); example: `"JSON pointer must be empty or | |
11664 begin with /"` | |
11665 @throw std::domain_error if a tilde (`~`) is not followed by `0` | |
11666 (representing `~`) or `1` (representing `/`); example: `"escape error: | |
11667 ~ must be followed with 0 or 1"` | |
11668 | |
11669 @liveexample{The example shows the construction several valid JSON | |
11670 pointers as well as the exceptional behavior.,json_pointer} | |
11671 | |
11672 @since version 2.0.0 | |
11673 */ | |
11674 explicit json_pointer(const std::string& s = "") | |
11675 : reference_tokens(split(s)) | |
11676 {} | |
11677 | |
11678 /*! | |
11679 @brief return a string representation of the JSON pointer | |
11680 | |
11681 @invariant For each JSON pointer `ptr`, it holds: | |
11682 @code {.cpp} | |
11683 ptr == json_pointer(ptr.to_string()); | |
11684 @endcode | |
11685 | |
11686 @return a string representation of the JSON pointer | |
11687 | |
11688 @liveexample{The example shows the result of `to_string`., | |
11689 json_pointer__to_string} | |
11690 | |
11691 @since version 2.0.0 | |
11692 */ | |
11693 std::string to_string() const noexcept | |
11694 { | |
11695 return std::accumulate(reference_tokens.begin(), | |
11696 reference_tokens.end(), std::string{}, | |
11697 [](const std::string & a, const std::string & b) | |
11698 { | |
11699 return a + "/" + escape(b); | |
11700 }); | |
11701 } | |
11702 | |
11703 /// @copydoc to_string() | |
11704 operator std::string() const | |
11705 { | |
11706 return to_string(); | |
11707 } | |
11708 | |
11709 private: | |
11710 /// remove and return last reference pointer | |
11711 std::string pop_back() | |
11712 { | |
11713 if (is_root()) | |
11714 { | |
11715 JSON_THROW(std::domain_error("JSON pointer has no parent")); | |
11716 } | |
11717 | |
11718 auto last = reference_tokens.back(); | |
11719 reference_tokens.pop_back(); | |
11720 return last; | |
11721 } | |
11722 | |
11723 /// return whether pointer points to the root document | |
11724 bool is_root() const | |
11725 { | |
11726 return reference_tokens.empty(); | |
11727 } | |
11728 | |
11729 json_pointer top() const | |
11730 { | |
11731 if (is_root()) | |
11732 { | |
11733 JSON_THROW(std::domain_error("JSON pointer has no parent")); | |
11734 } | |
11735 | |
11736 json_pointer result = *this; | |
11737 result.reference_tokens = {reference_tokens[0]}; | |
11738 return result; | |
11739 } | |
11740 | |
11741 /*! | |
11742 @brief create and return a reference to the pointed to value | |
11743 | |
11744 @complexity Linear in the number of reference tokens. | |
11745 */ | |
11746 reference get_and_create(reference j) const | |
11747 { | |
11748 pointer result = &j; | |
11749 | |
11750 // in case no reference tokens exist, return a reference to the | |
11751 // JSON value j which will be overwritten by a primitive value | |
11752 for (const auto& reference_token : reference_tokens) | |
11753 { | |
11754 switch (result->m_type) | |
11755 { | |
11756 case value_t::null: | |
11757 { | |
11758 if (reference_token == "0") | |
11759 { | |
11760 // start a new array if reference token is 0 | |
11761 result = &result->operator[](0); | |
11762 } | |
11763 else | |
11764 { | |
11765 // start a new object otherwise | |
11766 result = &result->operator[](reference_token); | |
11767 } | |
11768 break; | |
11769 } | |
11770 | |
11771 case value_t::object: | |
11772 { | |
11773 // create an entry in the object | |
11774 result = &result->operator[](reference_token); | |
11775 break; | |
11776 } | |
11777 | |
11778 case value_t::array: | |
11779 { | |
11780 // create an entry in the array | |
11781 result = &result->operator[](static_cast<size_type>(std::stoi(reference_token))); | |
11782 break; | |
11783 } | |
11784 | |
11785 /* | |
11786 The following code is only reached if there exists a | |
11787 reference token _and_ the current value is primitive. In | |
11788 this case, we have an error situation, because primitive | |
11789 values may only occur as single value; that is, with an | |
11790 empty list of reference tokens. | |
11791 */ | |
11792 default: | |
11793 { | |
11794 JSON_THROW(std::domain_error("invalid value to unflatten")); | |
11795 } | |
11796 } | |
11797 } | |
11798 | |
11799 return *result; | |
11800 } | |
11801 | |
11802 /*! | |
11803 @brief return a reference to the pointed to value | |
11804 | |
11805 @note This version does not throw if a value is not present, but tries | |
11806 to create nested values instead. For instance, calling this function | |
11807 with pointer `"/this/that"` on a null value is equivalent to calling | |
11808 `operator[]("this").operator[]("that")` on that value, effectively | |
11809 changing the null value to an object. | |
11810 | |
11811 @param[in] ptr a JSON value | |
11812 | |
11813 @return reference to the JSON value pointed to by the JSON pointer | |
11814 | |
11815 @complexity Linear in the length of the JSON pointer. | |
11816 | |
11817 @throw std::out_of_range if the JSON pointer can not be resolved | |
11818 @throw std::domain_error if an array index begins with '0' | |
11819 @throw std::invalid_argument if an array index was not a number | |
11820 */ | |
11821 reference get_unchecked(pointer ptr) const | |
11822 { | |
11823 for (const auto& reference_token : reference_tokens) | |
11824 { | |
11825 // convert null values to arrays or objects before continuing | |
11826 if (ptr->m_type == value_t::null) | |
11827 { | |
11828 // check if reference token is a number | |
11829 const bool nums = std::all_of(reference_token.begin(), | |
11830 reference_token.end(), | |
11831 [](const char x) | |
11832 { | |
11833 return std::isdigit(x); | |
11834 }); | |
11835 | |
11836 // change value to array for numbers or "-" or to object | |
11837 // otherwise | |
11838 if (nums or reference_token == "-") | |
11839 { | |
11840 *ptr = value_t::array; | |
11841 } | |
11842 else | |
11843 { | |
11844 *ptr = value_t::object; | |
11845 } | |
11846 } | |
11847 | |
11848 switch (ptr->m_type) | |
11849 { | |
11850 case value_t::object: | |
11851 { | |
11852 // use unchecked object access | |
11853 ptr = &ptr->operator[](reference_token); | |
11854 break; | |
11855 } | |
11856 | |
11857 case value_t::array: | |
11858 { | |
11859 // error condition (cf. RFC 6901, Sect. 4) | |
11860 if (reference_token.size() > 1 and reference_token[0] == '0') | |
11861 { | |
11862 JSON_THROW(std::domain_error("array index must not begin with '0'")); | |
11863 } | |
11864 | |
11865 if (reference_token == "-") | |
11866 { | |
11867 // explicitly treat "-" as index beyond the end | |
11868 ptr = &ptr->operator[](ptr->m_value.array->size()); | |
11869 } | |
11870 else | |
11871 { | |
11872 // convert array index to number; unchecked access | |
11873 ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token))); | |
11874 } | |
11875 break; | |
11876 } | |
11877 | |
11878 default: | |
11879 { | |
11880 JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'")); | |
11881 } | |
11882 } | |
11883 } | |
11884 | |
11885 return *ptr; | |
11886 } | |
11887 | |
11888 reference get_checked(pointer ptr) const | |
11889 { | |
11890 for (const auto& reference_token : reference_tokens) | |
11891 { | |
11892 switch (ptr->m_type) | |
11893 { | |
11894 case value_t::object: | |
11895 { | |
11896 // note: at performs range check | |
11897 ptr = &ptr->at(reference_token); | |
11898 break; | |
11899 } | |
11900 | |
11901 case value_t::array: | |
11902 { | |
11903 if (reference_token == "-") | |
11904 { | |
11905 // "-" always fails the range check | |
11906 JSON_THROW(std::out_of_range("array index '-' (" + | |
11907 std::to_string(ptr->m_value.array->size()) + | |
11908 ") is out of range")); | |
11909 } | |
11910 | |
11911 // error condition (cf. RFC 6901, Sect. 4) | |
11912 if (reference_token.size() > 1 and reference_token[0] == '0') | |
11913 { | |
11914 JSON_THROW(std::domain_error("array index must not begin with '0'")); | |
11915 } | |
11916 | |
11917 // note: at performs range check | |
11918 ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token))); | |
11919 break; | |
11920 } | |
11921 | |
11922 default: | |
11923 { | |
11924 JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'")); | |
11925 } | |
11926 } | |
11927 } | |
11928 | |
11929 return *ptr; | |
11930 } | |
11931 | |
11932 /*! | |
11933 @brief return a const reference to the pointed to value | |
11934 | |
11935 @param[in] ptr a JSON value | |
11936 | |
11937 @return const reference to the JSON value pointed to by the JSON | |
11938 pointer | |
11939 */ | |
11940 const_reference get_unchecked(const_pointer ptr) const | |
11941 { | |
11942 for (const auto& reference_token : reference_tokens) | |
11943 { | |
11944 switch (ptr->m_type) | |
11945 { | |
11946 case value_t::object: | |
11947 { | |
11948 // use unchecked object access | |
11949 ptr = &ptr->operator[](reference_token); | |
11950 break; | |
11951 } | |
11952 | |
11953 case value_t::array: | |
11954 { | |
11955 if (reference_token == "-") | |
11956 { | |
11957 // "-" cannot be used for const access | |
11958 JSON_THROW(std::out_of_range("array index '-' (" + | |
11959 std::to_string(ptr->m_value.array->size()) + | |
11960 ") is out of range")); | |
11961 } | |
11962 | |
11963 // error condition (cf. RFC 6901, Sect. 4) | |
11964 if (reference_token.size() > 1 and reference_token[0] == '0') | |
11965 { | |
11966 JSON_THROW(std::domain_error("array index must not begin with '0'")); | |
11967 } | |
11968 | |
11969 // use unchecked array access | |
11970 ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token))); | |
11971 break; | |
11972 } | |
11973 | |
11974 default: | |
11975 { | |
11976 JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'")); | |
11977 } | |
11978 } | |
11979 } | |
11980 | |
11981 return *ptr; | |
11982 } | |
11983 | |
11984 const_reference get_checked(const_pointer ptr) const | |
11985 { | |
11986 for (const auto& reference_token : reference_tokens) | |
11987 { | |
11988 switch (ptr->m_type) | |
11989 { | |
11990 case value_t::object: | |
11991 { | |
11992 // note: at performs range check | |
11993 ptr = &ptr->at(reference_token); | |
11994 break; | |
11995 } | |
11996 | |
11997 case value_t::array: | |
11998 { | |
11999 if (reference_token == "-") | |
12000 { | |
12001 // "-" always fails the range check | |
12002 JSON_THROW(std::out_of_range("array index '-' (" + | |
12003 std::to_string(ptr->m_value.array->size()) + | |
12004 ") is out of range")); | |
12005 } | |
12006 | |
12007 // error condition (cf. RFC 6901, Sect. 4) | |
12008 if (reference_token.size() > 1 and reference_token[0] == '0') | |
12009 { | |
12010 JSON_THROW(std::domain_error("array index must not begin with '0'")); | |
12011 } | |
12012 | |
12013 // note: at performs range check | |
12014 ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token))); | |
12015 break; | |
12016 } | |
12017 | |
12018 default: | |
12019 { | |
12020 JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'")); | |
12021 } | |
12022 } | |
12023 } | |
12024 | |
12025 return *ptr; | |
12026 } | |
12027 | |
12028 /// split the string input to reference tokens | |
12029 static std::vector<std::string> split(const std::string& reference_string) | |
12030 { | |
12031 std::vector<std::string> result; | |
12032 | |
12033 // special case: empty reference string -> no reference tokens | |
12034 if (reference_string.empty()) | |
12035 { | |
12036 return result; | |
12037 } | |
12038 | |
12039 // check if nonempty reference string begins with slash | |
12040 if (reference_string[0] != '/') | |
12041 { | |
12042 JSON_THROW(std::domain_error("JSON pointer must be empty or begin with '/'")); | |
12043 } | |
12044 | |
12045 // extract the reference tokens: | |
12046 // - slash: position of the last read slash (or end of string) | |
12047 // - start: position after the previous slash | |
12048 for ( | |
12049 // search for the first slash after the first character | |
12050 size_t slash = reference_string.find_first_of('/', 1), | |
12051 // set the beginning of the first reference token | |
12052 start = 1; | |
12053 // we can stop if start == string::npos+1 = 0 | |
12054 start != 0; | |
12055 // set the beginning of the next reference token | |
12056 // (will eventually be 0 if slash == std::string::npos) | |
12057 start = slash + 1, | |
12058 // find next slash | |
12059 slash = reference_string.find_first_of('/', start)) | |
12060 { | |
12061 // use the text between the beginning of the reference token | |
12062 // (start) and the last slash (slash). | |
12063 auto reference_token = reference_string.substr(start, slash - start); | |
12064 | |
12065 // check reference tokens are properly escaped | |
12066 for (size_t pos = reference_token.find_first_of('~'); | |
12067 pos != std::string::npos; | |
12068 pos = reference_token.find_first_of('~', pos + 1)) | |
12069 { | |
12070 assert(reference_token[pos] == '~'); | |
12071 | |
12072 // ~ must be followed by 0 or 1 | |
12073 if (pos == reference_token.size() - 1 or | |
12074 (reference_token[pos + 1] != '0' and | |
12075 reference_token[pos + 1] != '1')) | |
12076 { | |
12077 JSON_THROW(std::domain_error("escape error: '~' must be followed with '0' or '1'")); | |
12078 } | |
12079 } | |
12080 | |
12081 // finally, store the reference token | |
12082 unescape(reference_token); | |
12083 result.push_back(reference_token); | |
12084 } | |
12085 | |
12086 return result; | |
12087 } | |
12088 | |
12089 private: | |
12090 /*! | |
12091 @brief replace all occurrences of a substring by another string | |
12092 | |
12093 @param[in,out] s the string to manipulate; changed so that all | |
12094 occurrences of @a f are replaced with @a t | |
12095 @param[in] f the substring to replace with @a t | |
12096 @param[in] t the string to replace @a f | |
12097 | |
12098 @pre The search string @a f must not be empty. | |
12099 | |
12100 @since version 2.0.0 | |
12101 */ | |
12102 static void replace_substring(std::string& s, | |
12103 const std::string& f, | |
12104 const std::string& t) | |
12105 { | |
12106 assert(not f.empty()); | |
12107 | |
12108 for ( | |
12109 size_t pos = s.find(f); // find first occurrence of f | |
12110 pos != std::string::npos; // make sure f was found | |
12111 s.replace(pos, f.size(), t), // replace with t | |
12112 pos = s.find(f, pos + t.size()) // find next occurrence of f | |
12113 ); | |
12114 } | |
12115 | |
12116 /// escape tilde and slash | |
12117 static std::string escape(std::string s) | |
12118 { | |
12119 // escape "~"" to "~0" and "/" to "~1" | |
12120 replace_substring(s, "~", "~0"); | |
12121 replace_substring(s, "/", "~1"); | |
12122 return s; | |
12123 } | |
12124 | |
12125 /// unescape tilde and slash | |
12126 static void unescape(std::string& s) | |
12127 { | |
12128 // first transform any occurrence of the sequence '~1' to '/' | |
12129 replace_substring(s, "~1", "/"); | |
12130 // then transform any occurrence of the sequence '~0' to '~' | |
12131 replace_substring(s, "~0", "~"); | |
12132 } | |
12133 | |
12134 /*! | |
12135 @param[in] reference_string the reference string to the current value | |
12136 @param[in] value the value to consider | |
12137 @param[in,out] result the result object to insert values to | |
12138 | |
12139 @note Empty objects or arrays are flattened to `null`. | |
12140 */ | |
12141 static void flatten(const std::string& reference_string, | |
12142 const basic_json& value, | |
12143 basic_json& result) | |
12144 { | |
12145 switch (value.m_type) | |
12146 { | |
12147 case value_t::array: | |
12148 { | |
12149 if (value.m_value.array->empty()) | |
12150 { | |
12151 // flatten empty array as null | |
12152 result[reference_string] = nullptr; | |
12153 } | |
12154 else | |
12155 { | |
12156 // iterate array and use index as reference string | |
12157 for (size_t i = 0; i < value.m_value.array->size(); ++i) | |
12158 { | |
12159 flatten(reference_string + "/" + std::to_string(i), | |
12160 value.m_value.array->operator[](i), result); | |
12161 } | |
12162 } | |
12163 break; | |
12164 } | |
12165 | |
12166 case value_t::object: | |
12167 { | |
12168 if (value.m_value.object->empty()) | |
12169 { | |
12170 // flatten empty object as null | |
12171 result[reference_string] = nullptr; | |
12172 } | |
12173 else | |
12174 { | |
12175 // iterate object and use keys as reference string | |
12176 for (const auto& element : *value.m_value.object) | |
12177 { | |
12178 flatten(reference_string + "/" + escape(element.first), | |
12179 element.second, result); | |
12180 } | |
12181 } | |
12182 break; | |
12183 } | |
12184 | |
12185 default: | |
12186 { | |
12187 // add primitive value with its reference string | |
12188 result[reference_string] = value; | |
12189 break; | |
12190 } | |
12191 } | |
12192 } | |
12193 | |
12194 /*! | |
12195 @param[in] value flattened JSON | |
12196 | |
12197 @return unflattened JSON | |
12198 */ | |
12199 static basic_json unflatten(const basic_json& value) | |
12200 { | |
12201 if (not value.is_object()) | |
12202 { | |
12203 JSON_THROW(std::domain_error("only objects can be unflattened")); | |
12204 } | |
12205 | |
12206 basic_json result; | |
12207 | |
12208 // iterate the JSON object values | |
12209 for (const auto& element : *value.m_value.object) | |
12210 { | |
12211 if (not element.second.is_primitive()) | |
12212 { | |
12213 JSON_THROW(std::domain_error("values in object must be primitive")); | |
12214 } | |
12215 | |
12216 // assign value to reference pointed to by JSON pointer; Note | |
12217 // that if the JSON pointer is "" (i.e., points to the whole | |
12218 // value), function get_and_create returns a reference to | |
12219 // result itself. An assignment will then create a primitive | |
12220 // value. | |
12221 json_pointer(element.first).get_and_create(result) = element.second; | |
12222 } | |
12223 | |
12224 return result; | |
12225 } | |
12226 | |
12227 private: | |
12228 friend bool operator==(json_pointer const& lhs, | |
12229 json_pointer const& rhs) noexcept | |
12230 { | |
12231 return lhs.reference_tokens == rhs.reference_tokens; | |
12232 } | |
12233 | |
12234 friend bool operator!=(json_pointer const& lhs, | |
12235 json_pointer const& rhs) noexcept | |
12236 { | |
12237 return !(lhs == rhs); | |
12238 } | |
12239 | |
12240 /// the reference tokens | |
12241 std::vector<std::string> reference_tokens {}; | |
12242 }; | |
12243 | 16397 |
12244 ////////////////////////// | 16398 ////////////////////////// |
12245 // JSON Pointer support // | 16399 // JSON Pointer support // |
12246 ////////////////////////// | 16400 ////////////////////////// |
12247 | 16401 |
12271 | 16425 |
12272 @return reference to the element pointed to by @a ptr | 16426 @return reference to the element pointed to by @a ptr |
12273 | 16427 |
12274 @complexity Constant. | 16428 @complexity Constant. |
12275 | 16429 |
12276 @throw std::out_of_range if the JSON pointer can not be resolved | 16430 @throw parse_error.106 if an array index begins with '0' |
12277 @throw std::domain_error if an array index begins with '0' | 16431 @throw parse_error.109 if an array index was not a number |
12278 @throw std::invalid_argument if an array index was not a number | 16432 @throw out_of_range.404 if the JSON pointer can not be resolved |
12279 | 16433 |
12280 @liveexample{The behavior is shown in the example.,operatorjson_pointer} | 16434 @liveexample{The behavior is shown in the example.,operatorjson_pointer} |
12281 | 16435 |
12282 @since version 2.0.0 | 16436 @since version 2.0.0 |
12283 */ | 16437 */ |
12298 | 16452 |
12299 @return const reference to the element pointed to by @a ptr | 16453 @return const reference to the element pointed to by @a ptr |
12300 | 16454 |
12301 @complexity Constant. | 16455 @complexity Constant. |
12302 | 16456 |
12303 @throw std::out_of_range if the JSON pointer can not be resolved | 16457 @throw parse_error.106 if an array index begins with '0' |
12304 @throw std::domain_error if an array index begins with '0' | 16458 @throw parse_error.109 if an array index was not a number |
12305 @throw std::invalid_argument if an array index was not a number | 16459 @throw out_of_range.402 if the array index '-' is used |
16460 @throw out_of_range.404 if the JSON pointer can not be resolved | |
12306 | 16461 |
12307 @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} | 16462 @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} |
12308 | 16463 |
12309 @since version 2.0.0 | 16464 @since version 2.0.0 |
12310 */ | 16465 */ |
12321 | 16476 |
12322 @param[in] ptr JSON pointer to the desired element | 16477 @param[in] ptr JSON pointer to the desired element |
12323 | 16478 |
12324 @return reference to the element pointed to by @a ptr | 16479 @return reference to the element pointed to by @a ptr |
12325 | 16480 |
16481 @throw parse_error.106 if an array index in the passed JSON pointer @a ptr | |
16482 begins with '0'. See example below. | |
16483 | |
16484 @throw parse_error.109 if an array index in the passed JSON pointer @a ptr | |
16485 is not a number. See example below. | |
16486 | |
16487 @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr | |
16488 is out of range. See example below. | |
16489 | |
16490 @throw out_of_range.402 if the array index '-' is used in the passed JSON | |
16491 pointer @a ptr. As `at` provides checked access (and no elements are | |
16492 implicitly inserted), the index '-' is always invalid. See example below. | |
16493 | |
16494 @throw out_of_range.403 if the JSON pointer describes a key of an object | |
16495 which cannot be found. See example below. | |
16496 | |
16497 @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. | |
16498 See example below. | |
16499 | |
16500 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
16501 changes in the JSON value. | |
16502 | |
12326 @complexity Constant. | 16503 @complexity Constant. |
12327 | 16504 |
12328 @throw std::out_of_range if the JSON pointer can not be resolved | 16505 @since version 2.0.0 |
12329 @throw std::domain_error if an array index begins with '0' | |
12330 @throw std::invalid_argument if an array index was not a number | |
12331 | 16506 |
12332 @liveexample{The behavior is shown in the example.,at_json_pointer} | 16507 @liveexample{The behavior is shown in the example.,at_json_pointer} |
12333 | |
12334 @since version 2.0.0 | |
12335 */ | 16508 */ |
12336 reference at(const json_pointer& ptr) | 16509 reference at(const json_pointer& ptr) |
12337 { | 16510 { |
12338 return ptr.get_checked(this); | 16511 return ptr.get_checked(this); |
12339 } | 16512 } |
12346 | 16519 |
12347 @param[in] ptr JSON pointer to the desired element | 16520 @param[in] ptr JSON pointer to the desired element |
12348 | 16521 |
12349 @return reference to the element pointed to by @a ptr | 16522 @return reference to the element pointed to by @a ptr |
12350 | 16523 |
16524 @throw parse_error.106 if an array index in the passed JSON pointer @a ptr | |
16525 begins with '0'. See example below. | |
16526 | |
16527 @throw parse_error.109 if an array index in the passed JSON pointer @a ptr | |
16528 is not a number. See example below. | |
16529 | |
16530 @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr | |
16531 is out of range. See example below. | |
16532 | |
16533 @throw out_of_range.402 if the array index '-' is used in the passed JSON | |
16534 pointer @a ptr. As `at` provides checked access (and no elements are | |
16535 implicitly inserted), the index '-' is always invalid. See example below. | |
16536 | |
16537 @throw out_of_range.403 if the JSON pointer describes a key of an object | |
16538 which cannot be found. See example below. | |
16539 | |
16540 @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. | |
16541 See example below. | |
16542 | |
16543 @exceptionsafety Strong guarantee: if an exception is thrown, there are no | |
16544 changes in the JSON value. | |
16545 | |
12351 @complexity Constant. | 16546 @complexity Constant. |
12352 | 16547 |
12353 @throw std::out_of_range if the JSON pointer can not be resolved | 16548 @since version 2.0.0 |
12354 @throw std::domain_error if an array index begins with '0' | |
12355 @throw std::invalid_argument if an array index was not a number | |
12356 | 16549 |
12357 @liveexample{The behavior is shown in the example.,at_json_pointer_const} | 16550 @liveexample{The behavior is shown in the example.,at_json_pointer_const} |
12358 | |
12359 @since version 2.0.0 | |
12360 */ | 16551 */ |
12361 const_reference at(const json_pointer& ptr) const | 16552 const_reference at(const json_pointer& ptr) const |
12362 { | 16553 { |
12363 return ptr.get_checked(this); | 16554 return ptr.get_checked(this); |
12364 } | 16555 } |
12410 this example, for a JSON value `j`, the following is always true: | 16601 this example, for a JSON value `j`, the following is always true: |
12411 `j == j.flatten().unflatten()`. | 16602 `j == j.flatten().unflatten()`. |
12412 | 16603 |
12413 @complexity Linear in the size the JSON value. | 16604 @complexity Linear in the size the JSON value. |
12414 | 16605 |
16606 @throw type_error.314 if value is not an object | |
16607 @throw type_error.315 if object values are not primitive | |
16608 | |
12415 @liveexample{The following code shows how a flattened JSON object is | 16609 @liveexample{The following code shows how a flattened JSON object is |
12416 unflattened into the original nested JSON object.,unflatten} | 16610 unflattened into the original nested JSON object.,unflatten} |
12417 | 16611 |
12418 @sa @ref flatten() for the reverse function | 16612 @sa @ref flatten() for the reverse function |
12419 | 16613 |
12447 @note The application of a patch is atomic: Either all operations succeed | 16641 @note The application of a patch is atomic: Either all operations succeed |
12448 and the patched document is returned or an exception is thrown. In | 16642 and the patched document is returned or an exception is thrown. In |
12449 any case, the original value is not changed: the patch is applied | 16643 any case, the original value is not changed: the patch is applied |
12450 to a copy of the value. | 16644 to a copy of the value. |
12451 | 16645 |
12452 @throw std::out_of_range if a JSON pointer inside the patch could not | 16646 @throw parse_error.104 if the JSON patch does not consist of an array of |
12453 be resolved successfully in the current JSON value; example: `"key baz | 16647 objects |
12454 not found"` | 16648 |
12455 @throw invalid_argument if the JSON patch is malformed (e.g., mandatory | 16649 @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory |
12456 attributes are missing); example: `"operation add must have member path"` | 16650 attributes are missing); example: `"operation add must have member path"` |
16651 | |
16652 @throw out_of_range.401 if an array index is out of range. | |
16653 | |
16654 @throw out_of_range.403 if a JSON pointer inside the patch could not be | |
16655 resolved successfully in the current JSON value; example: `"key baz not | |
16656 found"` | |
16657 | |
16658 @throw out_of_range.405 if JSON pointer has no parent ("add", "remove", | |
16659 "move") | |
16660 | |
16661 @throw other_error.501 if "test" operation was unsuccessful | |
12457 | 16662 |
12458 @complexity Linear in the size of the JSON value and the length of the | 16663 @complexity Linear in the size of the JSON value and the length of the |
12459 JSON patch. As usually only a fraction of the JSON value is affected by | 16664 JSON patch. As usually only a fraction of the JSON value is affected by |
12460 the patch, the complexity can usually be neglected. | 16665 the patch, the complexity can usually be neglected. |
12461 | 16666 |
12475 basic_json result = *this; | 16680 basic_json result = *this; |
12476 | 16681 |
12477 // the valid JSON Patch operations | 16682 // the valid JSON Patch operations |
12478 enum class patch_operations {add, remove, replace, move, copy, test, invalid}; | 16683 enum class patch_operations {add, remove, replace, move, copy, test, invalid}; |
12479 | 16684 |
12480 const auto get_op = [](const std::string op) | 16685 const auto get_op = [](const std::string & op) |
12481 { | 16686 { |
12482 if (op == "add") | 16687 if (op == "add") |
12483 { | 16688 { |
12484 return patch_operations::add; | 16689 return patch_operations::add; |
12485 } | 16690 } |
12545 // special case: append to back | 16750 // special case: append to back |
12546 parent.push_back(val); | 16751 parent.push_back(val); |
12547 } | 16752 } |
12548 else | 16753 else |
12549 { | 16754 { |
12550 const auto idx = std::stoi(last_path); | 16755 const auto idx = json_pointer::array_index(last_path); |
12551 if (static_cast<size_type>(idx) > parent.size()) | 16756 if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size())) |
12552 { | 16757 { |
12553 // avoid undefined behavior | 16758 // avoid undefined behavior |
12554 JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range")); | 16759 JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); |
12555 } | 16760 } |
12556 else | 16761 else |
12557 { | 16762 { |
12558 // default case: insert add offset | 16763 // default case: insert add offset |
12559 parent.insert(parent.begin() + static_cast<difference_type>(idx), val); | 16764 parent.insert(parent.begin() + static_cast<difference_type>(idx), val); |
12581 // remove child | 16786 // remove child |
12582 if (parent.is_object()) | 16787 if (parent.is_object()) |
12583 { | 16788 { |
12584 // perform range check | 16789 // perform range check |
12585 auto it = parent.find(last_path); | 16790 auto it = parent.find(last_path); |
12586 if (it != parent.end()) | 16791 if (JSON_LIKELY(it != parent.end())) |
12587 { | 16792 { |
12588 parent.erase(it); | 16793 parent.erase(it); |
12589 } | 16794 } |
12590 else | 16795 else |
12591 { | 16796 { |
12592 JSON_THROW(std::out_of_range("key '" + last_path + "' not found")); | 16797 JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found")); |
12593 } | 16798 } |
12594 } | 16799 } |
12595 else if (parent.is_array()) | 16800 else if (parent.is_array()) |
12596 { | 16801 { |
12597 // note erase performs range check | 16802 // note erase performs range check |
12598 parent.erase(static_cast<size_type>(std::stoi(last_path))); | 16803 parent.erase(static_cast<size_type>(json_pointer::array_index(last_path))); |
12599 } | 16804 } |
12600 }; | 16805 }; |
12601 | 16806 |
12602 // type check | 16807 // type check: top level value must be an array |
12603 if (not json_patch.is_array()) | 16808 if (JSON_UNLIKELY(not json_patch.is_array())) |
12604 { | 16809 { |
12605 // a JSON patch must be an array of objects | 16810 JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); |
12606 JSON_THROW(std::invalid_argument("JSON patch must be an array of objects")); | |
12607 } | 16811 } |
12608 | 16812 |
12609 // iterate and apply the operations | 16813 // iterate and apply the operations |
12610 for (const auto& val : json_patch) | 16814 for (const auto& val : json_patch) |
12611 { | 16815 { |
12612 // wrapper to get a value for an operation | 16816 // wrapper to get a value for an operation |
12613 const auto get_value = [&val](const std::string & op, | 16817 const auto get_value = [&val](const std::string & op, |
12614 const std::string & member, | 16818 const std::string & member, |
12615 bool string_type) -> basic_json& | 16819 bool string_type) -> basic_json & |
12616 { | 16820 { |
12617 // find value | 16821 // find value |
12618 auto it = val.m_value.object->find(member); | 16822 auto it = val.m_value.object->find(member); |
12619 | 16823 |
12620 // context-sensitive error message | 16824 // context-sensitive error message |
12621 const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; | 16825 const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; |
12622 | 16826 |
12623 // check if desired value is present | 16827 // check if desired value is present |
12624 if (it == val.m_value.object->end()) | 16828 if (JSON_UNLIKELY(it == val.m_value.object->end())) |
12625 { | 16829 { |
12626 JSON_THROW(std::invalid_argument(error_msg + " must have member '" + member + "'")); | 16830 JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'")); |
12627 } | 16831 } |
12628 | 16832 |
12629 // check if result is of type string | 16833 // check if result is of type string |
12630 if (string_type and not it->second.is_string()) | 16834 if (JSON_UNLIKELY(string_type and not it->second.is_string())) |
12631 { | 16835 { |
12632 JSON_THROW(std::invalid_argument(error_msg + " must have string member '" + member + "'")); | 16836 JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'")); |
12633 } | 16837 } |
12634 | 16838 |
12635 // no error: return value | 16839 // no error: return value |
12636 return it->second; | 16840 return it->second; |
12637 }; | 16841 }; |
12638 | 16842 |
12639 // type check | 16843 // type check: every element of the array must be an object |
12640 if (not val.is_object()) | 16844 if (JSON_UNLIKELY(not val.is_object())) |
12641 { | 16845 { |
12642 JSON_THROW(std::invalid_argument("JSON patch must be an array of objects")); | 16846 JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); |
12643 } | 16847 } |
12644 | 16848 |
12645 // collect mandatory members | 16849 // collect mandatory members |
12646 const std::string op = get_value("op", "op", true); | 16850 const std::string op = get_value("op", "op", true); |
12647 const std::string path = get_value(op, "path", true); | 16851 const std::string path = get_value(op, "path", true); |
12685 break; | 16889 break; |
12686 } | 16890 } |
12687 | 16891 |
12688 case patch_operations::copy: | 16892 case patch_operations::copy: |
12689 { | 16893 { |
12690 const std::string from_path = get_value("copy", "from", true);; | 16894 const std::string from_path = get_value("copy", "from", true); |
12691 const json_pointer from_ptr(from_path); | 16895 const json_pointer from_ptr(from_path); |
12692 | 16896 |
12693 // the "from" location must exist - use at() | 16897 // the "from" location must exist - use at() |
12694 result[ptr] = result.at(from_ptr); | 16898 basic_json v = result.at(from_ptr); |
16899 | |
16900 // The copy is functionally identical to an "add" | |
16901 // operation at the target location using the value | |
16902 // specified in the "from" member. | |
16903 operation_add(ptr, v); | |
12695 break; | 16904 break; |
12696 } | 16905 } |
12697 | 16906 |
12698 case patch_operations::test: | 16907 case patch_operations::test: |
12699 { | 16908 { |
12702 { | 16911 { |
12703 // check if "value" matches the one at "path" | 16912 // check if "value" matches the one at "path" |
12704 // the "path" location must exist - use at() | 16913 // the "path" location must exist - use at() |
12705 success = (result.at(ptr) == get_value("test", "value", false)); | 16914 success = (result.at(ptr) == get_value("test", "value", false)); |
12706 } | 16915 } |
12707 JSON_CATCH (std::out_of_range&) | 16916 JSON_CATCH (out_of_range&) |
12708 { | 16917 { |
12709 // ignore out of range errors: success remains false | 16918 // ignore out of range errors: success remains false |
12710 } | 16919 } |
12711 | 16920 |
12712 // throw an exception if test fails | 16921 // throw an exception if test fails |
12713 if (not success) | 16922 if (JSON_UNLIKELY(not success)) |
12714 { | 16923 { |
12715 JSON_THROW(std::domain_error("unsuccessful: " + val.dump())); | 16924 JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump())); |
12716 } | 16925 } |
12717 | 16926 |
12718 break; | 16927 break; |
12719 } | 16928 } |
12720 | 16929 |
12721 case patch_operations::invalid: | 16930 case patch_operations::invalid: |
12722 { | 16931 { |
12723 // op must be "add", "remove", "replace", "move", "copy", or | 16932 // op must be "add", "remove", "replace", "move", "copy", or |
12724 // "test" | 16933 // "test" |
12725 JSON_THROW(std::invalid_argument("operation value '" + op + "' is invalid")); | 16934 JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid")); |
12726 } | 16935 } |
12727 } | 16936 } |
12728 } | 16937 } |
12729 | 16938 |
12730 return result; | 16939 return result; |
12755 | 16964 |
12756 @liveexample{The following code shows how a JSON patch is created as a | 16965 @liveexample{The following code shows how a JSON patch is created as a |
12757 diff for two JSON values.,diff} | 16966 diff for two JSON values.,diff} |
12758 | 16967 |
12759 @sa @ref patch -- apply a JSON patch | 16968 @sa @ref patch -- apply a JSON patch |
16969 @sa @ref merge_patch -- apply a JSON Merge Patch | |
12760 | 16970 |
12761 @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) | 16971 @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) |
12762 | 16972 |
12763 @since version 2.0.0 | 16973 @since version 2.0.0 |
12764 */ | 16974 */ |
12765 static basic_json diff(const basic_json& source, | 16975 static basic_json diff(const basic_json& source, const basic_json& target, |
12766 const basic_json& target, | |
12767 const std::string& path = "") | 16976 const std::string& path = "") |
12768 { | 16977 { |
12769 // the patch | 16978 // the patch |
12770 basic_json result(value_t::array); | 16979 basic_json result(value_t::array); |
12771 | 16980 |
12778 if (source.type() != target.type()) | 16987 if (source.type() != target.type()) |
12779 { | 16988 { |
12780 // different types: replace value | 16989 // different types: replace value |
12781 result.push_back( | 16990 result.push_back( |
12782 { | 16991 { |
12783 {"op", "replace"}, | 16992 {"op", "replace"}, {"path", path}, {"value", target} |
12784 {"path", path}, | |
12785 {"value", target} | |
12786 }); | 16993 }); |
12787 } | 16994 } |
12788 else | 16995 else |
12789 { | 16996 { |
12790 switch (source.type()) | 16997 switch (source.type()) |
12791 { | 16998 { |
12792 case value_t::array: | 16999 case value_t::array: |
12793 { | 17000 { |
12794 // first pass: traverse common elements | 17001 // first pass: traverse common elements |
12795 size_t i = 0; | 17002 std::size_t i = 0; |
12796 while (i < source.size() and i < target.size()) | 17003 while (i < source.size() and i < target.size()) |
12797 { | 17004 { |
12798 // recursive call to compare array values at index i | 17005 // recursive call to compare array values at index i |
12799 auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); | 17006 auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); |
12800 result.insert(result.end(), temp_diff.begin(), temp_diff.end()); | 17007 result.insert(result.end(), temp_diff.begin(), temp_diff.end()); |
12834 } | 17041 } |
12835 | 17042 |
12836 case value_t::object: | 17043 case value_t::object: |
12837 { | 17044 { |
12838 // first pass: traverse this object's elements | 17045 // first pass: traverse this object's elements |
12839 for (auto it = source.begin(); it != source.end(); ++it) | 17046 for (auto it = source.cbegin(); it != source.cend(); ++it) |
12840 { | 17047 { |
12841 // escape the key name to be used in a JSON patch | 17048 // escape the key name to be used in a JSON patch |
12842 const auto key = json_pointer::escape(it.key()); | 17049 const auto key = json_pointer::escape(it.key()); |
12843 | 17050 |
12844 if (target.find(it.key()) != target.end()) | 17051 if (target.find(it.key()) != target.end()) |
12850 else | 17057 else |
12851 { | 17058 { |
12852 // found a key that is not in o -> remove it | 17059 // found a key that is not in o -> remove it |
12853 result.push_back(object( | 17060 result.push_back(object( |
12854 { | 17061 { |
12855 {"op", "remove"}, | 17062 {"op", "remove"}, {"path", path + "/" + key} |
12856 {"path", path + "/" + key} | |
12857 })); | 17063 })); |
12858 } | 17064 } |
12859 } | 17065 } |
12860 | 17066 |
12861 // second pass: traverse other object's elements | 17067 // second pass: traverse other object's elements |
12862 for (auto it = target.begin(); it != target.end(); ++it) | 17068 for (auto it = target.cbegin(); it != target.cend(); ++it) |
12863 { | 17069 { |
12864 if (source.find(it.key()) == source.end()) | 17070 if (source.find(it.key()) == source.end()) |
12865 { | 17071 { |
12866 // found a key that is not in this -> add it | 17072 // found a key that is not in this -> add it |
12867 const auto key = json_pointer::escape(it.key()); | 17073 const auto key = json_pointer::escape(it.key()); |
12868 result.push_back( | 17074 result.push_back( |
12869 { | 17075 { |
12870 {"op", "add"}, | 17076 {"op", "add"}, {"path", path + "/" + key}, |
12871 {"path", path + "/" + key}, | |
12872 {"value", it.value()} | 17077 {"value", it.value()} |
12873 }); | 17078 }); |
12874 } | 17079 } |
12875 } | 17080 } |
12876 | 17081 |
12880 default: | 17085 default: |
12881 { | 17086 { |
12882 // both primitive type: replace value | 17087 // both primitive type: replace value |
12883 result.push_back( | 17088 result.push_back( |
12884 { | 17089 { |
12885 {"op", "replace"}, | 17090 {"op", "replace"}, {"path", path}, {"value", target} |
12886 {"path", path}, | |
12887 {"value", target} | |
12888 }); | 17091 }); |
12889 break; | 17092 break; |
12890 } | 17093 } |
12891 } | 17094 } |
12892 } | 17095 } |
12893 | 17096 |
12894 return result; | 17097 return result; |
12895 } | 17098 } |
12896 | 17099 |
12897 /// @} | 17100 /// @} |
17101 | |
17102 //////////////////////////////// | |
17103 // JSON Merge Patch functions // | |
17104 //////////////////////////////// | |
17105 | |
17106 /// @name JSON Merge Patch functions | |
17107 /// @{ | |
17108 | |
17109 /*! | |
17110 @brief applies a JSON Merge Patch | |
17111 | |
17112 The merge patch format is primarily intended for use with the HTTP PATCH | |
17113 method as a means of describing a set of modifications to a target | |
17114 resource's content. This function applies a merge patch to the current | |
17115 JSON value. | |
17116 | |
17117 The function implements the following algorithm from Section 2 of | |
17118 [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396): | |
17119 | |
17120 ``` | |
17121 define MergePatch(Target, Patch): | |
17122 if Patch is an Object: | |
17123 if Target is not an Object: | |
17124 Target = {} // Ignore the contents and set it to an empty Object | |
17125 for each Name/Value pair in Patch: | |
17126 if Value is null: | |
17127 if Name exists in Target: | |
17128 remove the Name/Value pair from Target | |
17129 else: | |
17130 Target[Name] = MergePatch(Target[Name], Value) | |
17131 return Target | |
17132 else: | |
17133 return Patch | |
17134 ``` | |
17135 | |
17136 Thereby, `Target` is the current object; that is, the patch is applied to | |
17137 the current value. | |
17138 | |
17139 @param[in] patch the patch to apply | |
17140 | |
17141 @complexity Linear in the lengths of @a patch. | |
17142 | |
17143 @liveexample{The following code shows how a JSON Merge Patch is applied to | |
17144 a JSON document.,merge_patch} | |
17145 | |
17146 @sa @ref patch -- apply a JSON patch | |
17147 @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396) | |
17148 | |
17149 @since version 3.0.0 | |
17150 */ | |
17151 void merge_patch(const basic_json& patch) | |
17152 { | |
17153 if (patch.is_object()) | |
17154 { | |
17155 if (not is_object()) | |
17156 { | |
17157 *this = object(); | |
17158 } | |
17159 for (auto it = patch.begin(); it != patch.end(); ++it) | |
17160 { | |
17161 if (it.value().is_null()) | |
17162 { | |
17163 erase(it.key()); | |
17164 } | |
17165 else | |
17166 { | |
17167 operator[](it.key()).merge_patch(it.value()); | |
17168 } | |
17169 } | |
17170 } | |
17171 else | |
17172 { | |
17173 *this = patch; | |
17174 } | |
17175 } | |
17176 | |
17177 /// @} | |
12898 }; | 17178 }; |
12899 | |
12900 ///////////// | |
12901 // presets // | |
12902 ///////////// | |
12903 | |
12904 /*! | |
12905 @brief default JSON class | |
12906 | |
12907 This type is the default specialization of the @ref basic_json class which | |
12908 uses the standard template types. | |
12909 | |
12910 @since version 1.0.0 | |
12911 */ | |
12912 using json = basic_json<>; | |
12913 } // namespace nlohmann | 17179 } // namespace nlohmann |
12914 | |
12915 | 17180 |
12916 /////////////////////// | 17181 /////////////////////// |
12917 // nonmember support // | 17182 // nonmember support // |
12918 /////////////////////// | 17183 /////////////////////// |
12919 | 17184 |
12949 // a naive hashing via the string representation | 17214 // a naive hashing via the string representation |
12950 const auto& h = hash<nlohmann::json::string_t>(); | 17215 const auto& h = hash<nlohmann::json::string_t>(); |
12951 return h(j.dump()); | 17216 return h(j.dump()); |
12952 } | 17217 } |
12953 }; | 17218 }; |
17219 | |
17220 /// specialization for std::less<value_t> | |
17221 /// @note: do not remove the space after '<', | |
17222 /// see https://github.com/nlohmann/json/pull/679 | |
17223 template<> | |
17224 struct less< ::nlohmann::detail::value_t> | |
17225 { | |
17226 /*! | |
17227 @brief compare two value_t enum values | |
17228 @since version 3.0.0 | |
17229 */ | |
17230 bool operator()(nlohmann::detail::value_t lhs, | |
17231 nlohmann::detail::value_t rhs) const noexcept | |
17232 { | |
17233 return nlohmann::detail::operator<(lhs, rhs); | |
17234 } | |
17235 }; | |
17236 | |
12954 } // namespace std | 17237 } // namespace std |
12955 | 17238 |
12956 /*! | 17239 /*! |
12957 @brief user-defined string literal for JSON values | 17240 @brief user-defined string literal for JSON values |
12958 | 17241 |
12987 inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) | 17270 inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) |
12988 { | 17271 { |
12989 return nlohmann::json::json_pointer(std::string(s, n)); | 17272 return nlohmann::json::json_pointer(std::string(s, n)); |
12990 } | 17273 } |
12991 | 17274 |
17275 // #include <nlohmann/detail/macro_unscope.hpp> | |
17276 | |
17277 | |
12992 // restore GCC/clang diagnostic settings | 17278 // restore GCC/clang diagnostic settings |
12993 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) | 17279 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) |
12994 #pragma GCC diagnostic pop | 17280 #pragma GCC diagnostic pop |
12995 #endif | 17281 #endif |
17282 #if defined(__clang__) | |
17283 #pragma GCC diagnostic pop | |
17284 #endif | |
12996 | 17285 |
12997 // clean up | 17286 // clean up |
12998 #undef JSON_CATCH | 17287 #undef JSON_CATCH |
12999 #undef JSON_DEPRECATED | |
13000 #undef JSON_THROW | 17288 #undef JSON_THROW |
13001 #undef JSON_TRY | 17289 #undef JSON_TRY |
17290 #undef JSON_LIKELY | |
17291 #undef JSON_UNLIKELY | |
17292 #undef JSON_DEPRECATED | |
17293 #undef JSON_HAS_CPP_14 | |
17294 #undef JSON_HAS_CPP_17 | |
17295 #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
17296 #undef NLOHMANN_BASIC_JSON_TPL | |
17297 #undef NLOHMANN_JSON_HAS_HELPER | |
17298 | |
13002 | 17299 |
13003 #endif | 17300 #endif |