2 * Copyright 2016 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.
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>
26 //////////////////////////////////////////////////////////////////////
31 struct hash< ::folly::dynamic> {
32 size_t operator()(::folly::dynamic const& d) const {
39 //////////////////////////////////////////////////////////////////////
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) \
73 //////////////////////////////////////////////////////////////////////
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);
85 //////////////////////////////////////////////////////////////////////
89 // This helper is used in destroy() to be able to run destructors on
90 // types like "int64_t" without a compiler error.
92 template<class T> static void destroy(T* t) { t->~T(); }
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.
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());
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());
111 return Op<double>()(a.asDouble(), b.asDouble());
113 return Op<int64_t>()(a.asInt(), b.asInt());
118 //////////////////////////////////////////////////////////////////////
121 * We're doing this instead of a simple member typedef to avoid the
122 * undefined behavior of parameterizing std::unordered_map<> with an
125 * Note: Later we may add separate order tracking here (a multi-index
128 struct dynamic::ObjectImpl : std::unordered_map<dynamic, dynamic> {};
130 //////////////////////////////////////////////////////////////////////
132 // Helper object for creating objects conveniently. See object and
133 // the dynamic::dynamic(ObjectMaker&&) ctor.
134 struct dynamic::ObjectMaker {
135 friend struct dynamic;
137 explicit ObjectMaker() : val_(dynamic::object) {}
138 explicit ObjectMaker(dynamic key, dynamic val)
139 : val_(dynamic::object)
141 val_.insert(std::move(key), std::move(val));
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;
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);
163 inline void dynamic::array(EmptyArrayTag) {}
165 template <class... Args>
166 inline dynamic dynamic::array(Args&& ...args) {
167 return dynamic(Array{std::forward<Args>(args)...});
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));
175 //////////////////////////////////////////////////////////////////////
177 struct dynamic::const_item_iterator
178 : boost::iterator_adaptor<dynamic::const_item_iterator,
179 dynamic::ObjectImpl::const_iterator> {
180 /* implicit */ const_item_iterator(base_type b) : iterator_adaptor_(b) { }
183 friend class boost::iterator_core_access;
186 struct dynamic::const_key_iterator
187 : boost::iterator_adaptor<dynamic::const_key_iterator,
188 dynamic::ObjectImpl::const_iterator,
190 /* implicit */ const_key_iterator(base_type b) : iterator_adaptor_(b) { }
193 dynamic const& dereference() const {
194 return base_reference()->first;
196 friend class boost::iterator_core_access;
199 struct dynamic::const_value_iterator
200 : boost::iterator_adaptor<dynamic::const_value_iterator,
201 dynamic::ObjectImpl::const_iterator,
203 /* implicit */ const_value_iterator(base_type b) : iterator_adaptor_(b) { }
206 dynamic const& dereference() const {
207 return base_reference()->second;
209 friend class boost::iterator_core_access;
212 //////////////////////////////////////////////////////////////////////
214 inline dynamic::dynamic() : dynamic(nullptr) {}
216 inline dynamic::dynamic(std::nullptr_t) : type_(NULLT) {}
218 inline dynamic::dynamic(void (*)(EmptyArrayTag))
221 new (&u_.array) Array();
224 inline dynamic::dynamic(ObjectMaker (*)())
227 new (getAddress<ObjectImpl>()) ObjectImpl();
230 inline dynamic::dynamic(StringPiece s)
233 new (&u_.string) std::string(s.data(), s.size());
236 inline dynamic::dynamic(char const* s)
239 new (&u_.string) std::string(s);
242 inline dynamic::dynamic(std::string s)
245 new (&u_.string) std::string(std::move(s));
248 inline dynamic::dynamic(ObjectMaker&& maker)
251 new (getAddress<ObjectImpl>())
252 ObjectImpl(std::move(*maker.val_.getAddress<ObjectImpl>()));
255 inline dynamic::dynamic(dynamic const& o)
261 inline dynamic::dynamic(dynamic&& o) noexcept
264 *this = std::move(o);
267 inline dynamic::~dynamic() noexcept { destroy(); }
269 // Integral types except bool convert to int64_t, float types to double.
271 struct dynamic::NumericTypeHelper<
272 T, typename std::enable_if<std::is_integral<T>::value>::type> {
273 using type = int64_t;
276 struct dynamic::NumericTypeHelper<bool> {
280 struct dynamic::NumericTypeHelper<float> {
284 struct dynamic::NumericTypeHelper<double> {
288 template<class T, class NumericType /* = typename NumericTypeHelper<T>::type */>
289 dynamic::dynamic(T t) {
290 type_ = TypeInfo<NumericType>::type;
291 new (getAddress<NumericType>()) NumericType(t);
294 template <class Iterator>
295 dynamic::dynamic(Iterator first, Iterator last)
298 new (&u_.array) Array(first, last);
301 //////////////////////////////////////////////////////////////////////
303 inline dynamic::const_iterator dynamic::begin() const {
304 return get<Array>().begin();
306 inline dynamic::const_iterator dynamic::end() const {
307 return get<Array>().end();
311 struct dynamic::IterableProxy {
312 typedef It const_iterator;
313 typedef typename It::value_type value_type;
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 {
345 return get_nothrow<std::string>();
347 inline bool dynamic::isObject() const { return get_nothrow<ObjectImpl>(); }
348 inline bool dynamic::isBool() const { return get_nothrow<bool>(); }
349 inline bool dynamic::isArray() const { return get_nothrow<Array>(); }
350 inline bool dynamic::isDouble() const { return get_nothrow<double>(); }
351 inline bool dynamic::isInt() const { return get_nothrow<int64_t>(); }
352 inline bool dynamic::isNull() const { return get_nothrow<void*>(); }
353 inline bool dynamic::isNumber() const { return isInt() || isDouble(); }
355 inline dynamic::Type dynamic::type() const {
359 inline std::string dynamic::asString() const {
360 return asImpl<std::string>();
362 inline double dynamic::asDouble() const {
363 return asImpl<double>();
365 inline int64_t dynamic::asInt() const {
366 return asImpl<int64_t>();
368 inline bool dynamic::asBool() const {
369 return asImpl<bool>();
372 inline const std::string& dynamic::getString() const& {
373 return get<std::string>();
375 inline double dynamic::getDouble() const& { return get<double>(); }
376 inline int64_t dynamic::getInt() const& { return get<int64_t>(); }
377 inline bool dynamic::getBool() const& { return get<bool>(); }
379 inline std::string& dynamic::getString()& {
380 return get<std::string>();
382 inline double& dynamic::getDouble() & { return get<double>(); }
383 inline int64_t& dynamic::getInt() & { return get<int64_t>(); }
384 inline bool& dynamic::getBool() & { return get<bool>(); }
386 inline std::string&& dynamic::getString()&& {
387 return std::move(get<std::string>());
389 inline double dynamic::getDouble() && { return get<double>(); }
390 inline int64_t dynamic::getInt() && { return get<int64_t>(); }
391 inline bool dynamic::getBool() && { return get<bool>(); }
393 inline const char* dynamic::data() const& {
394 return get<std::string>().data();
396 inline const char* dynamic::c_str() const& {
397 return get<std::string>().c_str();
399 inline StringPiece dynamic::stringPiece() const {
400 return get<std::string>();
404 struct dynamic::CompareOp {
405 static bool comp(T const& a, T const& b) { return a < b; }
408 struct dynamic::CompareOp<dynamic::ObjectImpl> {
409 static bool comp(ObjectImpl const&, ObjectImpl const&) {
410 // This code never executes; it is just here for the compiler.
415 inline dynamic& dynamic::operator+=(dynamic const& o) {
416 if (type() == STRING && o.type() == STRING) {
417 *getAddress<std::string>() += *o.getAddress<std::string>();
420 *this = detail::numericOp<std::plus>(*this, o);
424 inline dynamic& dynamic::operator-=(dynamic const& o) {
425 *this = detail::numericOp<std::minus>(*this, o);
429 inline dynamic& dynamic::operator*=(dynamic const& o) {
430 *this = detail::numericOp<std::multiplies>(*this, o);
434 inline dynamic& dynamic::operator/=(dynamic const& o) {
435 *this = detail::numericOp<std::divides>(*this, o);
439 #define FB_DYNAMIC_INTEGER_OP(op) \
440 inline dynamic& dynamic::operator op(dynamic const& o) { \
441 if (!isInt() || !o.isInt()) { \
442 throw TypeError("int64", type(), o.type()); \
444 *getAddress<int64_t>() op o.asInt(); \
448 FB_DYNAMIC_INTEGER_OP(%=)
449 FB_DYNAMIC_INTEGER_OP(|=)
450 FB_DYNAMIC_INTEGER_OP(&=)
451 FB_DYNAMIC_INTEGER_OP(^=)
453 #undef FB_DYNAMIC_INTEGER_OP
455 inline dynamic& dynamic::operator++() {
460 inline dynamic& dynamic::operator--() {
465 inline dynamic const& dynamic::operator[](dynamic const& idx) const& {
469 inline dynamic&& dynamic::operator[](dynamic const& idx) && {
470 return std::move((*this)[idx]);
473 template<class K, class V> inline dynamic& dynamic::setDefault(K&& k, V&& v) {
474 auto& obj = get<ObjectImpl>();
475 return obj.insert(std::make_pair(std::forward<K>(k),
476 std::forward<V>(v))).first->second;
479 template<class K> inline dynamic& dynamic::setDefault(K&& k, dynamic&& v) {
480 auto& obj = get<ObjectImpl>();
481 return obj.insert(std::make_pair(std::forward<K>(k),
482 std::move(v))).first->second;
485 template<class K> inline dynamic& dynamic::setDefault(K&& k, const dynamic& v) {
486 auto& obj = get<ObjectImpl>();
487 return obj.insert(std::make_pair(std::forward<K>(k), v)).first->second;
490 inline dynamic* dynamic::get_ptr(dynamic const& idx) & {
491 return const_cast<dynamic*>(const_cast<dynamic const*>(this)->get_ptr(idx));
494 inline dynamic& dynamic::at(dynamic const& idx) & {
495 return const_cast<dynamic&>(const_cast<dynamic const*>(this)->at(idx));
498 inline dynamic&& dynamic::at(dynamic const& idx) && {
499 return std::move(at(idx));
502 inline bool dynamic::empty() const {
509 inline std::size_t dynamic::count(dynamic const& key) const {
510 return find(key) != items().end();
513 inline dynamic::const_item_iterator dynamic::find(dynamic const& key) const {
514 return get<ObjectImpl>().find(key);
517 template<class K, class V> inline void dynamic::insert(K&& key, V&& val) {
518 auto& obj = get<ObjectImpl>();
519 auto rv = obj.insert({ std::forward<K>(key), nullptr });
520 rv.first->second = std::forward<V>(val);
523 inline void dynamic::update(const dynamic& mergeObj) {
524 if (!isObject() || !mergeObj.isObject()) {
525 throw TypeError("object", type(), mergeObj.type());
528 for (const auto& pair : mergeObj.items()) {
529 (*this)[pair.first] = pair.second;
533 inline void dynamic::update_missing(const dynamic& mergeObj1) {
534 if (!isObject() || !mergeObj1.isObject()) {
535 throw TypeError("object", type(), mergeObj1.type());
538 // Only add if not already there
539 for (const auto& pair : mergeObj1.items()) {
540 if ((*this).find(pair.first) == (*this).items().end()) {
541 (*this)[pair.first] = pair.second;
546 inline dynamic dynamic::merge(
547 const dynamic& mergeObj1,
548 const dynamic& mergeObj2) {
550 // No checks on type needed here because they are done in update_missing
551 // Note that we do update_missing here instead of update() because
552 // it will prevent the extra writes that would occur with update()
553 auto ret = mergeObj2;
554 ret.update_missing(mergeObj1);
558 inline std::size_t dynamic::erase(dynamic const& key) {
559 auto& obj = get<ObjectImpl>();
560 return obj.erase(key);
563 inline dynamic::const_iterator dynamic::erase(const_iterator it) {
564 auto& arr = get<Array>();
565 // std::vector doesn't have an erase method that works on const iterators,
566 // even though the standard says it should, so this hack converts to a
567 // non-const iterator before calling erase.
568 return get<Array>().erase(arr.begin() + (it - arr.begin()));
571 inline dynamic::const_key_iterator dynamic::erase(const_key_iterator it) {
572 return const_key_iterator(get<ObjectImpl>().erase(it.base()));
575 inline dynamic::const_key_iterator dynamic::erase(const_key_iterator first,
576 const_key_iterator last) {
577 return const_key_iterator(get<ObjectImpl>().erase(first.base(),
581 inline dynamic::const_value_iterator dynamic::erase(const_value_iterator it) {
582 return const_value_iterator(get<ObjectImpl>().erase(it.base()));
585 inline dynamic::const_value_iterator dynamic::erase(const_value_iterator first,
586 const_value_iterator last) {
587 return const_value_iterator(get<ObjectImpl>().erase(first.base(),
591 inline dynamic::const_item_iterator dynamic::erase(const_item_iterator it) {
592 return const_item_iterator(get<ObjectImpl>().erase(it.base()));
595 inline dynamic::const_item_iterator dynamic::erase(const_item_iterator first,
596 const_item_iterator last) {
597 return const_item_iterator(get<ObjectImpl>().erase(first.base(),
601 inline void dynamic::resize(std::size_t sz, dynamic const& c) {
602 auto& arr = get<Array>();
606 inline void dynamic::push_back(dynamic const& v) {
607 auto& arr = get<Array>();
611 inline void dynamic::push_back(dynamic&& v) {
612 auto& arr = get<Array>();
613 arr.push_back(std::move(v));
616 inline void dynamic::pop_back() {
617 auto& arr = get<Array>();
621 //////////////////////////////////////////////////////////////////////
623 inline dynamic::dynamic(Array&& r) : type_(ARRAY) {
624 new (&u_.array) Array(std::move(r));
627 #define FOLLY_DYNAMIC_DEC_TYPEINFO(T, str, val) \
628 template <> struct dynamic::TypeInfo<T> { \
629 static constexpr const char* name = str; \
630 static constexpr dynamic::Type type = val; \
634 FOLLY_DYNAMIC_DEC_TYPEINFO(void*, "null", dynamic::NULLT)
635 FOLLY_DYNAMIC_DEC_TYPEINFO(bool, "boolean", dynamic::BOOL)
636 FOLLY_DYNAMIC_DEC_TYPEINFO(std::string, "string", dynamic::STRING)
637 FOLLY_DYNAMIC_DEC_TYPEINFO(dynamic::Array, "array", dynamic::ARRAY)
638 FOLLY_DYNAMIC_DEC_TYPEINFO(double, "double", dynamic::DOUBLE)
639 FOLLY_DYNAMIC_DEC_TYPEINFO(int64_t, "int64", dynamic::INT64)
640 FOLLY_DYNAMIC_DEC_TYPEINFO(dynamic::ObjectImpl, "object", dynamic::OBJECT)
642 #undef FOLLY_DYNAMIC_DEC_TYPEINFO
645 T dynamic::asImpl() const {
647 case INT64: return to<T>(*get_nothrow<int64_t>());
648 case DOUBLE: return to<T>(*get_nothrow<double>());
649 case BOOL: return to<T>(*get_nothrow<bool>());
651 return to<T>(*get_nothrow<std::string>());
653 throw TypeError("int/double/bool/string", type());
657 // Return a T* to our type, or null if we're not that type.
659 T* dynamic::get_nothrow() & noexcept {
660 if (type_ != TypeInfo<T>::type) {
663 return getAddress<T>();
667 T const* dynamic::get_nothrow() const& noexcept {
668 return const_cast<dynamic*>(this)->get_nothrow<T>();
671 // Return T* for where we can put a T, without type checking. (Memory
672 // might be uninitialized, even.)
674 T* dynamic::getAddress() noexcept {
675 return GetAddrImpl<T>::get(u_);
679 T const* dynamic::getAddress() const noexcept {
680 return const_cast<dynamic*>(this)->getAddress<T>();
683 template<class T> struct dynamic::GetAddrImpl {};
684 template<> struct dynamic::GetAddrImpl<void*> {
685 static void** get(Data& d) noexcept { return &d.nul; }
687 template<> struct dynamic::GetAddrImpl<dynamic::Array> {
688 static Array* get(Data& d) noexcept { return &d.array; }
690 template<> struct dynamic::GetAddrImpl<bool> {
691 static bool* get(Data& d) noexcept { return &d.boolean; }
693 template<> struct dynamic::GetAddrImpl<int64_t> {
694 static int64_t* get(Data& d) noexcept { return &d.integer; }
696 template<> struct dynamic::GetAddrImpl<double> {
697 static double* get(Data& d) noexcept { return &d.doubl; }
700 struct dynamic::GetAddrImpl<std::string> {
701 static std::string* get(Data& d) noexcept {
705 template<> struct dynamic::GetAddrImpl<dynamic::ObjectImpl> {
706 static_assert(sizeof(ObjectImpl) <= sizeof(Data::objectBuffer),
707 "In your implementation, std::unordered_map<> apparently takes different"
708 " amount of space depending on its template parameters. This is "
709 "weird. Make objectBuffer bigger if you want to compile dynamic.");
711 static ObjectImpl* get(Data& d) noexcept {
712 void* data = &d.objectBuffer;
713 return static_cast<ObjectImpl*>(data);
719 if (auto* p = get_nothrow<T>()) {
722 throw TypeError(TypeInfo<T>::name, type());
726 T const& dynamic::get() const {
727 return const_cast<dynamic*>(this)->get<T>();
730 //////////////////////////////////////////////////////////////////////
733 * Helper for implementing operator<<. Throws if the type shouldn't
737 struct dynamic::PrintImpl {
738 static void print(dynamic const&, std::ostream& out, T const& t) {
742 // Otherwise, null, being (void*)0, would print as 0.
744 struct dynamic::PrintImpl<void*> {
745 static void print(dynamic const& /* d */,
748 DCHECK_EQ((void*)0, nul);
753 struct dynamic::PrintImpl<dynamic::ObjectImpl> {
754 static void print(dynamic const& d,
756 dynamic::ObjectImpl const&) {
757 d.print_as_pseudo_json(out);
761 struct dynamic::PrintImpl<dynamic::Array> {
762 static void print(dynamic const& d,
764 dynamic::Array const&) {
765 d.print_as_pseudo_json(out);
769 inline void dynamic::print(std::ostream& out) const {
770 #define FB_X(T) PrintImpl<T>::print(*this, out, *getAddress<T>())
771 FB_DYNAMIC_APPLY(type_, FB_X);
775 inline std::ostream& operator<<(std::ostream& out, dynamic const& d) {
780 //////////////////////////////////////////////////////////////////////
782 // Secialization of FormatValue so dynamic objects can be formatted
784 class FormatValue<dynamic> {
786 explicit FormatValue(const dynamic& val) : val_(val) { }
788 template <class FormatCallback>
789 void format(FormatArg& arg, FormatCallback& cb) const {
790 switch (val_.type()) {
792 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
795 FormatValue<bool>(val_.asBool()).format(arg, cb);
798 FormatValue<int64_t>(val_.asInt()).format(arg, cb);
800 case dynamic::STRING:
801 FormatValue<std::string>(val_.asString()).format(arg, cb);
803 case dynamic::DOUBLE:
804 FormatValue<double>(val_.asDouble()).format(arg, cb);
807 FormatValue(val_.at(arg.splitIntKey())).format(arg, cb);
809 case dynamic::OBJECT:
810 FormatValue(val_.at(arg.splitKey().toString())).format(arg, cb);
820 class FormatValue<detail::DefaultValueWrapper<dynamic, V>> {
822 explicit FormatValue(
823 const detail::DefaultValueWrapper<dynamic, V>& val)
826 template <class FormatCallback>
827 void format(FormatArg& arg, FormatCallback& cb) const {
828 auto& c = val_.container;
833 case dynamic::STRING:
834 case dynamic::DOUBLE:
835 FormatValue<dynamic>(c).format(arg, cb);
839 int key = arg.splitIntKey();
840 if (key >= 0 && size_t(key) < c.size()) {
841 FormatValue<dynamic>(c.at(key)).format(arg, cb);
843 FormatValue<V>(val_.defaultValue).format(arg, cb);
847 case dynamic::OBJECT:
849 auto pos = c.find(arg.splitKey());
850 if (pos != c.items().end()) {
851 FormatValue<dynamic>(pos->second).format(arg, cb);
853 FormatValue<V>(val_.defaultValue).format(arg, cb);
861 const detail::DefaultValueWrapper<dynamic, V>& val_;
866 #undef FB_DYNAMIC_APPLY