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