2 * Copyright 2012 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef FOLLY_DYNAMIC_INL_H_
18 #define FOLLY_DYNAMIC_INL_H_
21 #include <boost/iterator/iterator_adaptor.hpp>
22 #include <boost/iterator/iterator_facade.hpp>
23 #include "folly/Likely.h"
24 #include "folly/Conv.h"
25 #include "folly/Format.h"
27 //////////////////////////////////////////////////////////////////////
32 struct hash< ::folly::dynamic> {
33 size_t operator()(::folly::dynamic const& d) const {
40 //////////////////////////////////////////////////////////////////////
42 // This is a higher-order preprocessor macro to aid going from runtime
43 // types to the compile time type system.
44 #define FB_DYNAMIC_APPLY(type, apply) do { \
46 case NULLT: apply(void*); break; \
47 case ARRAY: apply(Array); break; \
48 case BOOL: apply(bool); break; \
49 case DOUBLE: apply(double); break; \
50 case INT64: apply(int64_t); break; \
51 case OBJECT: apply(ObjectImpl); break; \
52 case STRING: apply(fbstring); break; \
53 default: CHECK(0); abort(); \
57 //////////////////////////////////////////////////////////////////////
61 //////////////////////////////////////////////////////////////////////
65 // This helper is used in destroy() to be able to run destructors on
66 // types like "int64_t" without a compiler error.
68 template<class T> static void destroy(T* t) { t->~T(); }
72 * The enable_if junk here is necessary to avoid ambiguous
73 * conversions relating to bool and double when you implicitly
74 * convert an int or long to a dynamic.
76 template<class T, class Enable = void> struct ConversionHelper;
78 struct ConversionHelper<
80 typename std::enable_if<
81 std::is_integral<T>::value && !std::is_same<T,bool>::value
87 struct ConversionHelper<
89 typename std::enable_if<
90 (!std::is_integral<T>::value || std::is_same<T,bool>::value) &&
91 !std::is_same<T,std::nullptr_t>::value
97 struct ConversionHelper<
99 typename std::enable_if<
100 std::is_same<T,std::nullptr_t>::value
107 * Helper for implementing numeric conversions in operators on
108 * numbers. Just promotes to double when one of the arguments is
109 * double, or throws if either is not a numeric type.
111 template<template<class> class Op>
112 dynamic numericOp(dynamic const& a, dynamic const& b) {
113 if (!a.isNumber() || !b.isNumber()) {
114 throw TypeError("numeric", a.type(), b.type());
116 if (a.type() != b.type()) {
117 auto& integ = a.isInt() ? a : b;
118 auto& nonint = a.isInt() ? b : a;
119 return Op<double>()(to<double>(integ.asInt()), nonint.asDouble());
122 return Op<double>()(a.asDouble(), b.asDouble());
124 return Op<int64_t>()(a.asInt(), b.asInt());
129 //////////////////////////////////////////////////////////////////////
131 struct TypeError : std::runtime_error {
132 explicit TypeError(const std::string& expected, dynamic::Type actual)
133 : std::runtime_error(to<std::string>("TypeError: expected dynamic "
134 "type `", expected, '\'', ", but had type `",
135 dynamic::typeName(actual), '\''))
137 explicit TypeError(const std::string& expected,
138 dynamic::Type actual1, dynamic::Type actual2)
139 : std::runtime_error(to<std::string>("TypeError: expected dynamic "
140 "types `", expected, '\'', ", but had types `",
141 dynamic::typeName(actual1), "' and `", dynamic::typeName(actual2),
147 * We're doing this instead of a simple member typedef to avoid the
148 * undefined behavior of parameterizing std::unordered_map<> with an
151 * Note: Later we may add separate order tracking here (a multi-index
154 struct dynamic::ObjectImpl : std::unordered_map<dynamic, dynamic> {};
156 //////////////////////////////////////////////////////////////////////
158 // Helper object for creating objects conveniently. See object and
159 // the dynamic::dynamic(ObjectMaker&&) ctor.
160 struct dynamic::ObjectMaker {
161 friend struct dynamic;
163 explicit ObjectMaker() : val_(dynamic::object) {}
164 explicit ObjectMaker(dynamic const& key, dynamic val)
165 : val_(dynamic::object)
167 val_.insert(key, std::move(val));
169 explicit ObjectMaker(dynamic&& key, dynamic val)
170 : val_(dynamic::object)
172 val_.insert(std::move(key), std::move(val));
175 // Make sure no one tries to save one of these into an lvalue with
176 // auto or anything like that.
177 ObjectMaker(ObjectMaker&&) = default;
178 ObjectMaker(ObjectMaker const&) = delete;
179 ObjectMaker& operator=(ObjectMaker const&) = delete;
180 ObjectMaker& operator=(ObjectMaker&&) = delete;
182 // These return rvalue-references instead of lvalue-references to allow
183 // constructs like this to moved instead of copied:
184 // dynamic a = dynamic::object("a", "b")("c", "d")
185 ObjectMaker&& operator()(dynamic const& key, dynamic val) {
186 val_.insert(key, std::move(val));
187 return std::move(*this);
190 ObjectMaker&& operator()(dynamic&& key, dynamic val) {
191 val_.insert(std::move(key), std::move(val));
192 return std::move(*this);
199 template<class... Args>
200 inline dynamic::ObjectMaker dynamic::object(Args&&... args) {
201 return dynamic::ObjectMaker(std::forward<Args>(args)...);
204 //////////////////////////////////////////////////////////////////////
206 struct dynamic::const_item_iterator
207 : boost::iterator_adaptor<dynamic::const_item_iterator,
208 dynamic::ObjectImpl::const_iterator> {
209 /* implicit */ const_item_iterator(base_type b) : iterator_adaptor_(b) { }
212 friend class boost::iterator_core_access;
215 struct dynamic::const_key_iterator
216 : boost::iterator_adaptor<dynamic::const_key_iterator,
217 dynamic::ObjectImpl::const_iterator,
219 /* implicit */ const_key_iterator(base_type b) : iterator_adaptor_(b) { }
222 dynamic const& dereference() const {
223 return base_reference()->first;
225 friend class boost::iterator_core_access;
228 struct dynamic::const_value_iterator
229 : boost::iterator_adaptor<dynamic::const_value_iterator,
230 dynamic::ObjectImpl::const_iterator,
232 /* implicit */ const_value_iterator(base_type b) : iterator_adaptor_(b) { }
235 dynamic const& dereference() const {
236 return base_reference()->second;
238 friend class boost::iterator_core_access;
241 //////////////////////////////////////////////////////////////////////
243 inline dynamic::dynamic(ObjectMaker (*)())
246 new (getAddress<ObjectImpl>()) ObjectImpl();
249 inline dynamic::dynamic(char const* s)
252 new (&u_.string) fbstring(s);
255 inline dynamic::dynamic(std::string const& s)
258 new (&u_.string) fbstring(s);
261 inline dynamic::dynamic(std::initializer_list<dynamic> il)
264 new (&u_.array) Array(il.begin(), il.end());
267 inline dynamic::dynamic(ObjectMaker&& maker)
270 new (getAddress<ObjectImpl>())
271 ObjectImpl(std::move(*maker.val_.getAddress<ObjectImpl>()));
274 inline dynamic::dynamic(dynamic const& o)
280 inline dynamic::dynamic(dynamic&& o)
283 *this = std::move(o);
286 inline dynamic::~dynamic() { destroy(); }
289 dynamic::dynamic(T t) {
290 typedef typename detail::ConversionHelper<T>::type U;
291 type_ = TypeInfo<U>::type;
292 new (getAddress<U>()) U(std::move(t));
295 template<class Iterator>
296 dynamic::dynamic(Iterator first, Iterator last)
299 new (&u_.array) Array(first, last);
302 //////////////////////////////////////////////////////////////////////
304 inline dynamic::const_iterator dynamic::begin() const {
305 return get<Array>().begin();
307 inline dynamic::const_iterator dynamic::end() const {
308 return get<Array>().end();
312 struct dynamic::IterableProxy {
313 typedef It const_iterator;
315 /* implicit */ IterableProxy(const dynamic::ObjectImpl* o) : o_(o) { }
326 const dynamic::ObjectImpl* o_;
329 inline dynamic::IterableProxy<dynamic::const_key_iterator> dynamic::keys()
331 return &(get<ObjectImpl>());
334 inline dynamic::IterableProxy<dynamic::const_value_iterator> dynamic::values()
336 return &(get<ObjectImpl>());
339 inline dynamic::IterableProxy<dynamic::const_item_iterator> dynamic::items()
341 return &(get<ObjectImpl>());
344 inline bool dynamic::isString() const { return get_nothrow<fbstring>(); }
345 inline bool dynamic::isObject() const { return get_nothrow<ObjectImpl>(); }
346 inline bool dynamic::isBool() const { return get_nothrow<bool>(); }
347 inline bool dynamic::isArray() const { return get_nothrow<Array>(); }
348 inline bool dynamic::isDouble() const { return get_nothrow<double>(); }
349 inline bool dynamic::isInt() const { return get_nothrow<int64_t>(); }
350 inline bool dynamic::isNull() const { return get_nothrow<void*>(); }
351 inline bool dynamic::isNumber() const { return isInt() || isDouble(); }
353 inline dynamic::Type dynamic::type() const {
357 inline fbstring dynamic::asString() const { return asImpl<fbstring>(); }
358 inline double dynamic::asDouble() const { return asImpl<double>(); }
359 inline int64_t dynamic::asInt() const { return asImpl<int64_t>(); }
360 inline bool dynamic::asBool() const { return asImpl<bool>(); }
363 struct dynamic::CompareOp {
364 static bool comp(T const& a, T const& b) { return a < b; }
367 struct dynamic::CompareOp<dynamic::ObjectImpl> {
368 static bool comp(ObjectImpl const& a, ObjectImpl const& b) {
369 // This code never executes; it is just here for the compiler.
374 inline bool dynamic::operator<(dynamic const& o) const {
375 if (UNLIKELY(type_ == OBJECT || o.type_ == OBJECT)) {
376 throw TypeError("object", type_);
378 if (type_ != o.type_) {
379 return type_ < o.type_;
382 #define FB_X(T) return CompareOp<T>::comp(*getAddress<T>(), \
384 FB_DYNAMIC_APPLY(type_, FB_X);
388 inline bool dynamic::operator==(dynamic const& o) const {
389 if (type() != o.type()) {
390 if (isNumber() && o.isNumber()) {
391 auto& integ = isInt() ? *this : o;
392 auto& doubl = isInt() ? o : *this;
393 return integ.asInt() == doubl.asDouble();
398 #define FB_X(T) return *getAddress<T>() == *o.getAddress<T>();
399 FB_DYNAMIC_APPLY(type_, FB_X);
403 inline dynamic& dynamic::operator+=(dynamic const& o) {
404 if (type() == STRING && o.type() == STRING) {
405 *getAddress<fbstring>() += *o.getAddress<fbstring>();
408 *this = detail::numericOp<std::plus>(*this, o);
412 inline dynamic& dynamic::operator-=(dynamic const& o) {
413 *this = detail::numericOp<std::minus>(*this, o);
417 inline dynamic& dynamic::operator*=(dynamic const& o) {
418 *this = detail::numericOp<std::multiplies>(*this, o);
422 inline dynamic& dynamic::operator/=(dynamic const& o) {
423 *this = detail::numericOp<std::divides>(*this, o);
427 #define FB_DYNAMIC_INTEGER_OP(op) \
428 inline dynamic& dynamic::operator op(dynamic const& o) { \
429 if (!isInt() || !o.isInt()) { \
430 throw TypeError("int64", type(), o.type()); \
432 *getAddress<int64_t>() op o.asInt(); \
436 FB_DYNAMIC_INTEGER_OP(%=)
437 FB_DYNAMIC_INTEGER_OP(|=)
438 FB_DYNAMIC_INTEGER_OP(&=)
439 FB_DYNAMIC_INTEGER_OP(^=)
441 #undef FB_DYNAMIC_INTEGER_OP
443 inline dynamic& dynamic::operator++() {
448 inline dynamic& dynamic::operator--() {
453 inline dynamic& dynamic::operator=(dynamic const& o) {
456 #define FB_X(T) new (getAddress<T>()) T(*o.getAddress<T>())
457 FB_DYNAMIC_APPLY(o.type_, FB_X);
464 inline dynamic& dynamic::operator=(dynamic&& o) {
467 #define FB_X(T) new (getAddress<T>()) T(std::move(*o.getAddress<T>()))
468 FB_DYNAMIC_APPLY(o.type_, FB_X);
475 inline dynamic& dynamic::operator[](dynamic const& k) {
476 if (!isObject() && !isArray()) {
477 throw TypeError("object/array", type());
482 auto& obj = get<ObjectImpl>();
483 auto ret = obj.insert({k, nullptr});
484 return ret.first->second;
487 inline dynamic const& dynamic::operator[](dynamic const& idx) const {
491 inline dynamic dynamic::getDefault(const dynamic& k, const dynamic& v) const {
492 auto& obj = get<ObjectImpl>();
493 auto it = obj.find(k);
494 return it == obj.end() ? v : it->second;
497 inline dynamic&& dynamic::getDefault(const dynamic& k, dynamic&& v) const {
498 auto& obj = get<ObjectImpl>();
499 auto it = obj.find(k);
500 if (it != obj.end()) {
507 template<class K, class V> inline dynamic& dynamic::setDefault(K&& k, V&& v) {
508 auto& obj = get<ObjectImpl>();
509 return obj.insert(std::make_pair(std::forward<K>(k),
510 std::forward<V>(v))).first->second;
513 inline dynamic const& dynamic::at(dynamic const& idx) const {
514 return const_cast<dynamic*>(this)->at(idx);
517 inline dynamic& dynamic::at(dynamic const& idx) {
518 if (!isObject() && !isArray()) {
519 throw TypeError("object/array", type());
522 if (auto* parray = get_nothrow<Array>()) {
523 if (idx >= parray->size()) {
524 throw std::out_of_range("out of range in dynamic array");
527 throw TypeError("int64", idx.type());
529 return (*parray)[idx.asInt()];
532 auto* pobj = get_nothrow<ObjectImpl>();
535 if (it == items().end()) {
536 throw std::out_of_range(to<std::string>(
537 "couldn't find key ", idx.asString(), " in dynamic object"));
539 return const_cast<dynamic&>(it->second);
542 inline bool dynamic::empty() const {
549 inline std::size_t dynamic::size() const {
550 if (auto* ar = get_nothrow<Array>()) {
553 if (auto* obj = get_nothrow<ObjectImpl>()) {
556 if (auto* str = get_nothrow<fbstring>()) {
559 throw TypeError("array/object", type());
562 inline std::size_t dynamic::count(dynamic const& key) const {
563 return find(key) != items().end();
566 inline dynamic::const_item_iterator dynamic::find(dynamic const& key) const {
567 return get<ObjectImpl>().find(key);
570 template<class K, class V> inline void dynamic::insert(K&& key, V&& val) {
571 auto& obj = get<ObjectImpl>();
572 auto rv = obj.insert(std::make_pair(std::forward<K>(key),
573 std::forward<V>(val)));
575 // note, the second use of std:forward<V>(val) is only correct
576 // if the first one did not result in a move. obj[key] = val
577 // would be preferrable but doesn't compile because dynamic
578 // is (intentionally) not default constructable
579 rv.first->second = std::forward<V>(val);
583 inline std::size_t dynamic::erase(dynamic const& key) {
584 auto& obj = get<ObjectImpl>();
585 return obj.erase(key);
588 inline dynamic::const_iterator dynamic::erase(const_iterator it) {
589 auto& arr = get<Array>();
590 return get<Array>().erase(arr.begin() + (it - arr.begin()));
593 inline dynamic::const_iterator
594 dynamic::erase(const_iterator first, const_iterator last) {
595 auto& arr = get<Array>();
596 return get<Array>().erase(
597 arr.begin() + (first - arr.begin()),
598 arr.begin() + (last - arr.begin()));
601 inline dynamic::const_key_iterator dynamic::erase(const_key_iterator it) {
602 return const_key_iterator(get<ObjectImpl>().erase(it.base()));
605 inline dynamic::const_key_iterator dynamic::erase(const_key_iterator first,
606 const_key_iterator last) {
607 return const_key_iterator(get<ObjectImpl>().erase(first.base(),
611 inline dynamic::const_value_iterator dynamic::erase(const_value_iterator it) {
612 return const_value_iterator(get<ObjectImpl>().erase(it.base()));
615 inline dynamic::const_value_iterator dynamic::erase(const_value_iterator first,
616 const_value_iterator last) {
617 return const_value_iterator(get<ObjectImpl>().erase(first.base(),
621 inline dynamic::const_item_iterator dynamic::erase(const_item_iterator it) {
622 return const_item_iterator(get<ObjectImpl>().erase(it.base()));
625 inline dynamic::const_item_iterator dynamic::erase(const_item_iterator first,
626 const_item_iterator last) {
627 return const_item_iterator(get<ObjectImpl>().erase(first.base(),
631 inline void dynamic::resize(std::size_t sz, dynamic const& c) {
632 auto& array = get<Array>();
636 inline void dynamic::push_back(dynamic const& v) {
637 auto& array = get<Array>();
641 inline void dynamic::push_back(dynamic&& v) {
642 auto& array = get<Array>();
643 array.push_back(std::move(v));
646 inline std::size_t dynamic::hash() const {
651 throw TypeError("not null/object/array", type());
653 return std::hash<int64_t>()(asInt());
655 return std::hash<double>()(asDouble());
657 return std::hash<bool>()(asBool());
659 return std::hash<fbstring>()(asString());
665 //////////////////////////////////////////////////////////////////////
667 template<class T> struct dynamic::TypeInfo {
668 static char const name[];
669 static Type const type;
673 T dynamic::asImpl() const {
675 case INT64: return to<T>(*get_nothrow<int64_t>());
676 case DOUBLE: return to<T>(*get_nothrow<double>());
677 case BOOL: return to<T>(*get_nothrow<bool>());
678 case STRING: return to<T>(*get_nothrow<fbstring>());
680 throw TypeError("int/double/bool/string", type());
684 // Return a T* to our type, or null if we're not that type.
686 T* dynamic::get_nothrow() {
687 if (type_ != TypeInfo<T>::type) {
690 return getAddress<T>();
694 T const* dynamic::get_nothrow() const {
695 return const_cast<dynamic*>(this)->get_nothrow<T>();
698 // Return T* for where we can put a T, without type checking. (Memory
699 // might be uninitialized, even.)
701 T* dynamic::getAddress() {
702 return GetAddrImpl<T>::get(u_);
706 T const* dynamic::getAddress() const {
707 return const_cast<dynamic*>(this)->getAddress<T>();
710 template<class T> struct dynamic::GetAddrImpl {};
711 template<> struct dynamic::GetAddrImpl<void*> {
712 static void** get(Data& d) { return &d.nul; }
714 template<> struct dynamic::GetAddrImpl<dynamic::Array> {
715 static Array* get(Data& d) { return &d.array; }
717 template<> struct dynamic::GetAddrImpl<bool> {
718 static bool* get(Data& d) { return &d.boolean; }
720 template<> struct dynamic::GetAddrImpl<int64_t> {
721 static int64_t* get(Data& d) { return &d.integer; }
723 template<> struct dynamic::GetAddrImpl<double> {
724 static double* get(Data& d) { return &d.doubl; }
726 template<> struct dynamic::GetAddrImpl<fbstring> {
727 static fbstring* get(Data& d) { return &d.string; }
729 template<> struct dynamic::GetAddrImpl<dynamic::ObjectImpl> {
730 static_assert(sizeof(ObjectImpl) <= sizeof(Data::objectBuffer),
731 "In your implementation, std::unordered_map<> apparently takes different"
732 " amount of space depending on its template parameters. This is "
733 "weird. Make objectBuffer bigger if you want to compile dynamic.");
735 static ObjectImpl* get(Data& d) {
736 void* data = &d.objectBuffer;
737 return static_cast<ObjectImpl*>(data);
743 if (auto* p = get_nothrow<T>()) {
746 throw TypeError(TypeInfo<T>::name, type());
750 T const& dynamic::get() const {
751 return const_cast<dynamic*>(this)->get<T>();
754 inline char const* dynamic::typeName(Type t) {
755 #define FB_X(T) return TypeInfo<T>::name
756 FB_DYNAMIC_APPLY(t, FB_X);
760 inline void dynamic::destroy() {
761 // This short-circuit speeds up some microbenchmarks.
762 if (type_ == NULLT) return;
764 #define FB_X(T) detail::Destroy::destroy(getAddress<T>())
765 FB_DYNAMIC_APPLY(type_, FB_X);
771 //////////////////////////////////////////////////////////////////////
774 * Helper for implementing operator<<. Throws if the type shouldn't
778 struct dynamic::PrintImpl {
779 static void print(dynamic const&, std::ostream& out, T const& t) {
784 struct dynamic::PrintImpl<dynamic::ObjectImpl> {
785 static void print(dynamic const& d,
787 dynamic::ObjectImpl const&) {
788 d.print_as_pseudo_json(out);
792 struct dynamic::PrintImpl<dynamic::Array> {
793 static void print(dynamic const& d,
795 dynamic::Array const&) {
796 d.print_as_pseudo_json(out);
800 inline void dynamic::print(std::ostream& out) const {
801 #define FB_X(T) PrintImpl<T>::print(*this, out, *getAddress<T>())
802 FB_DYNAMIC_APPLY(type_, FB_X);
806 inline std::ostream& operator<<(std::ostream& out, dynamic const& d) {
811 //////////////////////////////////////////////////////////////////////
813 // Secialization of FormatValue so dynamic objects can be formatted
815 class FormatValue<dynamic> {
817 explicit FormatValue(const dynamic& val) : val_(val) { }
819 template <class FormatCallback>
820 void format(FormatArg& arg, FormatCallback& cb) const {
821 switch (val_.type()) {
823 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
826 FormatValue<bool>(val_.asBool()).format(arg, cb);
829 FormatValue<int64_t>(val_.asInt()).format(arg, cb);
831 case dynamic::STRING:
832 FormatValue<fbstring>(val_.asString()).format(arg, cb);
834 case dynamic::DOUBLE:
835 FormatValue<double>(val_.asDouble()).format(arg, cb);
838 FormatValue(val_.at(arg.splitIntKey())).format(arg, cb);
840 case dynamic::OBJECT:
841 FormatValue(val_.at(arg.splitKey().toFbstring())).format(arg, cb);
852 #undef FB_DYNAMIC_APPLY