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