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