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