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