ee6a850eb485db355ff59eb2273281f7ff27f0c8
[folly.git] / folly / dynamic-inl.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #pragma once
18
19 #include <functional>
20
21 #include <boost/iterator/iterator_adaptor.hpp>
22 #include <boost/iterator/iterator_facade.hpp>
23
24 #include <folly/Conv.h>
25 #include <folly/Format.h>
26 #include <folly/Likely.h>
27
28 //////////////////////////////////////////////////////////////////////
29
30 namespace std {
31
32 template<>
33 struct hash< ::folly::dynamic> {
34   size_t operator()(::folly::dynamic const& d) const {
35     return d.hash();
36   }
37 };
38
39 }
40
41 //////////////////////////////////////////////////////////////////////
42
43 // This is a higher-order preprocessor macro to aid going from runtime
44 // types to the compile time type system.
45 #define FB_DYNAMIC_APPLY(type, apply) \
46   do {                                \
47     switch ((type)) {                 \
48       case NULLT:                     \
49         apply(std::nullptr_t);        \
50         break;                        \
51       case ARRAY:                     \
52         apply(Array);                 \
53         break;                        \
54       case BOOL:                      \
55         apply(bool);                  \
56         break;                        \
57       case DOUBLE:                    \
58         apply(double);                \
59         break;                        \
60       case INT64:                     \
61         apply(int64_t);               \
62         break;                        \
63       case OBJECT:                    \
64         apply(ObjectImpl);            \
65         break;                        \
66       case STRING:                    \
67         apply(std::string);           \
68         break;                        \
69       default:                        \
70         CHECK(0);                     \
71         abort();                      \
72     }                                 \
73   } while (0)
74
75 //////////////////////////////////////////////////////////////////////
76
77 namespace folly {
78
79 struct TypeError : std::runtime_error {
80   explicit TypeError(const std::string& expected, dynamic::Type actual);
81   explicit TypeError(
82       const std::string& expected,
83       dynamic::Type actual1,
84       dynamic::Type actual2);
85   ~TypeError() override;
86 };
87
88 [[noreturn]] void throwTypeError_(
89     std::string const& expected,
90     dynamic::Type actual);
91 [[noreturn]] void throwTypeError_(
92     std::string const& expected,
93     dynamic::Type actual1,
94     dynamic::Type actual2);
95
96 //////////////////////////////////////////////////////////////////////
97
98 namespace detail {
99
100   // This helper is used in destroy() to be able to run destructors on
101   // types like "int64_t" without a compiler error.
102   struct Destroy {
103     template<class T> static void destroy(T* t) { t->~T(); }
104   };
105
106   /*
107    * Helper for implementing numeric conversions in operators on
108    * numbers.  Just promotes to double when one of the arguments is
109    * double, or throws if either is not a numeric type.
110    */
111   template<template<class> class Op>
112   dynamic numericOp(dynamic const& a, dynamic const& b) {
113     if (!a.isNumber() || !b.isNumber()) {
114       throwTypeError_("numeric", a.type(), b.type());
115     }
116     if (a.type() != b.type()) {
117       auto& integ  = a.isInt() ? a : b;
118       auto& nonint = a.isInt() ? b : a;
119       return Op<double>()(to<double>(integ.asInt()), nonint.asDouble());
120     }
121     if (a.isDouble()) {
122       return Op<double>()(a.asDouble(), b.asDouble());
123     }
124     return Op<int64_t>()(a.asInt(), b.asInt());
125   }
126
127 }
128
129 //////////////////////////////////////////////////////////////////////
130
131 /*
132  * We're doing this instead of a simple member typedef to avoid the
133  * undefined behavior of parameterizing std::unordered_map<> with an
134  * incomplete type.
135  *
136  * Note: Later we may add separate order tracking here (a multi-index
137  * type of thing.)
138  */
139 struct dynamic::ObjectImpl : std::unordered_map<dynamic, dynamic> {};
140
141 //////////////////////////////////////////////////////////////////////
142
143 // Helper object for creating objects conveniently.  See object and
144 // the dynamic::dynamic(ObjectMaker&&) ctor.
145 struct dynamic::ObjectMaker {
146   friend struct dynamic;
147
148   explicit ObjectMaker() : val_(dynamic::object) {}
149   explicit ObjectMaker(dynamic key, dynamic val)
150     : val_(dynamic::object)
151   {
152     val_.insert(std::move(key), std::move(val));
153   }
154
155   // Make sure no one tries to save one of these into an lvalue with
156   // auto or anything like that.
157   ObjectMaker(ObjectMaker&&) = default;
158   ObjectMaker(ObjectMaker const&) = delete;
159   ObjectMaker& operator=(ObjectMaker const&) = delete;
160   ObjectMaker& operator=(ObjectMaker&&) = delete;
161
162   // This returns an rvalue-reference instead of an lvalue-reference
163   // to allow constructs like this to moved instead of copied:
164   //  dynamic a = dynamic::object("a", "b")("c", "d")
165   ObjectMaker&& operator()(dynamic key, dynamic val) {
166     val_.insert(std::move(key), std::move(val));
167     return std::move(*this);
168   }
169
170 private:
171   dynamic val_;
172 };
173
174 inline void dynamic::array(EmptyArrayTag) {}
175
176 template <class... Args>
177 inline dynamic dynamic::array(Args&& ...args) {
178   return dynamic(Array{std::forward<Args>(args)...});
179 }
180
181 inline dynamic::ObjectMaker dynamic::object() { return ObjectMaker(); }
182 inline dynamic::ObjectMaker dynamic::object(dynamic a, dynamic b) {
183   return ObjectMaker(std::move(a), std::move(b));
184 }
185
186 //////////////////////////////////////////////////////////////////////
187
188 struct dynamic::item_iterator : boost::iterator_adaptor<
189                                     dynamic::item_iterator,
190                                     dynamic::ObjectImpl::iterator> {
191   /* implicit */ item_iterator(base_type b) : iterator_adaptor_(b) {}
192
193   using object_type = dynamic::ObjectImpl;
194
195  private:
196   friend class boost::iterator_core_access;
197 };
198
199 struct dynamic::value_iterator : boost::iterator_adaptor<
200                                      dynamic::value_iterator,
201                                      dynamic::ObjectImpl::iterator,
202                                      dynamic> {
203   /* implicit */ value_iterator(base_type b) : iterator_adaptor_(b) {}
204
205   using object_type = dynamic::ObjectImpl;
206
207  private:
208   dynamic& dereference() const {
209     return base_reference()->second;
210   }
211   friend class boost::iterator_core_access;
212 };
213
214 struct dynamic::const_item_iterator
215   : boost::iterator_adaptor<dynamic::const_item_iterator,
216                             dynamic::ObjectImpl::const_iterator> {
217   /* implicit */ const_item_iterator(base_type b) : iterator_adaptor_(b) { }
218   /* implicit */ const_item_iterator(item_iterator i)
219       : iterator_adaptor_(i.base()) {}
220   /* implicit */ const_item_iterator(dynamic::ObjectImpl::iterator i)
221       : iterator_adaptor_(i) {}
222
223   using object_type = dynamic::ObjectImpl const;
224
225  private:
226   friend class boost::iterator_core_access;
227 };
228
229 struct dynamic::const_key_iterator
230   : boost::iterator_adaptor<dynamic::const_key_iterator,
231                             dynamic::ObjectImpl::const_iterator,
232                             dynamic const> {
233   /* implicit */ const_key_iterator(base_type b) : iterator_adaptor_(b) { }
234
235   using object_type = dynamic::ObjectImpl const;
236
237  private:
238   dynamic const& dereference() const {
239     return base_reference()->first;
240   }
241   friend class boost::iterator_core_access;
242 };
243
244 struct dynamic::const_value_iterator
245   : boost::iterator_adaptor<dynamic::const_value_iterator,
246                             dynamic::ObjectImpl::const_iterator,
247                             dynamic const> {
248   /* implicit */ const_value_iterator(base_type b) : iterator_adaptor_(b) { }
249   /* implicit */ const_value_iterator(value_iterator i)
250       : iterator_adaptor_(i.base()) {}
251   /* implicit */ const_value_iterator(dynamic::ObjectImpl::iterator i)
252       : iterator_adaptor_(i) {}
253
254   using object_type = dynamic::ObjectImpl const;
255
256  private:
257   dynamic const& dereference() const {
258     return base_reference()->second;
259   }
260   friend class boost::iterator_core_access;
261 };
262
263 //////////////////////////////////////////////////////////////////////
264
265 inline dynamic::dynamic() : dynamic(nullptr) {}
266
267 inline dynamic::dynamic(std::nullptr_t) : type_(NULLT) {}
268
269 inline dynamic::dynamic(void (*)(EmptyArrayTag))
270   : type_(ARRAY)
271 {
272   new (&u_.array) Array();
273 }
274
275 inline dynamic::dynamic(ObjectMaker (*)())
276   : type_(OBJECT)
277 {
278   new (getAddress<ObjectImpl>()) ObjectImpl();
279 }
280
281 inline dynamic::dynamic(StringPiece s)
282   : type_(STRING)
283 {
284   new (&u_.string) std::string(s.data(), s.size());
285 }
286
287 inline dynamic::dynamic(char const* s)
288   : type_(STRING)
289 {
290   new (&u_.string) std::string(s);
291 }
292
293 inline dynamic::dynamic(std::string s)
294   : type_(STRING)
295 {
296   new (&u_.string) std::string(std::move(s));
297 }
298
299 inline dynamic::dynamic(ObjectMaker&& maker)
300   : type_(OBJECT)
301 {
302   new (getAddress<ObjectImpl>())
303     ObjectImpl(std::move(*maker.val_.getAddress<ObjectImpl>()));
304 }
305
306 inline dynamic::dynamic(dynamic const& o)
307   : type_(NULLT)
308 {
309   *this = o;
310 }
311
312 inline dynamic::dynamic(dynamic&& o) noexcept
313   : type_(NULLT)
314 {
315   *this = std::move(o);
316 }
317
318 inline dynamic::~dynamic() noexcept { destroy(); }
319
320 // Integral types except bool convert to int64_t, float types to double.
321 template <class T>
322 struct dynamic::NumericTypeHelper<
323     T, typename std::enable_if<std::is_integral<T>::value>::type> {
324   static_assert(
325       !kIsObjC || sizeof(T) > sizeof(char),
326       "char-sized types are ambiguous in objc; cast to bool or wider type");
327   using type = int64_t;
328 };
329 template <>
330 struct dynamic::NumericTypeHelper<bool> {
331   using type = bool;
332 };
333 template <>
334 struct dynamic::NumericTypeHelper<float> {
335   using type = double;
336 };
337 template <>
338 struct dynamic::NumericTypeHelper<double> {
339   using type = double;
340 };
341
342 template<class T, class NumericType /* = typename NumericTypeHelper<T>::type */>
343 dynamic::dynamic(T t) {
344   type_ = TypeInfo<NumericType>::type;
345   new (getAddress<NumericType>()) NumericType(NumericType(t));
346 }
347
348 template <class Iterator>
349 dynamic::dynamic(Iterator first, Iterator last)
350   : type_(ARRAY)
351 {
352   new (&u_.array) Array(first, last);
353 }
354
355 //////////////////////////////////////////////////////////////////////
356
357 inline dynamic::const_iterator dynamic::begin() const {
358   return get<Array>().begin();
359 }
360 inline dynamic::const_iterator dynamic::end() const {
361   return get<Array>().end();
362 }
363
364 inline dynamic::iterator dynamic::begin() {
365   return get<Array>().begin();
366 }
367 inline dynamic::iterator dynamic::end() {
368   return get<Array>().end();
369 }
370
371 template <class It>
372 struct dynamic::IterableProxy {
373   typedef It iterator;
374   typedef typename It::value_type value_type;
375   typedef typename It::object_type object_type;
376
377   /* implicit */ IterableProxy(object_type* o) : o_(o) {}
378
379   It begin() const {
380     return o_->begin();
381   }
382
383   It end() const {
384     return o_->end();
385   }
386
387  private:
388   object_type* o_;
389 };
390
391 inline dynamic::IterableProxy<dynamic::const_key_iterator> dynamic::keys()
392   const {
393   return &(get<ObjectImpl>());
394 }
395
396 inline dynamic::IterableProxy<dynamic::const_value_iterator> dynamic::values()
397   const {
398   return &(get<ObjectImpl>());
399 }
400
401 inline dynamic::IterableProxy<dynamic::const_item_iterator> dynamic::items()
402   const {
403   return &(get<ObjectImpl>());
404 }
405
406 inline dynamic::IterableProxy<dynamic::value_iterator> dynamic::values() {
407   return &(get<ObjectImpl>());
408 }
409
410 inline dynamic::IterableProxy<dynamic::item_iterator> dynamic::items() {
411   return &(get<ObjectImpl>());
412 }
413
414 inline bool dynamic::isString() const {
415   return get_nothrow<std::string>() != nullptr;
416 }
417 inline bool dynamic::isObject() const {
418   return get_nothrow<ObjectImpl>() != nullptr;
419 }
420 inline bool dynamic::isBool() const {
421   return get_nothrow<bool>() != nullptr;
422 }
423 inline bool dynamic::isArray() const {
424   return get_nothrow<Array>() != nullptr;
425 }
426 inline bool dynamic::isDouble() const {
427   return get_nothrow<double>() != nullptr;
428 }
429 inline bool dynamic::isInt() const {
430   return get_nothrow<int64_t>() != nullptr;
431 }
432 inline bool dynamic::isNull() const {
433   return get_nothrow<std::nullptr_t>() != nullptr;
434 }
435 inline bool dynamic::isNumber() const {
436   return isInt() || isDouble();
437 }
438
439 inline dynamic::Type dynamic::type() const {
440   return type_;
441 }
442
443 inline std::string dynamic::asString() const {
444   return asImpl<std::string>();
445 }
446 inline double dynamic::asDouble() const {
447   return asImpl<double>();
448 }
449 inline int64_t dynamic::asInt() const {
450   return asImpl<int64_t>();
451 }
452 inline bool dynamic::asBool() const {
453   return asImpl<bool>();
454 }
455
456 inline const std::string& dynamic::getString() const& {
457   return get<std::string>();
458 }
459 inline double          dynamic::getDouble() const& { return get<double>(); }
460 inline int64_t         dynamic::getInt()    const& { return get<int64_t>(); }
461 inline bool            dynamic::getBool()   const& { return get<bool>(); }
462
463 inline std::string& dynamic::getString()& {
464   return get<std::string>();
465 }
466 inline double&   dynamic::getDouble() & { return get<double>(); }
467 inline int64_t&  dynamic::getInt()    & { return get<int64_t>(); }
468 inline bool&     dynamic::getBool()   & { return get<bool>(); }
469
470 inline std::string&& dynamic::getString()&& {
471   return std::move(get<std::string>());
472 }
473 inline double   dynamic::getDouble() && { return get<double>(); }
474 inline int64_t  dynamic::getInt()    && { return get<int64_t>(); }
475 inline bool     dynamic::getBool()   && { return get<bool>(); }
476
477 inline const char* dynamic::data() const& {
478   return get<std::string>().data();
479 }
480 inline const char* dynamic::c_str() const& {
481   return get<std::string>().c_str();
482 }
483 inline StringPiece dynamic::stringPiece() const {
484   return get<std::string>();
485 }
486
487 template<class T>
488 struct dynamic::CompareOp {
489   static bool comp(T const& a, T const& b) { return a < b; }
490 };
491 template<>
492 struct dynamic::CompareOp<dynamic::ObjectImpl> {
493   static bool comp(ObjectImpl const&, ObjectImpl const&) {
494     // This code never executes; it is just here for the compiler.
495     return false;
496   }
497 };
498 template<>
499 struct dynamic::CompareOp<std::nullptr_t> {
500   static bool comp(std::nullptr_t const&, std::nullptr_t const&) {
501     return true;
502   }
503 };
504
505 inline dynamic& dynamic::operator+=(dynamic const& o) {
506   if (type() == STRING && o.type() == STRING) {
507     *getAddress<std::string>() += *o.getAddress<std::string>();
508     return *this;
509   }
510   *this = detail::numericOp<std::plus>(*this, o);
511   return *this;
512 }
513
514 inline dynamic& dynamic::operator-=(dynamic const& o) {
515   *this = detail::numericOp<std::minus>(*this, o);
516   return *this;
517 }
518
519 inline dynamic& dynamic::operator*=(dynamic const& o) {
520   *this = detail::numericOp<std::multiplies>(*this, o);
521   return *this;
522 }
523
524 inline dynamic& dynamic::operator/=(dynamic const& o) {
525   *this = detail::numericOp<std::divides>(*this, o);
526   return *this;
527 }
528
529 #define FB_DYNAMIC_INTEGER_OP(op)                          \
530   inline dynamic& dynamic::operator op(dynamic const& o) { \
531     if (!isInt() || !o.isInt()) {                          \
532       throwTypeError_("int64", type(), o.type());          \
533     }                                                      \
534     *getAddress<int64_t>() op o.asInt();                   \
535     return *this;                                          \
536   }
537
538 FB_DYNAMIC_INTEGER_OP(%=)
539 FB_DYNAMIC_INTEGER_OP(|=)
540 FB_DYNAMIC_INTEGER_OP(&=)
541 FB_DYNAMIC_INTEGER_OP(^=)
542
543 #undef FB_DYNAMIC_INTEGER_OP
544
545 inline dynamic& dynamic::operator++() {
546   ++get<int64_t>();
547   return *this;
548 }
549
550 inline dynamic& dynamic::operator--() {
551   --get<int64_t>();
552   return *this;
553 }
554
555 inline dynamic const& dynamic::operator[](dynamic const& idx) const& {
556   return at(idx);
557 }
558
559 inline dynamic&& dynamic::operator[](dynamic const& idx) && {
560   return std::move((*this)[idx]);
561 }
562
563 template<class K, class V> inline dynamic& dynamic::setDefault(K&& k, V&& v) {
564   auto& obj = get<ObjectImpl>();
565   return obj.insert(std::make_pair(std::forward<K>(k),
566                                    std::forward<V>(v))).first->second;
567 }
568
569 template<class K> inline dynamic& dynamic::setDefault(K&& k, dynamic&& v) {
570   auto& obj = get<ObjectImpl>();
571   return obj.insert(std::make_pair(std::forward<K>(k),
572                                    std::move(v))).first->second;
573 }
574
575 template<class K> inline dynamic& dynamic::setDefault(K&& k, const dynamic& v) {
576   auto& obj = get<ObjectImpl>();
577   return obj.insert(std::make_pair(std::forward<K>(k), v)).first->second;
578 }
579
580 inline dynamic* dynamic::get_ptr(dynamic const& idx) & {
581   return const_cast<dynamic*>(const_cast<dynamic const*>(this)->get_ptr(idx));
582 }
583
584 inline dynamic& dynamic::at(dynamic const& idx) & {
585   return const_cast<dynamic&>(const_cast<dynamic const*>(this)->at(idx));
586 }
587
588 inline dynamic&& dynamic::at(dynamic const& idx) && {
589   return std::move(at(idx));
590 }
591
592 inline bool dynamic::empty() const {
593   if (isNull()) {
594     return true;
595   }
596   return !size();
597 }
598
599 inline std::size_t dynamic::count(dynamic const& key) const {
600   return find(key) != items().end() ? 1u : 0u;
601 }
602
603 inline dynamic::const_item_iterator dynamic::find(dynamic const& key) const {
604   return get<ObjectImpl>().find(key);
605 }
606 inline dynamic::item_iterator dynamic::find(dynamic const& key) {
607   return get<ObjectImpl>().find(key);
608 }
609
610 template<class K, class V> inline void dynamic::insert(K&& key, V&& val) {
611   auto& obj = get<ObjectImpl>();
612   auto rv = obj.insert({ std::forward<K>(key), nullptr });
613   rv.first->second = std::forward<V>(val);
614 }
615
616 inline void dynamic::update(const dynamic& mergeObj) {
617   if (!isObject() || !mergeObj.isObject()) {
618     throwTypeError_("object", type(), mergeObj.type());
619   }
620
621   for (const auto& pair : mergeObj.items()) {
622     (*this)[pair.first] = pair.second;
623   }
624 }
625
626 inline void dynamic::update_missing(const dynamic& mergeObj1) {
627   if (!isObject() || !mergeObj1.isObject()) {
628     throwTypeError_("object", type(), mergeObj1.type());
629   }
630
631   // Only add if not already there
632   for (const auto& pair : mergeObj1.items()) {
633     if ((*this).find(pair.first) == (*this).items().end()) {
634       (*this)[pair.first] = pair.second;
635     }
636   }
637 }
638
639 inline dynamic dynamic::merge(
640     const dynamic& mergeObj1,
641     const dynamic& mergeObj2) {
642
643   // No checks on type needed here because they are done in update_missing
644   // Note that we do update_missing here instead of update() because
645   // it will prevent the extra writes that would occur with update()
646   auto ret = mergeObj2;
647   ret.update_missing(mergeObj1);
648   return ret;
649 }
650
651 inline std::size_t dynamic::erase(dynamic const& key) {
652   auto& obj = get<ObjectImpl>();
653   return obj.erase(key);
654 }
655
656 inline dynamic::iterator dynamic::erase(const_iterator it) {
657   auto& arr = get<Array>();
658   // std::vector doesn't have an erase method that works on const iterators,
659   // even though the standard says it should, so this hack converts to a
660   // non-const iterator before calling erase.
661   return get<Array>().erase(arr.begin() + (it - arr.begin()));
662 }
663
664 inline dynamic::const_key_iterator dynamic::erase(const_key_iterator it) {
665   return const_key_iterator(get<ObjectImpl>().erase(it.base()));
666 }
667
668 inline dynamic::const_key_iterator dynamic::erase(
669     const_key_iterator first,
670     const_key_iterator last) {
671   return const_key_iterator(get<ObjectImpl>().erase(first.base(),
672                                                     last.base()));
673 }
674
675 inline dynamic::value_iterator dynamic::erase(const_value_iterator it) {
676   return value_iterator(get<ObjectImpl>().erase(it.base()));
677 }
678
679 inline dynamic::value_iterator dynamic::erase(
680     const_value_iterator first,
681     const_value_iterator last) {
682   return value_iterator(get<ObjectImpl>().erase(first.base(), last.base()));
683 }
684
685 inline dynamic::item_iterator dynamic::erase(const_item_iterator it) {
686   return item_iterator(get<ObjectImpl>().erase(it.base()));
687 }
688
689 inline dynamic::item_iterator dynamic::erase(
690     const_item_iterator first,
691     const_item_iterator last) {
692   return item_iterator(get<ObjectImpl>().erase(first.base(), last.base()));
693 }
694
695 inline void dynamic::resize(std::size_t sz, dynamic const& c) {
696   auto& arr = get<Array>();
697   arr.resize(sz, c);
698 }
699
700 inline void dynamic::push_back(dynamic const& v) {
701   auto& arr = get<Array>();
702   arr.push_back(v);
703 }
704
705 inline void dynamic::push_back(dynamic&& v) {
706   auto& arr = get<Array>();
707   arr.push_back(std::move(v));
708 }
709
710 inline void dynamic::pop_back() {
711   auto& arr = get<Array>();
712   arr.pop_back();
713 }
714
715 //////////////////////////////////////////////////////////////////////
716
717 inline dynamic::dynamic(Array&& r) : type_(ARRAY) {
718   new (&u_.array) Array(std::move(r));
719 }
720
721 #define FOLLY_DYNAMIC_DEC_TYPEINFO(T, str, val) \
722   template <> struct dynamic::TypeInfo<T> { \
723     static constexpr const char* name = str; \
724     static constexpr dynamic::Type type = val; \
725   }; \
726   //
727
728 FOLLY_DYNAMIC_DEC_TYPEINFO(std::nullptr_t,      "null",    dynamic::NULLT)
729 FOLLY_DYNAMIC_DEC_TYPEINFO(bool,                "boolean", dynamic::BOOL)
730 FOLLY_DYNAMIC_DEC_TYPEINFO(std::string,         "string",  dynamic::STRING)
731 FOLLY_DYNAMIC_DEC_TYPEINFO(dynamic::Array,      "array",   dynamic::ARRAY)
732 FOLLY_DYNAMIC_DEC_TYPEINFO(double,              "double",  dynamic::DOUBLE)
733 FOLLY_DYNAMIC_DEC_TYPEINFO(int64_t,             "int64",   dynamic::INT64)
734 FOLLY_DYNAMIC_DEC_TYPEINFO(dynamic::ObjectImpl, "object",  dynamic::OBJECT)
735
736 #undef FOLLY_DYNAMIC_DEC_TYPEINFO
737
738 template<class T>
739 T dynamic::asImpl() const {
740   switch (type()) {
741   case INT64:    return to<T>(*get_nothrow<int64_t>());
742   case DOUBLE:   return to<T>(*get_nothrow<double>());
743   case BOOL:     return to<T>(*get_nothrow<bool>());
744   case STRING:
745     return to<T>(*get_nothrow<std::string>());
746   default:
747     throwTypeError_("int/double/bool/string", type());
748   }
749 }
750
751 // Return a T* to our type, or null if we're not that type.
752 template<class T>
753 T* dynamic::get_nothrow() & noexcept {
754   if (type_ != TypeInfo<T>::type) {
755     return nullptr;
756   }
757   return getAddress<T>();
758 }
759
760 template<class T>
761 T const* dynamic::get_nothrow() const& noexcept {
762   return const_cast<dynamic*>(this)->get_nothrow<T>();
763 }
764
765 // Return T* for where we can put a T, without type checking.  (Memory
766 // might be uninitialized, even.)
767 template<class T>
768 T* dynamic::getAddress() noexcept {
769   return GetAddrImpl<T>::get(u_);
770 }
771
772 template<class T>
773 T const* dynamic::getAddress() const noexcept {
774   return const_cast<dynamic*>(this)->getAddress<T>();
775 }
776
777 template<class T> struct dynamic::GetAddrImpl {};
778 template<> struct dynamic::GetAddrImpl<std::nullptr_t> {
779   static std::nullptr_t* get(Data& d) noexcept { return &d.nul; }
780 };
781 template<> struct dynamic::GetAddrImpl<dynamic::Array> {
782   static Array* get(Data& d) noexcept { return &d.array; }
783 };
784 template<> struct dynamic::GetAddrImpl<bool> {
785   static bool* get(Data& d) noexcept { return &d.boolean; }
786 };
787 template<> struct dynamic::GetAddrImpl<int64_t> {
788   static int64_t* get(Data& d) noexcept { return &d.integer; }
789 };
790 template<> struct dynamic::GetAddrImpl<double> {
791   static double* get(Data& d) noexcept { return &d.doubl; }
792 };
793 template <>
794 struct dynamic::GetAddrImpl<std::string> {
795   static std::string* get(Data& d) noexcept {
796     return &d.string;
797   }
798 };
799 template<> struct dynamic::GetAddrImpl<dynamic::ObjectImpl> {
800   static_assert(sizeof(ObjectImpl) <= sizeof(Data::objectBuffer),
801     "In your implementation, std::unordered_map<> apparently takes different"
802     " amount of space depending on its template parameters.  This is "
803     "weird.  Make objectBuffer bigger if you want to compile dynamic.");
804
805   static ObjectImpl* get(Data& d) noexcept {
806     void* data = &d.objectBuffer;
807     return static_cast<ObjectImpl*>(data);
808   }
809 };
810
811 template<class T>
812 T& dynamic::get() {
813   if (auto* p = get_nothrow<T>()) {
814     return *p;
815   }
816   throwTypeError_(TypeInfo<T>::name, type());
817 }
818
819 template<class T>
820 T const& dynamic::get() const {
821   return const_cast<dynamic*>(this)->get<T>();
822 }
823
824 //////////////////////////////////////////////////////////////////////
825
826 /*
827  * Helper for implementing operator<<.  Throws if the type shouldn't
828  * support it.
829  */
830 template<class T>
831 struct dynamic::PrintImpl {
832   static void print(dynamic const&, std::ostream& out, T const& t) {
833     out << t;
834   }
835 };
836 // Otherwise, null, being (void*)0, would print as 0.
837 template <>
838 struct dynamic::PrintImpl<std::nullptr_t> {
839   static void print(dynamic const& /* d */,
840                     std::ostream& out,
841                     std::nullptr_t const&) {
842     out << "null";
843   }
844 };
845 template<>
846 struct dynamic::PrintImpl<dynamic::ObjectImpl> {
847   static void print(dynamic const& d,
848                     std::ostream& out,
849                     dynamic::ObjectImpl const&) {
850     d.print_as_pseudo_json(out);
851   }
852 };
853 template<>
854 struct dynamic::PrintImpl<dynamic::Array> {
855   static void print(dynamic const& d,
856                     std::ostream& out,
857                     dynamic::Array const&) {
858     d.print_as_pseudo_json(out);
859   }
860 };
861
862 inline void dynamic::print(std::ostream& out) const {
863 #define FB_X(T) PrintImpl<T>::print(*this, out, *getAddress<T>())
864   FB_DYNAMIC_APPLY(type_, FB_X);
865 #undef FB_X
866 }
867
868 inline std::ostream& operator<<(std::ostream& out, dynamic const& d) {
869   d.print(out);
870   return out;
871 }
872
873 //////////////////////////////////////////////////////////////////////
874
875 // Secialization of FormatValue so dynamic objects can be formatted
876 template <>
877 class FormatValue<dynamic> {
878  public:
879   explicit FormatValue(const dynamic& val) : val_(val) { }
880
881   template <class FormatCallback>
882   void format(FormatArg& arg, FormatCallback& cb) const {
883     switch (val_.type()) {
884     case dynamic::NULLT:
885       FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
886       break;
887     case dynamic::BOOL:
888       FormatValue<bool>(val_.asBool()).format(arg, cb);
889       break;
890     case dynamic::INT64:
891       FormatValue<int64_t>(val_.asInt()).format(arg, cb);
892       break;
893     case dynamic::STRING:
894       FormatValue<std::string>(val_.asString()).format(arg, cb);
895       break;
896     case dynamic::DOUBLE:
897       FormatValue<double>(val_.asDouble()).format(arg, cb);
898       break;
899     case dynamic::ARRAY:
900       FormatValue(val_.at(arg.splitIntKey())).format(arg, cb);
901       break;
902     case dynamic::OBJECT:
903       FormatValue(val_.at(arg.splitKey().toString())).format(arg, cb);
904       break;
905     }
906   }
907
908  private:
909   const dynamic& val_;
910 };
911
912 template <class V>
913 class FormatValue<detail::DefaultValueWrapper<dynamic, V>> {
914  public:
915   explicit FormatValue(
916       const detail::DefaultValueWrapper<dynamic, V>& val)
917     : val_(val) { }
918
919   template <class FormatCallback>
920   void format(FormatArg& arg, FormatCallback& cb) const {
921     auto& c = val_.container;
922     switch (c.type()) {
923     case dynamic::NULLT:
924     case dynamic::BOOL:
925     case dynamic::INT64:
926     case dynamic::STRING:
927     case dynamic::DOUBLE:
928       FormatValue<dynamic>(c).format(arg, cb);
929       break;
930     case dynamic::ARRAY:
931       {
932         int key = arg.splitIntKey();
933         if (key >= 0 && size_t(key) < c.size()) {
934           FormatValue<dynamic>(c.at(key)).format(arg, cb);
935         } else{
936           FormatValue<V>(val_.defaultValue).format(arg, cb);
937         }
938       }
939       break;
940     case dynamic::OBJECT:
941       {
942         auto pos = c.find(arg.splitKey());
943         if (pos != c.items().end()) {
944           FormatValue<dynamic>(pos->second).format(arg, cb);
945         } else {
946           FormatValue<V>(val_.defaultValue).format(arg, cb);
947         }
948       }
949       break;
950     }
951   }
952
953  private:
954   const detail::DefaultValueWrapper<dynamic, V>& val_;
955 };
956
957 }  // namespaces
958
959 #undef FB_DYNAMIC_APPLY