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 struct TypeError : std::runtime_error {
62 explicit TypeError(const std::string& expected, dynamic::Type actual)
63 : std::runtime_error(to<std::string>("TypeError: expected dynamic "
64 "type `", expected, '\'', ", but had type `",
65 dynamic::typeName(actual), '\''))
67 explicit TypeError(const std::string& expected,
68 dynamic::Type actual1, dynamic::Type actual2)
69 : std::runtime_error(to<std::string>("TypeError: expected dynamic "
70 "types `", expected, '\'', ", but had types `",
71 dynamic::typeName(actual1), "' and `", dynamic::typeName(actual2),
77 //////////////////////////////////////////////////////////////////////
81 // This helper is used in destroy() to be able to run destructors on
82 // types like "int64_t" without a compiler error.
84 template<class T> static void destroy(T* t) { t->~T(); }
88 * The enable_if junk here is necessary to avoid ambiguous
89 * conversions relating to bool and double when you implicitly
90 * convert an int or long to a dynamic.
92 template<class T, class Enable = void> struct ConversionHelper;
94 struct ConversionHelper<
96 typename std::enable_if<
97 std::is_integral<T>::value && !std::is_same<T,bool>::value
100 typedef int64_t type;
103 struct ConversionHelper<
105 typename std::enable_if<
106 (!std::is_integral<T>::value || std::is_same<T,bool>::value) &&
107 !std::is_same<T,std::nullptr_t>::value
113 struct ConversionHelper<
115 typename std::enable_if<
116 std::is_same<T,std::nullptr_t>::value
123 * Helper for implementing numeric conversions in operators on
124 * numbers. Just promotes to double when one of the arguments is
125 * double, or throws if either is not a numeric type.
127 template<template<class> class Op>
128 dynamic numericOp(dynamic const& a, dynamic const& b) {
129 if (!a.isNumber() || !b.isNumber()) {
130 throw TypeError("numeric", a.type(), b.type());
132 if (a.type() != b.type()) {
133 auto& integ = a.isInt() ? a : b;
134 auto& nonint = a.isInt() ? b : a;
135 return Op<double>()(to<double>(integ.asInt()), nonint.asDouble());
138 return Op<double>()(a.asDouble(), b.asDouble());
140 return Op<int64_t>()(a.asInt(), b.asInt());
145 //////////////////////////////////////////////////////////////////////
148 * We're doing this instead of a simple member typedef to avoid the
149 * undefined behavior of parameterizing std::unordered_map<> with an
152 * Note: Later we may add separate order tracking here (a multi-index
155 struct dynamic::ObjectImpl : std::unordered_map<dynamic, dynamic> {};
157 //////////////////////////////////////////////////////////////////////
159 // Helper object for creating objects conveniently. See object and
160 // the dynamic::dynamic(ObjectMaker&&) ctor.
161 struct dynamic::ObjectMaker {
162 friend struct dynamic;
164 explicit ObjectMaker() : val_(dynamic::object) {}
165 explicit ObjectMaker(dynamic const& key, dynamic val)
166 : val_(dynamic::object)
168 val_.insert(key, std::move(val));
170 explicit ObjectMaker(dynamic&& key, dynamic val)
171 : val_(dynamic::object)
173 val_.insert(std::move(key), std::move(val));
176 // Make sure no one tries to save one of these into an lvalue with
177 // auto or anything like that.
178 ObjectMaker(ObjectMaker&&) = default;
179 ObjectMaker(ObjectMaker const&) = delete;
180 ObjectMaker& operator=(ObjectMaker const&) = delete;
181 ObjectMaker& operator=(ObjectMaker&&) = delete;
183 // These return rvalue-references instead of lvalue-references to allow
184 // constructs like this to moved instead of copied:
185 // dynamic a = dynamic::object("a", "b")("c", "d")
186 ObjectMaker&& operator()(dynamic const& key, dynamic val) {
187 val_.insert(key, std::move(val));
188 return std::move(*this);
191 ObjectMaker&& operator()(dynamic&& key, dynamic val) {
192 val_.insert(std::move(key), std::move(val));
193 return std::move(*this);
200 template<class... Args>
201 inline dynamic::ObjectMaker dynamic::object(Args&&... args) {
202 return dynamic::ObjectMaker(std::forward<Args>(args)...);
205 //////////////////////////////////////////////////////////////////////
207 struct dynamic::const_item_iterator
208 : boost::iterator_adaptor<dynamic::const_item_iterator,
209 dynamic::ObjectImpl::const_iterator> {
210 /* implicit */ const_item_iterator(base_type b) : iterator_adaptor_(b) { }
213 friend class boost::iterator_core_access;
216 struct dynamic::const_key_iterator
217 : boost::iterator_adaptor<dynamic::const_key_iterator,
218 dynamic::ObjectImpl::const_iterator,
220 /* implicit */ const_key_iterator(base_type b) : iterator_adaptor_(b) { }
223 dynamic const& dereference() const {
224 return base_reference()->first;
226 friend class boost::iterator_core_access;
229 struct dynamic::const_value_iterator
230 : boost::iterator_adaptor<dynamic::const_value_iterator,
231 dynamic::ObjectImpl::const_iterator,
233 /* implicit */ const_value_iterator(base_type b) : iterator_adaptor_(b) { }
236 dynamic const& dereference() const {
237 return base_reference()->second;
239 friend class boost::iterator_core_access;
242 //////////////////////////////////////////////////////////////////////
244 inline dynamic::dynamic(ObjectMaker (*)())
247 new (getAddress<ObjectImpl>()) ObjectImpl();
250 inline dynamic::dynamic(char const* s)
253 new (&u_.string) fbstring(s);
256 inline dynamic::dynamic(std::string const& s)
259 new (&u_.string) fbstring(s);
262 inline dynamic::dynamic(std::initializer_list<dynamic> il)
265 new (&u_.array) Array(il.begin(), il.end());
268 inline dynamic::dynamic(ObjectMaker&& maker)
271 new (getAddress<ObjectImpl>())
272 ObjectImpl(std::move(*maker.val_.getAddress<ObjectImpl>()));
275 inline dynamic::dynamic(dynamic const& o)
281 inline dynamic::dynamic(dynamic&& o)
284 *this = std::move(o);
287 inline dynamic::~dynamic() { destroy(); }
290 dynamic::dynamic(T t) {
291 typedef typename detail::ConversionHelper<T>::type U;
292 type_ = TypeInfo<U>::type;
293 new (getAddress<U>()) U(std::move(t));
296 template<class Iterator>
297 dynamic::dynamic(Iterator first, Iterator last)
300 new (&u_.array) Array(first, last);
303 //////////////////////////////////////////////////////////////////////
305 inline dynamic::const_iterator dynamic::begin() const {
306 return get<Array>().begin();
308 inline dynamic::const_iterator dynamic::end() const {
309 return get<Array>().end();
313 struct dynamic::IterableProxy {
314 typedef It const_iterator;
316 /* implicit */ IterableProxy(const dynamic::ObjectImpl* o) : o_(o) { }
327 const dynamic::ObjectImpl* o_;
330 inline dynamic::IterableProxy<dynamic::const_key_iterator> dynamic::keys()
332 return &(get<ObjectImpl>());
335 inline dynamic::IterableProxy<dynamic::const_value_iterator> dynamic::values()
337 return &(get<ObjectImpl>());
340 inline dynamic::IterableProxy<dynamic::const_item_iterator> dynamic::items()
342 return &(get<ObjectImpl>());
345 inline bool dynamic::isString() const { return get_nothrow<fbstring>(); }
346 inline bool dynamic::isObject() const { return get_nothrow<ObjectImpl>(); }
347 inline bool dynamic::isBool() const { return get_nothrow<bool>(); }
348 inline bool dynamic::isArray() const { return get_nothrow<Array>(); }
349 inline bool dynamic::isDouble() const { return get_nothrow<double>(); }
350 inline bool dynamic::isInt() const { return get_nothrow<int64_t>(); }
351 inline bool dynamic::isNull() const { return get_nothrow<void*>(); }
352 inline bool dynamic::isNumber() const { return isInt() || isDouble(); }
354 inline dynamic::Type dynamic::type() const {
358 inline fbstring dynamic::asString() const { return asImpl<fbstring>(); }
359 inline double dynamic::asDouble() const { return asImpl<double>(); }
360 inline int64_t dynamic::asInt() const { return asImpl<int64_t>(); }
361 inline bool dynamic::asBool() const { return asImpl<bool>(); }
364 struct dynamic::CompareOp {
365 static bool comp(T const& a, T const& b) { return a < b; }
368 struct dynamic::CompareOp<dynamic::ObjectImpl> {
369 static bool comp(ObjectImpl const& a, ObjectImpl const& b) {
370 // This code never executes; it is just here for the compiler.
375 inline bool dynamic::operator<(dynamic const& o) const {
376 if (UNLIKELY(type_ == OBJECT || o.type_ == OBJECT)) {
377 throw TypeError("object", type_);
379 if (type_ != o.type_) {
380 return type_ < o.type_;
383 #define FB_X(T) return CompareOp<T>::comp(*getAddress<T>(), \
385 FB_DYNAMIC_APPLY(type_, FB_X);
389 inline bool dynamic::operator==(dynamic const& o) const {
390 if (type() != o.type()) {
391 if (isNumber() && o.isNumber()) {
392 auto& integ = isInt() ? *this : o;
393 auto& doubl = isInt() ? o : *this;
394 return integ.asInt() == doubl.asDouble();
399 #define FB_X(T) return *getAddress<T>() == *o.getAddress<T>();
400 FB_DYNAMIC_APPLY(type_, FB_X);
404 inline dynamic& dynamic::operator+=(dynamic const& o) {
405 if (type() == STRING && o.type() == STRING) {
406 *getAddress<fbstring>() += *o.getAddress<fbstring>();
409 *this = detail::numericOp<std::plus>(*this, o);
413 inline dynamic& dynamic::operator-=(dynamic const& o) {
414 *this = detail::numericOp<std::minus>(*this, o);
418 inline dynamic& dynamic::operator*=(dynamic const& o) {
419 *this = detail::numericOp<std::multiplies>(*this, o);
423 inline dynamic& dynamic::operator/=(dynamic const& o) {
424 *this = detail::numericOp<std::divides>(*this, o);
428 #define FB_DYNAMIC_INTEGER_OP(op) \
429 inline dynamic& dynamic::operator op(dynamic const& o) { \
430 if (!isInt() || !o.isInt()) { \
431 throw TypeError("int64", type(), o.type()); \
433 *getAddress<int64_t>() op o.asInt(); \
437 FB_DYNAMIC_INTEGER_OP(%=)
438 FB_DYNAMIC_INTEGER_OP(|=)
439 FB_DYNAMIC_INTEGER_OP(&=)
440 FB_DYNAMIC_INTEGER_OP(^=)
442 #undef FB_DYNAMIC_INTEGER_OP
444 inline dynamic& dynamic::operator++() {
449 inline dynamic& dynamic::operator--() {
454 inline dynamic& dynamic::operator=(dynamic const& o) {
457 #define FB_X(T) new (getAddress<T>()) T(*o.getAddress<T>())
458 FB_DYNAMIC_APPLY(o.type_, FB_X);
465 inline dynamic& dynamic::operator=(dynamic&& o) {
468 #define FB_X(T) new (getAddress<T>()) T(std::move(*o.getAddress<T>()))
469 FB_DYNAMIC_APPLY(o.type_, FB_X);
476 inline dynamic& dynamic::operator[](dynamic const& k) {
477 if (!isObject() && !isArray()) {
478 throw TypeError("object/array", type());
483 auto& obj = get<ObjectImpl>();
484 auto ret = obj.insert({k, nullptr});
485 return ret.first->second;
488 inline dynamic const& dynamic::operator[](dynamic const& idx) const {
492 inline dynamic dynamic::getDefault(const dynamic& k, const dynamic& v) const {
493 auto& obj = get<ObjectImpl>();
494 auto it = obj.find(k);
495 return it == obj.end() ? v : it->second;
498 inline dynamic&& dynamic::getDefault(const dynamic& k, dynamic&& v) const {
499 auto& obj = get<ObjectImpl>();
500 auto it = obj.find(k);
501 if (it != obj.end()) {
508 template<class K, class V> inline dynamic& dynamic::setDefault(K&& k, V&& v) {
509 auto& obj = get<ObjectImpl>();
510 return obj.insert(std::make_pair(std::forward<K>(k),
511 std::forward<V>(v))).first->second;
514 inline dynamic const& dynamic::at(dynamic const& idx) const {
515 return const_cast<dynamic*>(this)->at(idx);
518 inline dynamic& dynamic::at(dynamic const& idx) {
519 if (!isObject() && !isArray()) {
520 throw TypeError("object/array", type());
523 if (auto* parray = get_nothrow<Array>()) {
524 if (idx >= parray->size()) {
525 throw std::out_of_range("out of range in dynamic array");
528 throw TypeError("int64", idx.type());
530 return (*parray)[idx.asInt()];
533 auto* pobj = get_nothrow<ObjectImpl>();
536 if (it == items().end()) {
537 throw std::out_of_range(to<std::string>(
538 "couldn't find key ", idx.asString(), " in dynamic object"));
540 return const_cast<dynamic&>(it->second);
543 inline bool dynamic::empty() const {
550 inline std::size_t dynamic::size() const {
551 if (auto* ar = get_nothrow<Array>()) {
554 if (auto* obj = get_nothrow<ObjectImpl>()) {
557 if (auto* str = get_nothrow<fbstring>()) {
560 throw TypeError("array/object", type());
563 inline std::size_t dynamic::count(dynamic const& key) const {
564 return find(key) != items().end();
567 inline dynamic::const_item_iterator dynamic::find(dynamic const& key) const {
568 return get<ObjectImpl>().find(key);
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::make_pair(std::forward<K>(key),
574 std::forward<V>(val)));
576 // note, the second use of std:forward<V>(val) is only correct
577 // if the first one did not result in a move. obj[key] = val
578 // would be preferrable but doesn't compile because dynamic
579 // is (intentionally) not default constructable
580 rv.first->second = std::forward<V>(val);
584 inline std::size_t dynamic::erase(dynamic const& key) {
585 auto& obj = get<ObjectImpl>();
586 return obj.erase(key);
589 inline dynamic::const_iterator dynamic::erase(const_iterator it) {
590 auto& arr = get<Array>();
591 // std::vector doesn't have an erase method that works on const iterators,
592 // even though the standard says it should, so this hack converts to a
593 // non-const iterator before calling erase.
594 return get<Array>().erase(arr.begin() + (it - arr.begin()));
597 inline dynamic::const_iterator
598 dynamic::erase(const_iterator first, const_iterator last) {
599 auto& arr = get<Array>();
600 return get<Array>().erase(
601 arr.begin() + (first - arr.begin()),
602 arr.begin() + (last - arr.begin()));
605 inline dynamic::const_key_iterator dynamic::erase(const_key_iterator it) {
606 return const_key_iterator(get<ObjectImpl>().erase(it.base()));
609 inline dynamic::const_key_iterator dynamic::erase(const_key_iterator first,
610 const_key_iterator last) {
611 return const_key_iterator(get<ObjectImpl>().erase(first.base(),
615 inline dynamic::const_value_iterator dynamic::erase(const_value_iterator it) {
616 return const_value_iterator(get<ObjectImpl>().erase(it.base()));
619 inline dynamic::const_value_iterator dynamic::erase(const_value_iterator first,
620 const_value_iterator last) {
621 return const_value_iterator(get<ObjectImpl>().erase(first.base(),
625 inline dynamic::const_item_iterator dynamic::erase(const_item_iterator it) {
626 return const_item_iterator(get<ObjectImpl>().erase(it.base()));
629 inline dynamic::const_item_iterator dynamic::erase(const_item_iterator first,
630 const_item_iterator last) {
631 return const_item_iterator(get<ObjectImpl>().erase(first.base(),
635 inline void dynamic::resize(std::size_t sz, dynamic const& c) {
636 auto& array = get<Array>();
640 inline void dynamic::push_back(dynamic const& v) {
641 auto& array = get<Array>();
645 inline void dynamic::push_back(dynamic&& v) {
646 auto& array = get<Array>();
647 array.push_back(std::move(v));
650 inline void dynamic::pop_back() {
651 auto& array = get<Array>();
655 inline std::size_t dynamic::hash() const {
660 throw TypeError("not null/object/array", type());
662 return std::hash<int64_t>()(asInt());
664 return std::hash<double>()(asDouble());
666 return std::hash<bool>()(asBool());
668 return std::hash<fbstring>()(asString());
674 //////////////////////////////////////////////////////////////////////
676 template<class T> struct dynamic::TypeInfo {
677 static char const name[];
678 static Type const type;
682 T dynamic::asImpl() const {
684 case INT64: return to<T>(*get_nothrow<int64_t>());
685 case DOUBLE: return to<T>(*get_nothrow<double>());
686 case BOOL: return to<T>(*get_nothrow<bool>());
687 case STRING: return to<T>(*get_nothrow<fbstring>());
689 throw TypeError("int/double/bool/string", type());
693 // Return a T* to our type, or null if we're not that type.
695 T* dynamic::get_nothrow() {
696 if (type_ != TypeInfo<T>::type) {
699 return getAddress<T>();
703 T const* dynamic::get_nothrow() const {
704 return const_cast<dynamic*>(this)->get_nothrow<T>();
707 // Return T* for where we can put a T, without type checking. (Memory
708 // might be uninitialized, even.)
710 T* dynamic::getAddress() {
711 return GetAddrImpl<T>::get(u_);
715 T const* dynamic::getAddress() const {
716 return const_cast<dynamic*>(this)->getAddress<T>();
719 template<class T> struct dynamic::GetAddrImpl {};
720 template<> struct dynamic::GetAddrImpl<void*> {
721 static void** get(Data& d) { return &d.nul; }
723 template<> struct dynamic::GetAddrImpl<dynamic::Array> {
724 static Array* get(Data& d) { return &d.array; }
726 template<> struct dynamic::GetAddrImpl<bool> {
727 static bool* get(Data& d) { return &d.boolean; }
729 template<> struct dynamic::GetAddrImpl<int64_t> {
730 static int64_t* get(Data& d) { return &d.integer; }
732 template<> struct dynamic::GetAddrImpl<double> {
733 static double* get(Data& d) { return &d.doubl; }
735 template<> struct dynamic::GetAddrImpl<fbstring> {
736 static fbstring* get(Data& d) { return &d.string; }
738 template<> struct dynamic::GetAddrImpl<dynamic::ObjectImpl> {
739 static_assert(sizeof(ObjectImpl) <= sizeof(Data::objectBuffer),
740 "In your implementation, std::unordered_map<> apparently takes different"
741 " amount of space depending on its template parameters. This is "
742 "weird. Make objectBuffer bigger if you want to compile dynamic.");
744 static ObjectImpl* get(Data& d) {
745 void* data = &d.objectBuffer;
746 return static_cast<ObjectImpl*>(data);
752 if (auto* p = get_nothrow<T>()) {
755 throw TypeError(TypeInfo<T>::name, type());
759 T const& dynamic::get() const {
760 return const_cast<dynamic*>(this)->get<T>();
763 inline char const* dynamic::typeName(Type t) {
764 #define FB_X(T) return TypeInfo<T>::name
765 FB_DYNAMIC_APPLY(t, FB_X);
769 inline void dynamic::destroy() {
770 // This short-circuit speeds up some microbenchmarks.
771 if (type_ == NULLT) return;
773 #define FB_X(T) detail::Destroy::destroy(getAddress<T>())
774 FB_DYNAMIC_APPLY(type_, FB_X);
780 //////////////////////////////////////////////////////////////////////
783 * Helper for implementing operator<<. Throws if the type shouldn't
787 struct dynamic::PrintImpl {
788 static void print(dynamic const&, std::ostream& out, T const& t) {
793 struct dynamic::PrintImpl<dynamic::ObjectImpl> {
794 static void print(dynamic const& d,
796 dynamic::ObjectImpl const&) {
797 d.print_as_pseudo_json(out);
801 struct dynamic::PrintImpl<dynamic::Array> {
802 static void print(dynamic const& d,
804 dynamic::Array const&) {
805 d.print_as_pseudo_json(out);
809 inline void dynamic::print(std::ostream& out) const {
810 #define FB_X(T) PrintImpl<T>::print(*this, out, *getAddress<T>())
811 FB_DYNAMIC_APPLY(type_, FB_X);
815 inline std::ostream& operator<<(std::ostream& out, dynamic const& d) {
820 //////////////////////////////////////////////////////////////////////
822 // Secialization of FormatValue so dynamic objects can be formatted
824 class FormatValue<dynamic> {
826 explicit FormatValue(const dynamic& val) : val_(val) { }
828 template <class FormatCallback>
829 void format(FormatArg& arg, FormatCallback& cb) const {
830 switch (val_.type()) {
832 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
835 FormatValue<bool>(val_.asBool()).format(arg, cb);
838 FormatValue<int64_t>(val_.asInt()).format(arg, cb);
840 case dynamic::STRING:
841 FormatValue<fbstring>(val_.asString()).format(arg, cb);
843 case dynamic::DOUBLE:
844 FormatValue<double>(val_.asDouble()).format(arg, cb);
847 FormatValue(val_.at(arg.splitIntKey())).format(arg, cb);
849 case dynamic::OBJECT:
850 FormatValue(val_.at(arg.splitKey().toFbstring())).format(arg, cb);
861 #undef FB_DYNAMIC_APPLY