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