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