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