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