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