1 #pragma once
2 
3 #include <algorithm> // transform
4 #include <array> // array
5 #include <forward_list> // forward_list
6 #include <iterator> // inserter, front_inserter, end
7 #include <map> // map
8 #include <string> // string
9 #include <tuple> // tuple, make_tuple
10 #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
11 #include <unordered_map> // unordered_map
12 #include <utility> // pair, declval
13 #include <valarray> // valarray
14 
15 #include <nlohmann/detail/exceptions.hpp>
16 #include <nlohmann/detail/macro_scope.hpp>
17 #include <nlohmann/detail/meta/cpp_future.hpp>
18 #include <nlohmann/detail/meta/identity_tag.hpp>
19 #include <nlohmann/detail/meta/type_traits.hpp>
20 #include <nlohmann/detail/value_t.hpp>
21 
22 namespace nlohmann
23 {
24 namespace detail
25 {
26 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename std::nullptr_t & n)27 void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
28 {
29     if (JSON_HEDLEY_UNLIKELY(!j.is_null()))
30     {
31         JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j));
32     }
33     n = nullptr;
34 }
35 
36 // overloads for basic_json template parameters
37 template < typename BasicJsonType, typename ArithmeticType,
38            enable_if_t < std::is_arithmetic<ArithmeticType>::value&&
39                          !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
40                          int > = 0 >
get_arithmetic_value(const BasicJsonType & j,ArithmeticType & val)41 void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
42 {
43     switch (static_cast<value_t>(j))
44     {
45         case value_t::number_unsigned:
46         {
47             val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
48             break;
49         }
50         case value_t::number_integer:
51         {
52             val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
53             break;
54         }
55         case value_t::number_float:
56         {
57             val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
58             break;
59         }
60 
61         default:
62             JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j));
63     }
64 }
65 
66 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename BasicJsonType::boolean_t & b)67 void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
68 {
69     if (JSON_HEDLEY_UNLIKELY(!j.is_boolean()))
70     {
71         JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j));
72     }
73     b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
74 }
75 
76 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename BasicJsonType::string_t & s)77 void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
78 {
79     if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
80     {
81         JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
82     }
83     s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
84 }
85 
86 template <
87     typename BasicJsonType, typename ConstructibleStringType,
88     enable_if_t <
89         is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value&&
90         !std::is_same<typename BasicJsonType::string_t,
91                       ConstructibleStringType>::value,
92         int > = 0 >
from_json(const BasicJsonType & j,ConstructibleStringType & s)93 void from_json(const BasicJsonType& j, ConstructibleStringType& s)
94 {
95     if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
96     {
97         JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
98     }
99 
100     s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
101 }
102 
103 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename BasicJsonType::number_float_t & val)104 void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
105 {
106     get_arithmetic_value(j, val);
107 }
108 
109 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename BasicJsonType::number_unsigned_t & val)110 void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
111 {
112     get_arithmetic_value(j, val);
113 }
114 
115 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename BasicJsonType::number_integer_t & val)116 void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
117 {
118     get_arithmetic_value(j, val);
119 }
120 
121 template<typename BasicJsonType, typename EnumType,
122          enable_if_t<std::is_enum<EnumType>::value, int> = 0>
from_json(const BasicJsonType & j,EnumType & e)123 void from_json(const BasicJsonType& j, EnumType& e)
124 {
125     typename std::underlying_type<EnumType>::type val;
126     get_arithmetic_value(j, val);
127     e = static_cast<EnumType>(val);
128 }
129 
130 // forward_list doesn't have an insert method
131 template<typename BasicJsonType, typename T, typename Allocator,
132          enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
from_json(const BasicJsonType & j,std::forward_list<T,Allocator> & l)133 void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
134 {
135     if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
136     {
137         JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
138     }
139     l.clear();
140     std::transform(j.rbegin(), j.rend(),
141                    std::front_inserter(l), [](const BasicJsonType & i)
142     {
143         return i.template get<T>();
144     });
145 }
146 
147 // valarray doesn't have an insert method
148 template<typename BasicJsonType, typename T,
149          enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
from_json(const BasicJsonType & j,std::valarray<T> & l)150 void from_json(const BasicJsonType& j, std::valarray<T>& l)
151 {
152     if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
153     {
154         JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
155     }
156     l.resize(j.size());
157     std::transform(j.begin(), j.end(), std::begin(l),
158                    [](const BasicJsonType & elem)
159     {
160         return elem.template get<T>();
161     });
162 }
163 
164 template<typename BasicJsonType, typename T, std::size_t N>
from_json(const BasicJsonType & j,T (& arr)[N])165 auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
166 -> decltype(j.template get<T>(), void())
167 {
168     for (std::size_t i = 0; i < N; ++i)
169     {
170         arr[i] = j.at(i).template get<T>();
171     }
172 }
173 
174 template<typename BasicJsonType>
from_json_array_impl(const BasicJsonType & j,typename BasicJsonType::array_t & arr,priority_tag<3>)175 void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
176 {
177     arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
178 }
179 
180 template<typename BasicJsonType, typename T, std::size_t N>
from_json_array_impl(const BasicJsonType & j,std::array<T,N> & arr,priority_tag<2>)181 auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
182                           priority_tag<2> /*unused*/)
183 -> decltype(j.template get<T>(), void())
184 {
185     for (std::size_t i = 0; i < N; ++i)
186     {
187         arr[i] = j.at(i).template get<T>();
188     }
189 }
190 
191 template<typename BasicJsonType, typename ConstructibleArrayType,
192          enable_if_t<
193              std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
194              int> = 0>
from_json_array_impl(const BasicJsonType & j,ConstructibleArrayType & arr,priority_tag<1>)195 auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
196 -> decltype(
197     arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
198     j.template get<typename ConstructibleArrayType::value_type>(),
199     void())
200 {
201     using std::end;
202 
203     ConstructibleArrayType ret;
204     ret.reserve(j.size());
205     std::transform(j.begin(), j.end(),
206                    std::inserter(ret, end(ret)), [](const BasicJsonType & i)
207     {
208         // get<BasicJsonType>() returns *this, this won't call a from_json
209         // method when value_type is BasicJsonType
210         return i.template get<typename ConstructibleArrayType::value_type>();
211     });
212     arr = std::move(ret);
213 }
214 
215 template<typename BasicJsonType, typename ConstructibleArrayType,
216          enable_if_t<
217              std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
218              int> = 0>
from_json_array_impl(const BasicJsonType & j,ConstructibleArrayType & arr,priority_tag<0>)219 void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
220                           priority_tag<0> /*unused*/)
221 {
222     using std::end;
223 
224     ConstructibleArrayType ret;
225     std::transform(
226         j.begin(), j.end(), std::inserter(ret, end(ret)),
227         [](const BasicJsonType & i)
228     {
229         // get<BasicJsonType>() returns *this, this won't call a from_json
230         // method when value_type is BasicJsonType
231         return i.template get<typename ConstructibleArrayType::value_type>();
232     });
233     arr = std::move(ret);
234 }
235 
236 template < typename BasicJsonType, typename ConstructibleArrayType,
237            enable_if_t <
238                is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value&&
239                !is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value&&
240                !is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value&&
241                !std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value&&
242                !is_basic_json<ConstructibleArrayType>::value,
243                int > = 0 >
from_json(const BasicJsonType & j,ConstructibleArrayType & arr)244 auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
245 -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
246 j.template get<typename ConstructibleArrayType::value_type>(),
247 void())
248 {
249     if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
250     {
251         JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
252     }
253 
254     from_json_array_impl(j, arr, priority_tag<3> {});
255 }
256 
257 template < typename BasicJsonType, typename T, std::size_t... Idx >
from_json_inplace_array_impl(BasicJsonType && j,identity_tag<std::array<T,sizeof...(Idx)>>,index_sequence<Idx...>)258 std::array<T, sizeof...(Idx)> from_json_inplace_array_impl(BasicJsonType&& j,
259         identity_tag<std::array<T, sizeof...(Idx)>> /*unused*/, index_sequence<Idx...> /*unused*/)
260 {
261     return { { std::forward<BasicJsonType>(j).at(Idx).template get<T>()... } };
262 }
263 
264 template < typename BasicJsonType, typename T, std::size_t N >
from_json(BasicJsonType && j,identity_tag<std::array<T,N>> tag)265 auto from_json(BasicJsonType&& j, identity_tag<std::array<T, N>> tag)
266 -> decltype(from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {}))
267 {
268     if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
269     {
270         JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
271     }
272 
273     return from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {});
274 }
275 
276 template<typename BasicJsonType>
from_json(const BasicJsonType & j,typename BasicJsonType::binary_t & bin)277 void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin)
278 {
279     if (JSON_HEDLEY_UNLIKELY(!j.is_binary()))
280     {
281         JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j));
282     }
283 
284     bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>();
285 }
286 
287 template<typename BasicJsonType, typename ConstructibleObjectType,
288          enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
from_json(const BasicJsonType & j,ConstructibleObjectType & obj)289 void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
290 {
291     if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
292     {
293         JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j));
294     }
295 
296     ConstructibleObjectType ret;
297     const auto* inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
298     using value_type = typename ConstructibleObjectType::value_type;
299     std::transform(
300         inner_object->begin(), inner_object->end(),
301         std::inserter(ret, ret.begin()),
302         [](typename BasicJsonType::object_t::value_type const & p)
303     {
304         return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
305     });
306     obj = std::move(ret);
307 }
308 
309 // overload for arithmetic types, not chosen for basic_json template arguments
310 // (BooleanType, etc..); note: Is it really necessary to provide explicit
311 // overloads for boolean_t etc. in case of a custom BooleanType which is not
312 // an arithmetic type?
313 template < typename BasicJsonType, typename ArithmeticType,
314            enable_if_t <
315                std::is_arithmetic<ArithmeticType>::value&&
316                !std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value&&
317                !std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value&&
318                !std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value&&
319                !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
320                int > = 0 >
from_json(const BasicJsonType & j,ArithmeticType & val)321 void from_json(const BasicJsonType& j, ArithmeticType& val)
322 {
323     switch (static_cast<value_t>(j))
324     {
325         case value_t::number_unsigned:
326         {
327             val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
328             break;
329         }
330         case value_t::number_integer:
331         {
332             val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
333             break;
334         }
335         case value_t::number_float:
336         {
337             val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
338             break;
339         }
340         case value_t::boolean:
341         {
342             val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
343             break;
344         }
345 
346         default:
347             JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j));
348     }
349 }
350 
351 template<typename BasicJsonType, typename... Args, std::size_t... Idx>
from_json_tuple_impl_base(BasicJsonType && j,index_sequence<Idx...>)352 std::tuple<Args...> from_json_tuple_impl_base(BasicJsonType&& j, index_sequence<Idx...> /*unused*/)
353 {
354     return std::make_tuple(std::forward<BasicJsonType>(j).at(Idx).template get<Args>()...);
355 }
356 
357 template < typename BasicJsonType, class A1, class A2 >
from_json_tuple_impl(BasicJsonType && j,identity_tag<std::pair<A1,A2>>,priority_tag<0>)358 std::pair<A1, A2> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::pair<A1, A2>> /*unused*/, priority_tag<0> /*unused*/)
359 {
360     return {std::forward<BasicJsonType>(j).at(0).template get<A1>(),
361             std::forward<BasicJsonType>(j).at(1).template get<A2>()};
362 }
363 
364 template<typename BasicJsonType, typename A1, typename A2>
from_json_tuple_impl(BasicJsonType && j,std::pair<A1,A2> & p,priority_tag<1>)365 void from_json_tuple_impl(BasicJsonType&& j, std::pair<A1, A2>& p, priority_tag<1> /*unused*/)
366 {
367     p = from_json_tuple_impl(std::forward<BasicJsonType>(j), identity_tag<std::pair<A1, A2>> {}, priority_tag<0> {});
368 }
369 
370 template<typename BasicJsonType, typename... Args>
from_json_tuple_impl(BasicJsonType && j,identity_tag<std::tuple<Args...>>,priority_tag<2>)371 std::tuple<Args...> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::tuple<Args...>> /*unused*/, priority_tag<2> /*unused*/)
372 {
373     return from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {});
374 }
375 
376 template<typename BasicJsonType, typename... Args>
from_json_tuple_impl(BasicJsonType && j,std::tuple<Args...> & t,priority_tag<3>)377 void from_json_tuple_impl(BasicJsonType&& j, std::tuple<Args...>& t, priority_tag<3> /*unused*/)
378 {
379     t = from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {});
380 }
381 
382 template<typename BasicJsonType, typename TupleRelated>
from_json(BasicJsonType && j,TupleRelated && t)383 auto from_json(BasicJsonType&& j, TupleRelated&& t)
384 -> decltype(from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {}))
385 {
386     if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
387     {
388         JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
389     }
390 
391     return from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {});
392 }
393 
394 template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
395            typename = enable_if_t < !std::is_constructible <
396                                         typename BasicJsonType::string_t, Key >::value >>
from_json(const BasicJsonType & j,std::map<Key,Value,Compare,Allocator> & m)397 void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
398 {
399     if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
400     {
401         JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
402     }
403     m.clear();
404     for (const auto& p : j)
405     {
406         if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
407         {
408             JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j));
409         }
410         m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
411     }
412 }
413 
414 template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
415            typename = enable_if_t < !std::is_constructible <
416                                         typename BasicJsonType::string_t, Key >::value >>
from_json(const BasicJsonType & j,std::unordered_map<Key,Value,Hash,KeyEqual,Allocator> & m)417 void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
418 {
419     if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
420     {
421         JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
422     }
423     m.clear();
424     for (const auto& p : j)
425     {
426         if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
427         {
428             JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j));
429         }
430         m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
431     }
432 }
433 
434 struct from_json_fn
435 {
436     template<typename BasicJsonType, typename T>
operator ()nlohmann::detail::from_json_fn437     auto operator()(const BasicJsonType& j, T&& val) const
438     noexcept(noexcept(from_json(j, std::forward<T>(val))))
439     -> decltype(from_json(j, std::forward<T>(val)))
440     {
441         return from_json(j, std::forward<T>(val));
442     }
443 };
444 }  // namespace detail
445 
446 /// namespace to hold default `from_json` function
447 /// to see why this is required:
448 /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
449 namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
450 {
451 constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; // NOLINT(misc-definitions-in-headers)
452 } // namespace
453 } // namespace nlohmann
454