(wangle) Fix a couple compilation issues
[folly.git] / folly / dynamic-inl.h
1 /*
2  * Copyright 2014 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 // 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 inline dynamic::ObjectMaker dynamic::object() { return ObjectMaker(); }
204 inline dynamic::ObjectMaker dynamic::object(dynamic&& a, dynamic&& b) {
205   return ObjectMaker(std::move(a), std::move(b));
206 }
207 inline dynamic::ObjectMaker dynamic::object(dynamic const& a, dynamic&& b) {
208   return ObjectMaker(a, std::move(b));
209 }
210 inline dynamic::ObjectMaker dynamic::object(dynamic&& a, dynamic const& b) {
211   return ObjectMaker(std::move(a), b);
212 }
213 inline dynamic::ObjectMaker
214 dynamic::object(dynamic const& a, dynamic const& b) {
215   return ObjectMaker(a, b);
216 }
217
218 //////////////////////////////////////////////////////////////////////
219
220 struct dynamic::const_item_iterator
221   : boost::iterator_adaptor<dynamic::const_item_iterator,
222                             dynamic::ObjectImpl::const_iterator> {
223   /* implicit */ const_item_iterator(base_type b) : iterator_adaptor_(b) { }
224
225  private:
226   friend class boost::iterator_core_access;
227 };
228
229 struct dynamic::const_key_iterator
230   : boost::iterator_adaptor<dynamic::const_key_iterator,
231                             dynamic::ObjectImpl::const_iterator,
232                             dynamic const> {
233   /* implicit */ const_key_iterator(base_type b) : iterator_adaptor_(b) { }
234
235  private:
236   dynamic const& dereference() const {
237     return base_reference()->first;
238   }
239   friend class boost::iterator_core_access;
240 };
241
242 struct dynamic::const_value_iterator
243   : boost::iterator_adaptor<dynamic::const_value_iterator,
244                             dynamic::ObjectImpl::const_iterator,
245                             dynamic const> {
246   /* implicit */ const_value_iterator(base_type b) : iterator_adaptor_(b) { }
247
248  private:
249   dynamic const& dereference() const {
250     return base_reference()->second;
251   }
252   friend class boost::iterator_core_access;
253 };
254
255 //////////////////////////////////////////////////////////////////////
256
257 inline dynamic::dynamic(ObjectMaker (*)())
258   : type_(OBJECT)
259 {
260   new (getAddress<ObjectImpl>()) ObjectImpl();
261 }
262
263 inline dynamic::dynamic(StringPiece s)
264   : type_(STRING)
265 {
266   new (&u_.string) fbstring(s.data(), s.size());
267 }
268
269 inline dynamic::dynamic(char const* s)
270   : type_(STRING)
271 {
272   new (&u_.string) fbstring(s);
273 }
274
275 inline dynamic::dynamic(std::string const& s)
276   : type_(STRING)
277 {
278   new (&u_.string) fbstring(s);
279 }
280
281 inline dynamic::dynamic(fbstring const& s)
282   : type_(STRING)
283 {
284   new (&u_.string) fbstring(s);
285 }
286
287 inline dynamic::dynamic(fbstring&& s)
288   : type_(STRING)
289 {
290   new (&u_.string) fbstring(std::move(s));
291 }
292
293 inline dynamic::dynamic(std::initializer_list<dynamic> il)
294   : type_(ARRAY)
295 {
296   new (&u_.array) Array(il.begin(), il.end());
297 }
298
299 inline dynamic::dynamic(ObjectMaker&& maker)
300   : type_(OBJECT)
301 {
302   new (getAddress<ObjectImpl>())
303     ObjectImpl(std::move(*maker.val_.getAddress<ObjectImpl>()));
304 }
305
306 inline dynamic::dynamic(dynamic const& o)
307   : type_(NULLT)
308 {
309   *this = o;
310 }
311
312 inline dynamic::dynamic(dynamic&& o)
313   : type_(NULLT)
314 {
315   *this = std::move(o);
316 }
317
318 inline dynamic::~dynamic() { destroy(); }
319
320 template<class T>
321 dynamic::dynamic(T t) {
322   typedef typename detail::ConversionHelper<T>::type U;
323   type_ = TypeInfo<U>::type;
324   new (getAddress<U>()) U(std::move(t));
325 }
326
327 template<class Iterator>
328 dynamic::dynamic(Iterator first, Iterator last)
329   : type_(ARRAY)
330 {
331   new (&u_.array) Array(first, last);
332 }
333
334 //////////////////////////////////////////////////////////////////////
335
336 inline dynamic::const_iterator dynamic::begin() const {
337   return get<Array>().begin();
338 }
339 inline dynamic::const_iterator dynamic::end() const {
340   return get<Array>().end();
341 }
342
343 template <class It>
344 struct dynamic::IterableProxy {
345   typedef It const_iterator;
346   typedef typename It::value_type value_type;
347
348   /* implicit */ IterableProxy(const dynamic::ObjectImpl* o) : o_(o) { }
349
350   It begin() const {
351     return o_->begin();
352   }
353
354   It end() const {
355     return o_->end();
356   }
357
358  private:
359   const dynamic::ObjectImpl* o_;
360 };
361
362 inline dynamic::IterableProxy<dynamic::const_key_iterator> dynamic::keys()
363   const {
364   return &(get<ObjectImpl>());
365 }
366
367 inline dynamic::IterableProxy<dynamic::const_value_iterator> dynamic::values()
368   const {
369   return &(get<ObjectImpl>());
370 }
371
372 inline dynamic::IterableProxy<dynamic::const_item_iterator> dynamic::items()
373   const {
374   return &(get<ObjectImpl>());
375 }
376
377 inline bool dynamic::isString() const { return get_nothrow<fbstring>(); }
378 inline bool dynamic::isObject() const { return get_nothrow<ObjectImpl>(); }
379 inline bool dynamic::isBool()   const { return get_nothrow<bool>(); }
380 inline bool dynamic::isArray()  const { return get_nothrow<Array>(); }
381 inline bool dynamic::isDouble() const { return get_nothrow<double>(); }
382 inline bool dynamic::isInt()    const { return get_nothrow<int64_t>(); }
383 inline bool dynamic::isNull()   const { return get_nothrow<void*>(); }
384 inline bool dynamic::isNumber() const { return isInt() || isDouble(); }
385
386 inline dynamic::Type dynamic::type() const {
387   return type_;
388 }
389
390 inline fbstring dynamic::asString() const { return asImpl<fbstring>(); }
391 inline double   dynamic::asDouble() const { return asImpl<double>(); }
392 inline int64_t  dynamic::asInt()    const { return asImpl<int64_t>(); }
393 inline bool     dynamic::asBool()   const { return asImpl<bool>(); }
394
395 inline const fbstring& dynamic::getString() const { return get<fbstring>(); }
396 inline double          dynamic::getDouble() const { return get<double>(); }
397 inline int64_t         dynamic::getInt()    const { return get<int64_t>(); }
398 inline bool            dynamic::getBool()   const { return get<bool>(); }
399
400 inline fbstring& dynamic::getString() { return get<fbstring>(); }
401 inline double&   dynamic::getDouble() { return get<double>(); }
402 inline int64_t&  dynamic::getInt()    { return get<int64_t>(); }
403 inline bool&     dynamic::getBool()   { return get<bool>(); }
404
405 inline const char* dynamic::data()  const { return get<fbstring>().data();  }
406 inline const char* dynamic::c_str() const { return get<fbstring>().c_str(); }
407 inline StringPiece dynamic::stringPiece() const { return get<fbstring>(); }
408
409 template<class T>
410 struct dynamic::CompareOp {
411   static bool comp(T const& a, T const& b) { return a < b; }
412 };
413 template<>
414 struct dynamic::CompareOp<dynamic::ObjectImpl> {
415   static bool comp(ObjectImpl const& a, ObjectImpl const& b) {
416     // This code never executes; it is just here for the compiler.
417     return false;
418   }
419 };
420
421 inline bool dynamic::operator<(dynamic const& o) const {
422   if (UNLIKELY(type_ == OBJECT || o.type_ == OBJECT)) {
423     throw TypeError("object", type_);
424   }
425   if (type_ != o.type_) {
426     return type_ < o.type_;
427   }
428
429 #define FB_X(T) return CompareOp<T>::comp(*getAddress<T>(),   \
430                                           *o.getAddress<T>())
431   FB_DYNAMIC_APPLY(type_, FB_X);
432 #undef FB_X
433 }
434
435 inline bool dynamic::operator==(dynamic const& o) const {
436   if (type() != o.type()) {
437     if (isNumber() && o.isNumber()) {
438       auto& integ = isInt() ? *this : o;
439       auto& doubl = isInt() ? o     : *this;
440       return integ.asInt() == doubl.asDouble();
441     }
442     return false;
443   }
444
445 #define FB_X(T) return *getAddress<T>() == *o.getAddress<T>();
446   FB_DYNAMIC_APPLY(type_, FB_X);
447 #undef FB_X
448 }
449
450 inline dynamic& dynamic::operator+=(dynamic const& o) {
451   if (type() == STRING && o.type() == STRING) {
452     *getAddress<fbstring>() += *o.getAddress<fbstring>();
453     return *this;
454   }
455   *this = detail::numericOp<std::plus>(*this, o);
456   return *this;
457 }
458
459 inline dynamic& dynamic::operator-=(dynamic const& o) {
460   *this = detail::numericOp<std::minus>(*this, o);
461   return *this;
462 }
463
464 inline dynamic& dynamic::operator*=(dynamic const& o) {
465   *this = detail::numericOp<std::multiplies>(*this, o);
466   return *this;
467 }
468
469 inline dynamic& dynamic::operator/=(dynamic const& o) {
470   *this = detail::numericOp<std::divides>(*this, o);
471   return *this;
472 }
473
474 #define FB_DYNAMIC_INTEGER_OP(op)                           \
475   inline dynamic& dynamic::operator op(dynamic const& o) {  \
476     if (!isInt() || !o.isInt()) {                           \
477       throw TypeError("int64", type(), o.type());           \
478     }                                                       \
479     *getAddress<int64_t>() op o.asInt();                    \
480     return *this;                                           \
481   }
482
483 FB_DYNAMIC_INTEGER_OP(%=)
484 FB_DYNAMIC_INTEGER_OP(|=)
485 FB_DYNAMIC_INTEGER_OP(&=)
486 FB_DYNAMIC_INTEGER_OP(^=)
487
488 #undef FB_DYNAMIC_INTEGER_OP
489
490 inline dynamic& dynamic::operator++() {
491   ++get<int64_t>();
492   return *this;
493 }
494
495 inline dynamic& dynamic::operator--() {
496   --get<int64_t>();
497   return *this;
498 }
499
500 inline dynamic& dynamic::operator=(dynamic const& o) {
501   if (&o != this) {
502     destroy();
503 #define FB_X(T) new (getAddress<T>()) T(*o.getAddress<T>())
504     FB_DYNAMIC_APPLY(o.type_, FB_X);
505 #undef FB_X
506     type_ = o.type_;
507   }
508   return *this;
509 }
510
511 inline dynamic& dynamic::operator=(dynamic&& o) {
512   if (&o != this) {
513     destroy();
514 #define FB_X(T) new (getAddress<T>()) T(std::move(*o.getAddress<T>()))
515     FB_DYNAMIC_APPLY(o.type_, FB_X);
516 #undef FB_X
517     type_ = o.type_;
518   }
519   return *this;
520 }
521
522 inline dynamic& dynamic::operator[](dynamic const& k) {
523   if (!isObject() && !isArray()) {
524     throw TypeError("object/array", type());
525   }
526   if (isArray()) {
527     return at(k);
528   }
529   auto& obj = get<ObjectImpl>();
530   auto ret = obj.insert({k, nullptr});
531   return ret.first->second;
532 }
533
534 inline dynamic const& dynamic::operator[](dynamic const& idx) const {
535   return at(idx);
536 }
537
538 inline dynamic dynamic::getDefault(const dynamic& k, const dynamic& v) const {
539   auto& obj = get<ObjectImpl>();
540   auto it = obj.find(k);
541   return it == obj.end() ? v : it->second;
542 }
543
544 inline dynamic&& dynamic::getDefault(const dynamic& k, dynamic&& v) const {
545   auto& obj = get<ObjectImpl>();
546   auto it = obj.find(k);
547   if (it != obj.end()) {
548     v = it->second;
549   }
550
551   return std::move(v);
552 }
553
554 template<class K, class V> inline dynamic& dynamic::setDefault(K&& k, V&& v) {
555   auto& obj = get<ObjectImpl>();
556   return obj.insert(std::make_pair(std::forward<K>(k),
557                                    std::forward<V>(v))).first->second;
558 }
559
560 inline dynamic* dynamic::get_ptr(dynamic const& idx) {
561   return const_cast<dynamic*>(const_cast<dynamic const*>(this)->get_ptr(idx));
562 }
563
564 inline const dynamic* dynamic::get_ptr(dynamic const& idx) const {
565   if (auto* parray = get_nothrow<Array>()) {
566     if (!idx.isInt()) {
567       throw TypeError("int64", idx.type());
568     }
569     if (idx >= parray->size()) {
570       return nullptr;
571     }
572     return &(*parray)[idx.asInt()];
573   } else if (auto* pobject = get_nothrow<ObjectImpl>()) {
574     auto it = pobject->find(idx);
575     if (it == pobject->end()) {
576       return nullptr;
577     }
578     return &it->second;
579   } else {
580     throw TypeError("object/array", type());
581   }
582 }
583
584 inline dynamic& dynamic::at(dynamic const& idx) {
585   return const_cast<dynamic&>(const_cast<dynamic const*>(this)->at(idx));
586 }
587
588 inline dynamic const& dynamic::at(dynamic const& idx) const {
589   if (auto* parray = get_nothrow<Array>()) {
590     if (!idx.isInt()) {
591       throw TypeError("int64", idx.type());
592     }
593     if (idx >= parray->size()) {
594       throw std::out_of_range("out of range in dynamic array");
595     }
596     return (*parray)[idx.asInt()];
597   } else if (auto* pobject = get_nothrow<ObjectImpl>()) {
598     auto it = pobject->find(idx);
599     if (it == pobject->end()) {
600       throw std::out_of_range(to<std::string>(
601           "couldn't find key ", idx.asString(), " in dynamic object"));
602     }
603     return it->second;
604   } else {
605     throw TypeError("object/array", type());
606   }
607 }
608
609 inline bool dynamic::empty() const {
610   if (isNull()) {
611     return true;
612   }
613   return !size();
614 }
615
616 inline std::size_t dynamic::size() const {
617   if (auto* ar = get_nothrow<Array>()) {
618     return ar->size();
619   }
620   if (auto* obj = get_nothrow<ObjectImpl>()) {
621     return obj->size();
622   }
623   if (auto* str = get_nothrow<fbstring>()) {
624     return str->size();
625   }
626   throw TypeError("array/object", type());
627 }
628
629 inline std::size_t dynamic::count(dynamic const& key) const {
630   return find(key) != items().end();
631 }
632
633 inline dynamic::const_item_iterator dynamic::find(dynamic const& key) const {
634   return get<ObjectImpl>().find(key);
635 }
636
637 template<class K, class V> inline void dynamic::insert(K&& key, V&& val) {
638   auto& obj = get<ObjectImpl>();
639   auto rv = obj.insert(std::make_pair(std::forward<K>(key),
640                                       std::forward<V>(val)));
641   if (!rv.second) {
642     // note, the second use of std:forward<V>(val) is only correct
643     // if the first one did not result in a move. obj[key] = val
644     // would be preferrable but doesn't compile because dynamic
645     // is (intentionally) not default constructable
646     rv.first->second = std::forward<V>(val);
647   }
648 }
649
650 inline std::size_t dynamic::erase(dynamic const& key) {
651   auto& obj = get<ObjectImpl>();
652   return obj.erase(key);
653 }
654
655 inline dynamic::const_iterator dynamic::erase(const_iterator it) {
656   auto& arr = get<Array>();
657   // std::vector doesn't have an erase method that works on const iterators,
658   // even though the standard says it should, so this hack converts to a
659   // non-const iterator before calling erase.
660   return get<Array>().erase(arr.begin() + (it - arr.begin()));
661 }
662
663 inline dynamic::const_iterator
664 dynamic::erase(const_iterator first, const_iterator last) {
665   auto& arr = get<Array>();
666   return get<Array>().erase(
667     arr.begin() + (first - arr.begin()),
668     arr.begin() + (last - arr.begin()));
669 }
670
671 inline dynamic::const_key_iterator dynamic::erase(const_key_iterator it) {
672   return const_key_iterator(get<ObjectImpl>().erase(it.base()));
673 }
674
675 inline dynamic::const_key_iterator dynamic::erase(const_key_iterator first,
676                                                   const_key_iterator last) {
677   return const_key_iterator(get<ObjectImpl>().erase(first.base(),
678                                                     last.base()));
679 }
680
681 inline dynamic::const_value_iterator dynamic::erase(const_value_iterator it) {
682   return const_value_iterator(get<ObjectImpl>().erase(it.base()));
683 }
684
685 inline dynamic::const_value_iterator dynamic::erase(const_value_iterator first,
686                                                     const_value_iterator last) {
687   return const_value_iterator(get<ObjectImpl>().erase(first.base(),
688                                                       last.base()));
689 }
690
691 inline dynamic::const_item_iterator dynamic::erase(const_item_iterator it) {
692   return const_item_iterator(get<ObjectImpl>().erase(it.base()));
693 }
694
695 inline dynamic::const_item_iterator dynamic::erase(const_item_iterator first,
696                                                    const_item_iterator last) {
697   return const_item_iterator(get<ObjectImpl>().erase(first.base(),
698                                                      last.base()));
699 }
700
701 inline void dynamic::resize(std::size_t sz, dynamic const& c) {
702   auto& array = get<Array>();
703   array.resize(sz, c);
704 }
705
706 inline void dynamic::push_back(dynamic const& v) {
707   auto& array = get<Array>();
708   array.push_back(v);
709 }
710
711 inline void dynamic::push_back(dynamic&& v) {
712   auto& array = get<Array>();
713   array.push_back(std::move(v));
714 }
715
716 inline void dynamic::pop_back() {
717   auto& array = get<Array>();
718   array.pop_back();
719 }
720
721 inline std::size_t dynamic::hash() const {
722   switch (type()) {
723   case OBJECT:
724   case ARRAY:
725   case NULLT:
726     throw TypeError("not null/object/array", type());
727   case INT64:
728     return std::hash<int64_t>()(asInt());
729   case DOUBLE:
730     return std::hash<double>()(asDouble());
731   case BOOL:
732     return std::hash<bool>()(asBool());
733   case STRING:
734     return std::hash<fbstring>()(asString());
735   default:
736     CHECK(0); abort();
737   }
738 }
739
740 //////////////////////////////////////////////////////////////////////
741
742 template<class T> struct dynamic::TypeInfo {
743   static char const name[];
744   static Type const type;
745 };
746
747 #define FB_DEC_TYPE(T)                                      \
748   template<> char const dynamic::TypeInfo<T>::name[];       \
749   template<> dynamic::Type const dynamic::TypeInfo<T>::type
750
751 FB_DEC_TYPE(void*);
752 FB_DEC_TYPE(bool);
753 FB_DEC_TYPE(fbstring);
754 FB_DEC_TYPE(dynamic::Array);
755 FB_DEC_TYPE(double);
756 FB_DEC_TYPE(int64_t);
757 FB_DEC_TYPE(dynamic::ObjectImpl);
758
759 #undef FB_DEC_TYPE
760
761 template<class T>
762 T dynamic::asImpl() const {
763   switch (type()) {
764   case INT64:    return to<T>(*get_nothrow<int64_t>());
765   case DOUBLE:   return to<T>(*get_nothrow<double>());
766   case BOOL:     return to<T>(*get_nothrow<bool>());
767   case STRING:   return to<T>(*get_nothrow<fbstring>());
768   default:
769     throw TypeError("int/double/bool/string", type());
770   }
771 }
772
773 // Return a T* to our type, or null if we're not that type.
774 template<class T>
775 T* dynamic::get_nothrow() {
776   if (type_ != TypeInfo<T>::type) {
777     return nullptr;
778   }
779   return getAddress<T>();
780 }
781
782 template<class T>
783 T const* dynamic::get_nothrow() const {
784   return const_cast<dynamic*>(this)->get_nothrow<T>();
785 }
786
787 // Return T* for where we can put a T, without type checking.  (Memory
788 // might be uninitialized, even.)
789 template<class T>
790 T* dynamic::getAddress() {
791   return GetAddrImpl<T>::get(u_);
792 }
793
794 template<class T>
795 T const* dynamic::getAddress() const {
796   return const_cast<dynamic*>(this)->getAddress<T>();
797 }
798
799 template<class T> struct dynamic::GetAddrImpl {};
800 template<> struct dynamic::GetAddrImpl<void*> {
801   static void** get(Data& d) { return &d.nul; }
802 };
803 template<> struct dynamic::GetAddrImpl<dynamic::Array> {
804   static Array* get(Data& d) { return &d.array; }
805 };
806 template<> struct dynamic::GetAddrImpl<bool> {
807   static bool* get(Data& d) { return &d.boolean; }
808 };
809 template<> struct dynamic::GetAddrImpl<int64_t> {
810   static int64_t* get(Data& d) { return &d.integer; }
811 };
812 template<> struct dynamic::GetAddrImpl<double> {
813   static double* get(Data& d) { return &d.doubl; }
814 };
815 template<> struct dynamic::GetAddrImpl<fbstring> {
816   static fbstring* get(Data& d) { return &d.string; }
817 };
818 template<> struct dynamic::GetAddrImpl<dynamic::ObjectImpl> {
819   static_assert(sizeof(ObjectImpl) <= sizeof(Data::objectBuffer),
820     "In your implementation, std::unordered_map<> apparently takes different"
821     " amount of space depending on its template parameters.  This is "
822     "weird.  Make objectBuffer bigger if you want to compile dynamic.");
823
824   static ObjectImpl* get(Data& d) {
825     void* data = &d.objectBuffer;
826     return static_cast<ObjectImpl*>(data);
827   }
828 };
829
830 template<class T>
831 T& dynamic::get() {
832   if (auto* p = get_nothrow<T>()) {
833     return *p;
834   }
835   throw TypeError(TypeInfo<T>::name, type());
836 }
837
838 template<class T>
839 T const& dynamic::get() const {
840   return const_cast<dynamic*>(this)->get<T>();
841 }
842
843 inline char const* dynamic::typeName(Type t) {
844 #define FB_X(T) return TypeInfo<T>::name
845   FB_DYNAMIC_APPLY(t, FB_X);
846 #undef FB_X
847 }
848
849 inline void dynamic::destroy() {
850   // This short-circuit speeds up some microbenchmarks.
851   if (type_ == NULLT) return;
852
853 #define FB_X(T) detail::Destroy::destroy(getAddress<T>())
854   FB_DYNAMIC_APPLY(type_, FB_X);
855 #undef FB_X
856   type_ = NULLT;
857   u_.nul = nullptr;
858 }
859
860 //////////////////////////////////////////////////////////////////////
861
862 /*
863  * Helper for implementing operator<<.  Throws if the type shouldn't
864  * support it.
865  */
866 template<class T>
867 struct dynamic::PrintImpl {
868   static void print(dynamic const&, std::ostream& out, T const& t) {
869     out << t;
870   }
871 };
872 template<>
873 struct dynamic::PrintImpl<dynamic::ObjectImpl> {
874   static void print(dynamic const& d,
875                     std::ostream& out,
876                     dynamic::ObjectImpl const&) {
877     d.print_as_pseudo_json(out);
878   }
879 };
880 template<>
881 struct dynamic::PrintImpl<dynamic::Array> {
882   static void print(dynamic const& d,
883                     std::ostream& out,
884                     dynamic::Array const&) {
885     d.print_as_pseudo_json(out);
886   }
887 };
888
889 inline void dynamic::print(std::ostream& out) const {
890 #define FB_X(T) PrintImpl<T>::print(*this, out, *getAddress<T>())
891   FB_DYNAMIC_APPLY(type_, FB_X);
892 #undef FB_X
893 }
894
895 inline std::ostream& operator<<(std::ostream& out, dynamic const& d) {
896   d.print(out);
897   return out;
898 }
899
900 //////////////////////////////////////////////////////////////////////
901
902 // Secialization of FormatValue so dynamic objects can be formatted
903 template <>
904 class FormatValue<dynamic> {
905  public:
906   explicit FormatValue(const dynamic& val) : val_(val) { }
907
908   template <class FormatCallback>
909   void format(FormatArg& arg, FormatCallback& cb) const {
910     switch (val_.type()) {
911     case dynamic::NULLT:
912       FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
913       break;
914     case dynamic::BOOL:
915       FormatValue<bool>(val_.asBool()).format(arg, cb);
916       break;
917     case dynamic::INT64:
918       FormatValue<int64_t>(val_.asInt()).format(arg, cb);
919       break;
920     case dynamic::STRING:
921       FormatValue<fbstring>(val_.asString()).format(arg, cb);
922       break;
923     case dynamic::DOUBLE:
924       FormatValue<double>(val_.asDouble()).format(arg, cb);
925       break;
926     case dynamic::ARRAY:
927       FormatValue(val_.at(arg.splitIntKey())).format(arg, cb);
928       break;
929     case dynamic::OBJECT:
930       FormatValue(val_.at(arg.splitKey().toFbstring())).format(arg, cb);
931       break;
932     }
933   }
934
935  private:
936   const dynamic& val_;
937 };
938
939 template <class V>
940 class FormatValue<detail::DefaultValueWrapper<dynamic, V>> {
941  public:
942   explicit FormatValue(
943       const detail::DefaultValueWrapper<dynamic, V>& val)
944     : val_(val) { }
945
946   template <class FormatCallback>
947   void format(FormatArg& arg, FormatCallback& cb) const {
948     auto& c = val_.container;
949     switch (c.type()) {
950     case dynamic::NULLT:
951     case dynamic::BOOL:
952     case dynamic::INT64:
953     case dynamic::STRING:
954     case dynamic::DOUBLE:
955       FormatValue<dynamic>(c).format(arg, cb);
956       break;
957     case dynamic::ARRAY:
958       {
959         int key = arg.splitIntKey();
960         if (key >= 0 && key < c.size()) {
961           FormatValue<dynamic>(c.at(key)).format(arg, cb);
962         } else{
963           FormatValue<V>(val_.defaultValue).format(arg, cb);
964         }
965       }
966       break;
967     case dynamic::OBJECT:
968       {
969         auto pos = c.find(arg.splitKey());
970         if (pos != c.items().end()) {
971           FormatValue<dynamic>(pos->second).format(arg, cb);
972         } else {
973           FormatValue<V>(val_.defaultValue).format(arg, cb);
974         }
975       }
976       break;
977     }
978   }
979
980  private:
981   const detail::DefaultValueWrapper<dynamic, V>& val_;
982 };
983
984 }  // namespaces
985
986 #undef FB_DYNAMIC_APPLY
987
988 #endif