Consistency in namespace-closing comments
[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 <
343     class T,
344     class NumericType /* = typename NumericTypeHelper<T>::type */>
345 dynamic::dynamic(T t) {
346   type_ = TypeInfo<NumericType>::type;
347   new (getAddress<NumericType>()) NumericType(NumericType(t));
348 }
349
350 template <class Iterator>
351 dynamic::dynamic(Iterator first, Iterator last)
352   : type_(ARRAY)
353 {
354   new (&u_.array) Array(first, last);
355 }
356
357 //////////////////////////////////////////////////////////////////////
358
359 inline dynamic::const_iterator dynamic::begin() const {
360   return get<Array>().begin();
361 }
362 inline dynamic::const_iterator dynamic::end() const {
363   return get<Array>().end();
364 }
365
366 inline dynamic::iterator dynamic::begin() {
367   return get<Array>().begin();
368 }
369 inline dynamic::iterator dynamic::end() {
370   return get<Array>().end();
371 }
372
373 template <class It>
374 struct dynamic::IterableProxy {
375   typedef It iterator;
376   typedef typename It::value_type value_type;
377   typedef typename It::object_type object_type;
378
379   /* implicit */ IterableProxy(object_type* o) : o_(o) {}
380
381   It begin() const {
382     return o_->begin();
383   }
384
385   It end() const {
386     return o_->end();
387   }
388
389  private:
390   object_type* o_;
391 };
392
393 inline dynamic::IterableProxy<dynamic::const_key_iterator> dynamic::keys()
394   const {
395   return &(get<ObjectImpl>());
396 }
397
398 inline dynamic::IterableProxy<dynamic::const_value_iterator> dynamic::values()
399   const {
400   return &(get<ObjectImpl>());
401 }
402
403 inline dynamic::IterableProxy<dynamic::const_item_iterator> dynamic::items()
404   const {
405   return &(get<ObjectImpl>());
406 }
407
408 inline dynamic::IterableProxy<dynamic::value_iterator> dynamic::values() {
409   return &(get<ObjectImpl>());
410 }
411
412 inline dynamic::IterableProxy<dynamic::item_iterator> dynamic::items() {
413   return &(get<ObjectImpl>());
414 }
415
416 inline bool dynamic::isString() const {
417   return get_nothrow<std::string>() != nullptr;
418 }
419 inline bool dynamic::isObject() const {
420   return get_nothrow<ObjectImpl>() != nullptr;
421 }
422 inline bool dynamic::isBool() const {
423   return get_nothrow<bool>() != nullptr;
424 }
425 inline bool dynamic::isArray() const {
426   return get_nothrow<Array>() != nullptr;
427 }
428 inline bool dynamic::isDouble() const {
429   return get_nothrow<double>() != nullptr;
430 }
431 inline bool dynamic::isInt() const {
432   return get_nothrow<int64_t>() != nullptr;
433 }
434 inline bool dynamic::isNull() const {
435   return get_nothrow<std::nullptr_t>() != nullptr;
436 }
437 inline bool dynamic::isNumber() const {
438   return isInt() || isDouble();
439 }
440
441 inline dynamic::Type dynamic::type() const {
442   return type_;
443 }
444
445 inline std::string dynamic::asString() const {
446   return asImpl<std::string>();
447 }
448 inline double dynamic::asDouble() const {
449   return asImpl<double>();
450 }
451 inline int64_t dynamic::asInt() const {
452   return asImpl<int64_t>();
453 }
454 inline bool dynamic::asBool() const {
455   return asImpl<bool>();
456 }
457
458 inline const std::string& dynamic::getString() const& {
459   return get<std::string>();
460 }
461 inline double          dynamic::getDouble() const& { return get<double>(); }
462 inline int64_t         dynamic::getInt()    const& { return get<int64_t>(); }
463 inline bool            dynamic::getBool()   const& { return get<bool>(); }
464
465 inline std::string& dynamic::getString()& {
466   return get<std::string>();
467 }
468 inline double&   dynamic::getDouble() & { return get<double>(); }
469 inline int64_t&  dynamic::getInt()    & { return get<int64_t>(); }
470 inline bool&     dynamic::getBool()   & { return get<bool>(); }
471
472 inline std::string&& dynamic::getString()&& {
473   return std::move(get<std::string>());
474 }
475 inline double   dynamic::getDouble() && { return get<double>(); }
476 inline int64_t  dynamic::getInt()    && { return get<int64_t>(); }
477 inline bool     dynamic::getBool()   && { return get<bool>(); }
478
479 inline const char* dynamic::data() const& {
480   return get<std::string>().data();
481 }
482 inline const char* dynamic::c_str() const& {
483   return get<std::string>().c_str();
484 }
485 inline StringPiece dynamic::stringPiece() const {
486   return get<std::string>();
487 }
488
489 template <class T>
490 struct dynamic::CompareOp {
491   static bool comp(T const& a, T const& b) { return a < b; }
492 };
493 template <>
494 struct dynamic::CompareOp<dynamic::ObjectImpl> {
495   static bool comp(ObjectImpl const&, ObjectImpl const&) {
496     // This code never executes; it is just here for the compiler.
497     return false;
498   }
499 };
500 template <>
501 struct dynamic::CompareOp<std::nullptr_t> {
502   static bool comp(std::nullptr_t const&, std::nullptr_t const&) {
503     return true;
504   }
505 };
506
507 inline dynamic& dynamic::operator+=(dynamic const& o) {
508   if (type() == STRING && o.type() == STRING) {
509     *getAddress<std::string>() += *o.getAddress<std::string>();
510     return *this;
511   }
512   *this = detail::numericOp<std::plus>(*this, o);
513   return *this;
514 }
515
516 inline dynamic& dynamic::operator-=(dynamic const& o) {
517   *this = detail::numericOp<std::minus>(*this, o);
518   return *this;
519 }
520
521 inline dynamic& dynamic::operator*=(dynamic const& o) {
522   *this = detail::numericOp<std::multiplies>(*this, o);
523   return *this;
524 }
525
526 inline dynamic& dynamic::operator/=(dynamic const& o) {
527   *this = detail::numericOp<std::divides>(*this, o);
528   return *this;
529 }
530
531 #define FB_DYNAMIC_INTEGER_OP(op)                          \
532   inline dynamic& dynamic::operator op(dynamic const& o) { \
533     if (!isInt() || !o.isInt()) {                          \
534       throwTypeError_("int64", type(), o.type());          \
535     }                                                      \
536     *getAddress<int64_t>() op o.asInt();                   \
537     return *this;                                          \
538   }
539
540 FB_DYNAMIC_INTEGER_OP(%=)
541 FB_DYNAMIC_INTEGER_OP(|=)
542 FB_DYNAMIC_INTEGER_OP(&=)
543 FB_DYNAMIC_INTEGER_OP(^=)
544
545 #undef FB_DYNAMIC_INTEGER_OP
546
547 inline dynamic& dynamic::operator++() {
548   ++get<int64_t>();
549   return *this;
550 }
551
552 inline dynamic& dynamic::operator--() {
553   --get<int64_t>();
554   return *this;
555 }
556
557 inline dynamic const& dynamic::operator[](dynamic const& idx) const& {
558   return at(idx);
559 }
560
561 inline dynamic&& dynamic::operator[](dynamic const& idx) && {
562   return std::move((*this)[idx]);
563 }
564
565 template <class K, class V> inline dynamic& dynamic::setDefault(K&& k, V&& v) {
566   auto& obj = get<ObjectImpl>();
567   return obj.insert(std::make_pair(std::forward<K>(k),
568                                    std::forward<V>(v))).first->second;
569 }
570
571 template <class K> inline dynamic& dynamic::setDefault(K&& k, dynamic&& v) {
572   auto& obj = get<ObjectImpl>();
573   return obj.insert(std::make_pair(std::forward<K>(k),
574                                    std::move(v))).first->second;
575 }
576
577 template <class K> inline dynamic& dynamic::setDefault(K&& k, const dynamic& v) {
578   auto& obj = get<ObjectImpl>();
579   return obj.insert(std::make_pair(std::forward<K>(k), v)).first->second;
580 }
581
582 inline dynamic* dynamic::get_ptr(dynamic const& idx) & {
583   return const_cast<dynamic*>(const_cast<dynamic const*>(this)->get_ptr(idx));
584 }
585
586 inline dynamic& dynamic::at(dynamic const& idx) & {
587   return const_cast<dynamic&>(const_cast<dynamic const*>(this)->at(idx));
588 }
589
590 inline dynamic&& dynamic::at(dynamic const& idx) && {
591   return std::move(at(idx));
592 }
593
594 inline bool dynamic::empty() const {
595   if (isNull()) {
596     return true;
597   }
598   return !size();
599 }
600
601 inline std::size_t dynamic::count(dynamic const& key) const {
602   return find(key) != items().end() ? 1u : 0u;
603 }
604
605 inline dynamic::const_item_iterator dynamic::find(dynamic const& key) const {
606   return get<ObjectImpl>().find(key);
607 }
608 inline dynamic::item_iterator dynamic::find(dynamic const& key) {
609   return get<ObjectImpl>().find(key);
610 }
611
612 template <class K, class V> inline void dynamic::insert(K&& key, V&& val) {
613   auto& obj = get<ObjectImpl>();
614   auto rv = obj.insert({ std::forward<K>(key), nullptr });
615   rv.first->second = std::forward<V>(val);
616 }
617
618 inline void dynamic::update(const dynamic& mergeObj) {
619   if (!isObject() || !mergeObj.isObject()) {
620     throwTypeError_("object", type(), mergeObj.type());
621   }
622
623   for (const auto& pair : mergeObj.items()) {
624     (*this)[pair.first] = pair.second;
625   }
626 }
627
628 inline void dynamic::update_missing(const dynamic& mergeObj1) {
629   if (!isObject() || !mergeObj1.isObject()) {
630     throwTypeError_("object", type(), mergeObj1.type());
631   }
632
633   // Only add if not already there
634   for (const auto& pair : mergeObj1.items()) {
635     if ((*this).find(pair.first) == (*this).items().end()) {
636       (*this)[pair.first] = pair.second;
637     }
638   }
639 }
640
641 inline dynamic dynamic::merge(
642     const dynamic& mergeObj1,
643     const dynamic& mergeObj2) {
644
645   // No checks on type needed here because they are done in update_missing
646   // Note that we do update_missing here instead of update() because
647   // it will prevent the extra writes that would occur with update()
648   auto ret = mergeObj2;
649   ret.update_missing(mergeObj1);
650   return ret;
651 }
652
653 inline std::size_t dynamic::erase(dynamic const& key) {
654   auto& obj = get<ObjectImpl>();
655   return obj.erase(key);
656 }
657
658 inline dynamic::iterator dynamic::erase(const_iterator it) {
659   auto& arr = get<Array>();
660   // std::vector doesn't have an erase method that works on const iterators,
661   // even though the standard says it should, so this hack converts to a
662   // non-const iterator before calling erase.
663   return get<Array>().erase(arr.begin() + (it - arr.begin()));
664 }
665
666 inline dynamic::const_key_iterator dynamic::erase(const_key_iterator it) {
667   return const_key_iterator(get<ObjectImpl>().erase(it.base()));
668 }
669
670 inline dynamic::const_key_iterator dynamic::erase(
671     const_key_iterator first,
672     const_key_iterator last) {
673   return const_key_iterator(get<ObjectImpl>().erase(first.base(),
674                                                     last.base()));
675 }
676
677 inline dynamic::value_iterator dynamic::erase(const_value_iterator it) {
678   return value_iterator(get<ObjectImpl>().erase(it.base()));
679 }
680
681 inline dynamic::value_iterator dynamic::erase(
682     const_value_iterator first,
683     const_value_iterator last) {
684   return value_iterator(get<ObjectImpl>().erase(first.base(), last.base()));
685 }
686
687 inline dynamic::item_iterator dynamic::erase(const_item_iterator it) {
688   return item_iterator(get<ObjectImpl>().erase(it.base()));
689 }
690
691 inline dynamic::item_iterator dynamic::erase(
692     const_item_iterator first,
693     const_item_iterator last) {
694   return item_iterator(get<ObjectImpl>().erase(first.base(), last.base()));
695 }
696
697 inline void dynamic::resize(std::size_t sz, dynamic const& c) {
698   auto& arr = get<Array>();
699   arr.resize(sz, c);
700 }
701
702 inline void dynamic::push_back(dynamic const& v) {
703   auto& arr = get<Array>();
704   arr.push_back(v);
705 }
706
707 inline void dynamic::push_back(dynamic&& v) {
708   auto& arr = get<Array>();
709   arr.push_back(std::move(v));
710 }
711
712 inline void dynamic::pop_back() {
713   auto& arr = get<Array>();
714   arr.pop_back();
715 }
716
717 //////////////////////////////////////////////////////////////////////
718
719 inline dynamic::dynamic(Array&& r) : type_(ARRAY) {
720   new (&u_.array) Array(std::move(r));
721 }
722
723 #define FOLLY_DYNAMIC_DEC_TYPEINFO(T, str, val) \
724   template <> struct dynamic::TypeInfo<T> { \
725     static constexpr const char* name = str; \
726     static constexpr dynamic::Type type = val; \
727   }; \
728   //
729
730 FOLLY_DYNAMIC_DEC_TYPEINFO(std::nullptr_t,      "null",    dynamic::NULLT)
731 FOLLY_DYNAMIC_DEC_TYPEINFO(bool,                "boolean", dynamic::BOOL)
732 FOLLY_DYNAMIC_DEC_TYPEINFO(std::string,         "string",  dynamic::STRING)
733 FOLLY_DYNAMIC_DEC_TYPEINFO(dynamic::Array,      "array",   dynamic::ARRAY)
734 FOLLY_DYNAMIC_DEC_TYPEINFO(double,              "double",  dynamic::DOUBLE)
735 FOLLY_DYNAMIC_DEC_TYPEINFO(int64_t,             "int64",   dynamic::INT64)
736 FOLLY_DYNAMIC_DEC_TYPEINFO(dynamic::ObjectImpl, "object",  dynamic::OBJECT)
737
738 #undef FOLLY_DYNAMIC_DEC_TYPEINFO
739
740 template <class T>
741 T dynamic::asImpl() const {
742   switch (type()) {
743   case INT64:    return to<T>(*get_nothrow<int64_t>());
744   case DOUBLE:   return to<T>(*get_nothrow<double>());
745   case BOOL:     return to<T>(*get_nothrow<bool>());
746   case STRING:
747     return to<T>(*get_nothrow<std::string>());
748   default:
749     throwTypeError_("int/double/bool/string", type());
750   }
751 }
752
753 // Return a T* to our type, or null if we're not that type.
754 template <class T>
755 T* dynamic::get_nothrow() & noexcept {
756   if (type_ != TypeInfo<T>::type) {
757     return nullptr;
758   }
759   return getAddress<T>();
760 }
761
762 template <class T>
763 T const* dynamic::get_nothrow() const& noexcept {
764   return const_cast<dynamic*>(this)->get_nothrow<T>();
765 }
766
767 // Return T* for where we can put a T, without type checking.  (Memory
768 // might be uninitialized, even.)
769 template <class T>
770 T* dynamic::getAddress() noexcept {
771   return GetAddrImpl<T>::get(u_);
772 }
773
774 template <class T>
775 T const* dynamic::getAddress() const noexcept {
776   return const_cast<dynamic*>(this)->getAddress<T>();
777 }
778
779 template <class T> struct dynamic::GetAddrImpl {};
780 template <> struct dynamic::GetAddrImpl<std::nullptr_t> {
781   static std::nullptr_t* get(Data& d) noexcept { return &d.nul; }
782 };
783 template <> struct dynamic::GetAddrImpl<dynamic::Array> {
784   static Array* get(Data& d) noexcept { return &d.array; }
785 };
786 template <> struct dynamic::GetAddrImpl<bool> {
787   static bool* get(Data& d) noexcept { return &d.boolean; }
788 };
789 template <> struct dynamic::GetAddrImpl<int64_t> {
790   static int64_t* get(Data& d) noexcept { return &d.integer; }
791 };
792 template <> struct dynamic::GetAddrImpl<double> {
793   static double* get(Data& d) noexcept { return &d.doubl; }
794 };
795 template <>
796 struct dynamic::GetAddrImpl<std::string> {
797   static std::string* get(Data& d) noexcept {
798     return &d.string;
799   }
800 };
801 template <> struct dynamic::GetAddrImpl<dynamic::ObjectImpl> {
802   static_assert(sizeof(ObjectImpl) <= sizeof(Data::objectBuffer),
803     "In your implementation, std::unordered_map<> apparently takes different"
804     " amount of space depending on its template parameters.  This is "
805     "weird.  Make objectBuffer bigger if you want to compile dynamic.");
806
807   static ObjectImpl* get(Data& d) noexcept {
808     void* data = &d.objectBuffer;
809     return static_cast<ObjectImpl*>(data);
810   }
811 };
812
813 template <class T>
814 T& dynamic::get() {
815   if (auto* p = get_nothrow<T>()) {
816     return *p;
817   }
818   throwTypeError_(TypeInfo<T>::name, type());
819 }
820
821 template <class T>
822 T const& dynamic::get() const {
823   return const_cast<dynamic*>(this)->get<T>();
824 }
825
826 //////////////////////////////////////////////////////////////////////
827
828 /*
829  * Helper for implementing operator<<.  Throws if the type shouldn't
830  * support it.
831  */
832 template <class T>
833 struct dynamic::PrintImpl {
834   static void print(dynamic const&, std::ostream& out, T const& t) {
835     out << t;
836   }
837 };
838 // Otherwise, null, being (void*)0, would print as 0.
839 template <>
840 struct dynamic::PrintImpl<std::nullptr_t> {
841   static void print(dynamic const& /* d */,
842                     std::ostream& out,
843                     std::nullptr_t const&) {
844     out << "null";
845   }
846 };
847 template <>
848 struct dynamic::PrintImpl<dynamic::ObjectImpl> {
849   static void print(dynamic const& d,
850                     std::ostream& out,
851                     dynamic::ObjectImpl const&) {
852     d.print_as_pseudo_json(out);
853   }
854 };
855 template <>
856 struct dynamic::PrintImpl<dynamic::Array> {
857   static void print(dynamic const& d,
858                     std::ostream& out,
859                     dynamic::Array const&) {
860     d.print_as_pseudo_json(out);
861   }
862 };
863
864 inline void dynamic::print(std::ostream& out) const {
865 #define FB_X(T) PrintImpl<T>::print(*this, out, *getAddress<T>())
866   FB_DYNAMIC_APPLY(type_, FB_X);
867 #undef FB_X
868 }
869
870 inline std::ostream& operator<<(std::ostream& out, dynamic const& d) {
871   d.print(out);
872   return out;
873 }
874
875 //////////////////////////////////////////////////////////////////////
876
877 // Secialization of FormatValue so dynamic objects can be formatted
878 template <>
879 class FormatValue<dynamic> {
880  public:
881   explicit FormatValue(const dynamic& val) : val_(val) { }
882
883   template <class FormatCallback>
884   void format(FormatArg& arg, FormatCallback& cb) const {
885     switch (val_.type()) {
886     case dynamic::NULLT:
887       FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
888       break;
889     case dynamic::BOOL:
890       FormatValue<bool>(val_.asBool()).format(arg, cb);
891       break;
892     case dynamic::INT64:
893       FormatValue<int64_t>(val_.asInt()).format(arg, cb);
894       break;
895     case dynamic::STRING:
896       FormatValue<std::string>(val_.asString()).format(arg, cb);
897       break;
898     case dynamic::DOUBLE:
899       FormatValue<double>(val_.asDouble()).format(arg, cb);
900       break;
901     case dynamic::ARRAY:
902       FormatValue(val_.at(arg.splitIntKey())).format(arg, cb);
903       break;
904     case dynamic::OBJECT:
905       FormatValue(val_.at(arg.splitKey().toString())).format(arg, cb);
906       break;
907     }
908   }
909
910  private:
911   const dynamic& val_;
912 };
913
914 template <class V>
915 class FormatValue<detail::DefaultValueWrapper<dynamic, V>> {
916  public:
917   explicit FormatValue(
918       const detail::DefaultValueWrapper<dynamic, V>& val)
919     : val_(val) { }
920
921   template <class FormatCallback>
922   void format(FormatArg& arg, FormatCallback& cb) const {
923     auto& c = val_.container;
924     switch (c.type()) {
925     case dynamic::NULLT:
926     case dynamic::BOOL:
927     case dynamic::INT64:
928     case dynamic::STRING:
929     case dynamic::DOUBLE:
930       FormatValue<dynamic>(c).format(arg, cb);
931       break;
932     case dynamic::ARRAY:
933       {
934         int key = arg.splitIntKey();
935         if (key >= 0 && size_t(key) < c.size()) {
936           FormatValue<dynamic>(c.at(key)).format(arg, cb);
937         } else{
938           FormatValue<V>(val_.defaultValue).format(arg, cb);
939         }
940       }
941       break;
942     case dynamic::OBJECT:
943       {
944         auto pos = c.find(arg.splitKey());
945         if (pos != c.items().end()) {
946           FormatValue<dynamic>(pos->second).format(arg, cb);
947         } else {
948           FormatValue<V>(val_.defaultValue).format(arg, cb);
949         }
950       }
951       break;
952     }
953   }
954
955  private:
956   const detail::DefaultValueWrapper<dynamic, V>& val_;
957 };
958
959 } // namespace folly
960
961 #undef FB_DYNAMIC_APPLY