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