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