2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 // @author Nicholas Ormrod <njormrod@fb.com>
22 #include <type_traits>
24 #include <boost/iterator/iterator_adaptor.hpp>
25 #include <boost/mpl/has_xxx.hpp>
27 #include <folly/Likely.h>
28 #include <folly/Optional.h>
29 #include <folly/Traits.h>
30 #include <folly/dynamic.h>
33 template <typename T> T convertTo(const dynamic&);
34 template <typename T> dynamic toDynamic(const T&);
38 * convertTo returns a well-typed representation of the input dynamic.
42 * dynamic d = dynamic::array(
43 * dynamic::array(1, 2, 3),
44 * dynamic::array(4, 5)); // a vector of vector of int
45 * auto vvi = convertTo<fbvector<fbvector<int>>>(d);
47 * See docs/DynamicConverter.md for supported types and customization
52 ///////////////////////////////////////////////////////////////////////////////
55 namespace dynamicconverter_detail {
57 BOOST_MPL_HAS_XXX_TRAIT_DEF(value_type);
58 BOOST_MPL_HAS_XXX_TRAIT_DEF(iterator);
59 BOOST_MPL_HAS_XXX_TRAIT_DEF(mapped_type);
60 BOOST_MPL_HAS_XXX_TRAIT_DEF(key_type);
62 template <typename T> struct iterator_class_is_container {
63 typedef std::reverse_iterator<typename T::iterator> some_iterator;
64 enum { value = has_value_type<T>::value &&
65 std::is_constructible<T, some_iterator, some_iterator>::value };
69 using class_is_container =
70 Conjunction<has_iterator<T>, iterator_class_is_container<T>>;
73 using is_range = StrictConjunction<has_value_type<T>, has_iterator<T>>;
76 using is_container = StrictConjunction<std::is_class<T>, class_is_container<T>>;
79 using is_map = StrictConjunction<is_range<T>, has_mapped_type<T>>;
82 using is_associative = StrictConjunction<is_range<T>, has_key_type<T>>;
84 } // namespace dynamicconverter_detail
86 ///////////////////////////////////////////////////////////////////////////////
90 * We have iterators that dereference to dynamics, but need iterators
91 * that dereference to typename T.
93 * Implementation details:
94 * 1. We cache the value of the dereference operator. This is necessary
95 * because boost::iterator_adaptor requires *it to return a
97 * 2. For const reasons, we cannot call operator= to refresh the
98 * cache: we must call the destructor then placement new.
101 namespace dynamicconverter_detail {
104 struct Dereferencer {
105 static inline void derefToCache(
106 Optional<T>* /* mem */,
107 const dynamic::const_item_iterator& /* it */) {
108 throw TypeError("array", dynamic::Type::OBJECT);
111 static inline void derefToCache(
113 const dynamic::const_iterator& it) {
114 mem->emplace(convertTo<T>(*it));
118 template<typename F, typename S>
119 struct Dereferencer<std::pair<F, S>> {
120 static inline void derefToCache(
121 Optional<std::pair<F, S>>* mem,
122 const dynamic::const_item_iterator& it) {
123 mem->emplace(convertTo<F>(it->first), convertTo<S>(it->second));
126 // Intentional duplication of the code in Dereferencer
127 template <typename T>
128 static inline void derefToCache(
130 const dynamic::const_iterator& it) {
131 mem->emplace(convertTo<T>(*it));
135 template <typename T, typename It>
138 iterator_adaptor<Transformer<T, It>, It, typename T::value_type> {
139 friend class boost::iterator_core_access;
141 typedef typename T::value_type ttype;
143 mutable Optional<ttype> cache_;
146 ++this->base_reference();
150 ttype& dereference() const {
152 Dereferencer<ttype>::derefToCache(&cache_, this->base_reference());
154 return cache_.value();
158 explicit Transformer(const It& it) : Transformer::iterator_adaptor_(it) {}
161 // conversion factory
162 template <typename T, typename It>
163 inline std::move_iterator<Transformer<T, It>> conversionIterator(const It& it) {
164 return std::make_move_iterator(Transformer<T, It>(it));
167 } // namespace dynamicconverter_detail
169 ///////////////////////////////////////////////////////////////////////////////
170 // DynamicConverter specializations
173 * Each specialization of DynamicConverter has the function
174 * 'static T convert(const dynamic&);'
177 // default - intentionally unimplemented
178 template <typename T, typename Enable = void> struct DynamicConverter;
182 struct DynamicConverter<bool> {
183 static bool convert(const dynamic& d) {
189 template <typename T>
190 struct DynamicConverter<
192 typename std::enable_if<
193 std::is_integral<T>::value && !std::is_same<T, bool>::value>::type> {
194 static T convert(const dynamic& d) {
195 return folly::to<T>(d.asInt());
200 template <typename T>
201 struct DynamicConverter<
203 typename std::enable_if<std::is_enum<T>::value>::type> {
204 static T convert(const dynamic& d) {
205 using type = typename std::underlying_type<T>::type;
206 return static_cast<T>(DynamicConverter<type>::convert(d));
211 template <typename T>
212 struct DynamicConverter<
214 typename std::enable_if<std::is_floating_point<T>::value>::type> {
215 static T convert(const dynamic& d) {
216 return folly::to<T>(d.asDouble());
222 struct DynamicConverter<folly::fbstring> {
223 static folly::fbstring convert(const dynamic& d) {
230 struct DynamicConverter<std::string> {
231 static std::string convert(const dynamic& d) {
237 template <typename F, typename S>
238 struct DynamicConverter<std::pair<F, S>> {
239 static std::pair<F, S> convert(const dynamic& d) {
240 if (d.isArray() && d.size() == 2) {
241 return std::make_pair(convertTo<F>(d[0]), convertTo<S>(d[1]));
242 } else if (d.isObject() && d.size() == 1) {
243 auto it = d.items().begin();
244 return std::make_pair(convertTo<F>(it->first), convertTo<S>(it->second));
246 throw TypeError("array (size 2) or object (size 1)", d.type());
251 // non-associative containers
252 template <typename C>
253 struct DynamicConverter<
255 typename std::enable_if<
256 dynamicconverter_detail::is_container<C>::value &&
257 !dynamicconverter_detail::is_associative<C>::value>::type> {
258 static C convert(const dynamic& d) {
260 return C(dynamicconverter_detail::conversionIterator<C>(d.begin()),
261 dynamicconverter_detail::conversionIterator<C>(d.end()));
262 } else if (d.isObject()) {
263 return C(dynamicconverter_detail::conversionIterator<C>
265 dynamicconverter_detail::conversionIterator<C>
268 throw TypeError("object or array", d.type());
273 // associative containers
274 template <typename C>
275 struct DynamicConverter<
277 typename std::enable_if<
278 dynamicconverter_detail::is_container<C>::value &&
279 dynamicconverter_detail::is_associative<C>::value>::type> {
280 static C convert(const dynamic& d) {
281 C ret; // avoid direct initialization due to unordered_map's constructor
282 // causing memory corruption if the iterator throws an exception
285 dynamicconverter_detail::conversionIterator<C>(d.begin()),
286 dynamicconverter_detail::conversionIterator<C>(d.end()));
287 } else if (d.isObject()) {
289 dynamicconverter_detail::conversionIterator<C>(d.items().begin()),
290 dynamicconverter_detail::conversionIterator<C>(d.items().end()));
292 throw TypeError("object or array", d.type());
298 ///////////////////////////////////////////////////////////////////////////////
299 // DynamicConstructor specializations
302 * Each specialization of DynamicConstructor has the function
303 * 'static dynamic construct(const C&);'
307 template <typename C, typename Enable = void>
308 struct DynamicConstructor {
309 static dynamic construct(const C& x) {
315 template <typename C>
316 struct DynamicConstructor<
318 typename std::enable_if<std::is_same<C, dynamic>::value>::type> {
319 static dynamic construct(const C& x) {
325 template <typename C>
326 struct DynamicConstructor<
328 typename std::enable_if<
329 !std::is_same<C, dynamic>::value &&
330 dynamicconverter_detail::is_map<C>::value>::type> {
331 static dynamic construct(const C& x) {
332 dynamic d = dynamic::object;
333 for (const auto& pair : x) {
334 d.insert(toDynamic(pair.first), toDynamic(pair.second));
341 template <typename C>
342 struct DynamicConstructor<
344 typename std::enable_if<
345 !std::is_same<C, dynamic>::value &&
346 !dynamicconverter_detail::is_map<C>::value &&
347 !std::is_constructible<StringPiece, const C&>::value &&
348 dynamicconverter_detail::is_range<C>::value>::type> {
349 static dynamic construct(const C& x) {
350 dynamic d = dynamic::array;
351 for (const auto& item : x) {
352 d.push_back(toDynamic(item));
359 template<typename A, typename B>
360 struct DynamicConstructor<std::pair<A, B>, void> {
361 static dynamic construct(const std::pair<A, B>& x) {
362 dynamic d = dynamic::array;
363 d.push_back(toDynamic(x.first));
364 d.push_back(toDynamic(x.second));
369 ///////////////////////////////////////////////////////////////////////////////
372 template <typename T>
373 T convertTo(const dynamic& d) {
374 return DynamicConverter<typename std::remove_cv<T>::type>::convert(d);
378 dynamic toDynamic(const T& x) {
379 return DynamicConstructor<typename std::remove_cv<T>::type>::construct(x);