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.
18 * This is a runtime dynamically typed value. It holds types from a
19 * specific predetermined set of types (ints, bools, arrays, etc). In
20 * particular, it can be used as a convenient in-memory representation
21 * for complete json objects.
23 * In general you can try to use these objects as if they were the
24 * type they represent (although in some cases with a slightly less
25 * complete interface than the raw type), and it'll just throw a
26 * TypeError if it is used in an illegal way.
30 * dynamic twelve = 12;
31 * dynamic str = "string";
32 * dynamic map = dynamic::object;
34 * map[str + "another_str"] = dynamic::array("array", "of", 4, "elements");
35 * map.insert("null_element", nullptr);
37 * assert(map[str] == 13);
39 * // Building a complex object with a sub array inline:
40 * dynamic d = dynamic::object
42 * ("key2", dynamic::array("a", "array"))
45 * Also see folly/json.h for the serialization and deserialization
48 * Note: dynamic is not DefaultConstructible. Rationale:
50 * - The intuitive thing to initialize a defaulted dynamic to would
53 * - However, the expression dynamic d = {} is required to call the
54 * default constructor by the standard, which is confusing
55 * behavior for dynamic unless the default constructor creates an
58 * Additional documentation is in folly/docs/Dynamic.md.
60 * @author Jordan DeLong <delong.j@fb.com>
66 #include <initializer_list>
70 #include <type_traits>
71 #include <unordered_map>
75 #include <boost/operators.hpp>
77 #include <folly/Range.h>
78 #include <folly/Traits.h>
82 //////////////////////////////////////////////////////////////////////
87 //////////////////////////////////////////////////////////////////////
89 struct dynamic : private boost::operators<dynamic> {
101 * We support direct iteration of arrays, and indirect iteration of objects.
102 * See begin(), end(), keys(), values(), and items() for more.
104 * Array iterators dereference as the elements in the array.
105 * Object key iterators dereference as the keys in the object.
106 * Object value iterators dereference as the values in the object.
107 * Object item iterators dereference as pairs of (key, value).
110 typedef std::vector<dynamic> Array;
112 typedef Array::const_iterator const_iterator;
113 typedef dynamic value_type;
114 struct const_key_iterator;
115 struct const_value_iterator;
116 struct const_item_iterator;
119 * Creation routines for making dynamic objects and arrays. Objects
120 * are maps from key to value (so named due to json-related origins
125 * // Make a fairly complex dynamic:
126 * dynamic d = dynamic::object("key", "value1")
127 * ("key2", dynamic::array("value",
132 * // Build an object in a few steps:
133 * dynamic d = dynamic::object;
135 * d["something_else"] = dynamic::array(1, 2, 3, nullptr);
138 struct PrivateTag {};
139 struct EmptyArrayTag {};
143 static void array(EmptyArrayTag);
144 template <class... Args>
145 static dynamic array(Args&& ...args);
147 static ObjectMaker object();
148 static ObjectMaker object(dynamic&&, dynamic&&);
149 static ObjectMaker object(dynamic const&, dynamic&&);
150 static ObjectMaker object(dynamic&&, dynamic const&);
151 static ObjectMaker object(dynamic const&, dynamic const&);
154 * String compatibility constructors.
156 /* implicit */ dynamic(StringPiece val);
157 /* implicit */ dynamic(char const* val);
158 /* implicit */ dynamic(std::string const& val);
159 /* implicit */ dynamic(std::string&& val);
162 * This is part of the plumbing for array() and object(), above.
163 * Used to create a new array or object dynamic.
165 /* implicit */ dynamic(void (*)(EmptyArrayTag));
166 /* implicit */ dynamic(ObjectMaker (*)());
167 /* implicit */ dynamic(ObjectMaker const&) = delete;
168 /* implicit */ dynamic(ObjectMaker&&);
171 * Create a new array from an initializer list.
175 * dynamic v = { 1, 2, 3, "foo" };
177 // TODO(ott, 10300209): Remove once all uses have been eradicated.
180 "Initializer list syntax is deprecated (#10300209). Use dynamic::array.")
181 /* implicit */ dynamic(std::initializer_list<dynamic> il);
183 "Initializer list syntax is deprecated (#10300209). Use dynamic::array.")
184 dynamic& operator=(std::initializer_list<dynamic> il);
187 * Conversion constructors from most of the other types.
189 template<class T> /* implicit */ dynamic(T t);
192 * Create a dynamic that is an array of the values from the supplied
195 template<class Iterator> dynamic(Iterator first, Iterator last);
197 dynamic(dynamic const&);
198 dynamic(dynamic&&) noexcept;
202 * "Deep" equality comparison. This will compare all the way down
203 * an object or array, and is potentially expensive.
205 bool operator==(dynamic const& o) const;
208 * For all types except object this returns the natural ordering on
209 * those types. For objects, we throw TypeError.
211 bool operator<(dynamic const& o) const;
216 * These throw TypeError when used with types or type combinations
217 * that don't support them.
219 * These functions may also throw if you use 64-bit integers with
220 * doubles when the integers are too big to fit in a double.
222 dynamic& operator+=(dynamic const&);
223 dynamic& operator-=(dynamic const&);
224 dynamic& operator*=(dynamic const&);
225 dynamic& operator/=(dynamic const&);
226 dynamic& operator%=(dynamic const&);
227 dynamic& operator|=(dynamic const&);
228 dynamic& operator&=(dynamic const&);
229 dynamic& operator^=(dynamic const&);
230 dynamic& operator++();
231 dynamic& operator--();
234 * Assignment from other dynamics. Because of the implicit conversion
235 * to dynamic from its potential types, you can use this to change the
236 * type pretty intuitively.
238 * Basic guarantee only.
240 dynamic& operator=(dynamic const&);
241 dynamic& operator=(dynamic&&) noexcept;
244 * For simple dynamics (not arrays or objects), this prints the
245 * value to an std::ostream in the expected way. Respects the
246 * formatting manipulators that have been sent to the stream
249 * If the dynamic holds an object or array, this prints them in a
250 * format very similar to JSON. (It will in fact actually be JSON
251 * as long as the dynamic validly represents a JSON object---i.e. it
252 * can't have non-string keys.)
254 friend std::ostream& operator<<(std::ostream&, dynamic const&);
257 * Returns true if this dynamic is of the specified type.
259 bool isString() const;
260 bool isObject() const;
263 bool isArray() const;
264 bool isDouble() const;
268 * Returns: isInt() || isDouble().
270 bool isNumber() const;
273 * Returns the type of this dynamic.
278 * Returns the type of this dynamic as a printable string.
280 const char* typeName() const;
283 * Extract a value while trying to convert to the specified type.
284 * Throws exceptions if we cannot convert from the real type to the
287 * Note you can only use this to access integral types or strings,
288 * since arrays and objects are generally best dealt with as a
291 std::string asString() const;
292 double asDouble() const;
293 int64_t asInt() const;
297 * Extract the value stored in this dynamic without type conversion.
299 * These will throw a TypeError if the dynamic has a different type.
301 const std::string& getString() const&;
302 double getDouble() const&;
303 int64_t getInt() const&;
304 bool getBool() const&;
305 std::string& getString() &;
306 double& getDouble() &;
309 std::string getString() &&;
310 double getDouble() &&;
315 * It is occasionally useful to access a string's internal pointer
316 * directly, without the type conversion of `asString()`.
318 * These will throw a TypeError if the dynamic is not a string.
320 const char* data() const&;
321 const char* data() && = delete;
322 const char* c_str() const&;
323 const char* c_str() && = delete;
324 StringPiece stringPiece() const;
327 * Returns: true if this dynamic is null, an empty array, an empty
328 * object, or an empty string.
333 * If this is an array or an object, returns the number of elements
334 * contained. If it is a string, returns the length. Otherwise
337 std::size_t size() const;
340 * You can iterate over the values of the array. Calling these on
341 * non-arrays will throw a TypeError.
343 const_iterator begin() const;
344 const_iterator end() const;
348 * Helper object returned by keys(), values(), and items().
350 template <class T> struct IterableProxy;
354 * You can iterate over the keys, values, or items (std::pair of key and
355 * value) in an object. Calling these on non-objects will throw a TypeError.
357 IterableProxy<const_key_iterator> keys() const;
358 IterableProxy<const_value_iterator> values() const;
359 IterableProxy<const_item_iterator> items() const;
362 * AssociativeContainer-style find interface for objects. Throws if
363 * this is not an object.
365 * Returns: items().end() if the key is not present, or a
366 * const_item_iterator pointing to the item.
368 const_item_iterator find(dynamic const&) const;
371 * If this is an object, returns whether it contains a field with
372 * the given name. Otherwise throws TypeError.
374 std::size_t count(dynamic const&) const;
377 * For objects or arrays, provides access to sub-fields by index or
380 * Using these with dynamic objects that are not arrays or objects
381 * will throw a TypeError. Using an index that is out of range or
382 * object-element that's not present throws std::out_of_range.
384 dynamic const& at(dynamic const&) const&;
385 dynamic& at(dynamic const&) &;
386 dynamic at(dynamic const&) &&;
389 * Like 'at', above, except it returns either a pointer to the contained
390 * object or nullptr if it wasn't found. This allows a key to be tested for
391 * containment and retrieved in one operation. Example:
393 * if (auto* found = d.get_ptr(key))
396 * Using these with dynamic objects that are not arrays or objects
397 * will throw a TypeError.
399 const dynamic* get_ptr(dynamic const&) const&;
400 dynamic* get_ptr(dynamic const&) &;
401 dynamic* get_ptr(dynamic const&) && = delete;
404 * This works for access to both objects and arrays.
406 * In the case of an array, the index must be an integer, and this will throw
407 * std::out_of_range if it is less than zero or greater than size().
409 * In the case of an object, the non-const overload inserts a null
410 * value if the key isn't present. The const overload will throw
411 * std::out_of_range if the key is not present.
413 * These functions do not invalidate iterators.
415 dynamic& operator[](dynamic const&) &;
416 dynamic const& operator[](dynamic const&) const&;
417 dynamic operator[](dynamic const&) &&;
420 * Only defined for objects, throws TypeError otherwise.
422 * getDefault will return the value associated with the supplied key, the
423 * supplied default otherwise. setDefault will set the key to the supplied
424 * default if it is not yet set, otherwise leaving it. setDefault returns
425 * a reference to the existing value if present, the new value otherwise.
428 getDefault(const dynamic& k, const dynamic& v = dynamic::object) const&;
429 dynamic getDefault(const dynamic& k, dynamic&& v) const&;
430 dynamic getDefault(const dynamic& k, const dynamic& v = dynamic::object) &&;
431 dynamic getDefault(const dynamic& k, dynamic&& v) &&;
432 template<class K, class V>
433 dynamic& setDefault(K&& k, V&& v);
434 // MSVC 2015 Update 3 needs these extra overloads because if V were a
435 // defaulted template parameter, it causes MSVC to consider v an rvalue
436 // reference rather than a universal reference, resulting in it not being
437 // able to find the correct overload to construct a dynamic with.
439 dynamic& setDefault(K&& k, dynamic&& v);
441 dynamic& setDefault(K&& k, const dynamic& v = dynamic::object);
444 * Resizes an array so it has at n elements, using the supplied
445 * default to fill new elements. Throws TypeError if this dynamic
448 * May invalidate iterators.
452 void resize(std::size_t n, dynamic const& = nullptr);
455 * Inserts the supplied key-value pair to an object, or throws if
456 * it's not an object.
458 * Invalidates iterators.
460 template<class K, class V> void insert(K&&, V&& val);
463 * These functions merge two folly dynamic objects.
464 * The "update" and "update_missing" functions extend the object by
465 * inserting the key/value pairs of mergeObj into the current object.
466 * For update, if key is duplicated between the two objects, it
467 * will overwrite with the value of the object being inserted (mergeObj).
468 * For "update_missing", it will prefer the value in the original object
470 * The "merge" function creates a new object consisting of the key/value
471 * pairs of both mergeObj1 and mergeObj2
472 * If the key is duplicated between the two objects,
473 * it will prefer value in the second object (mergeObj2)
475 void update(const dynamic& mergeObj);
476 void update_missing(const dynamic& other);
477 static dynamic merge(const dynamic& mergeObj1, const dynamic& mergeObj2);
480 * Erase an element from a dynamic object, by key.
482 * Invalidates iterators to the element being erased.
484 * Returns the number of elements erased (i.e. 1 or 0).
486 std::size_t erase(dynamic const& key);
489 * Erase an element from a dynamic object or array, using an
490 * iterator or an iterator range.
492 * In arrays, invalidates iterators to elements after the element
493 * being erased. In objects, invalidates iterators to the elements
496 * Returns a new iterator to the first element beyond any elements
497 * removed, or end() if there are none. (The iteration order does
500 const_iterator erase(const_iterator it);
501 const_iterator erase(const_iterator first, const_iterator last);
503 const_key_iterator erase(const_key_iterator it);
504 const_key_iterator erase(const_key_iterator first, const_key_iterator last);
506 const_value_iterator erase(const_value_iterator it);
507 const_value_iterator erase(const_value_iterator first,
508 const_value_iterator last);
510 const_item_iterator erase(const_item_iterator it);
511 const_item_iterator erase(const_item_iterator first,
512 const_item_iterator last);
514 * Append elements to an array. If this is not an array, throws
517 * Invalidates iterators.
519 void push_back(dynamic const&);
520 void push_back(dynamic&&);
523 * Remove an element from the back of an array. If this is not an array,
526 * Does not invalidate iterators.
531 * Get a hash code. This function is called by a std::hash<>
532 * specialization, also.
534 * Throws TypeError if this is an object, array, or null.
536 std::size_t hash() const;
539 friend struct TypeError;
541 template<class T> struct TypeInfo;
542 template<class T> struct CompareOp;
543 template<class T> struct GetAddrImpl;
544 template<class T> struct PrintImpl;
546 dynamic(Array&& array, PrivateTag);
548 template<class T> T const& get() const;
549 template<class T> T& get();
550 template<class T> T* get_nothrow() & noexcept;
551 template<class T> T const* get_nothrow() const& noexcept;
552 template<class T> T* get_nothrow() && noexcept = delete;
553 template<class T> T* getAddress() noexcept;
554 template<class T> T const* getAddress() const noexcept;
556 template<class T> T asImpl() const;
558 static char const* typeName(Type);
559 void destroy() noexcept;
560 void print(std::ostream&) const;
561 void print_as_pseudo_json(std::ostream&) const; // see json.cpp
566 explicit Data() : nul(nullptr) {}
569 // XXX: gcc does an ICE if we use std::nullptr_t instead of void*
570 // here. See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=50361
579 * Objects are placement new'd here. We have to use a char buffer
580 * because we don't know the type here (std::unordered_map<> with
581 * dynamic would be parameterizing a std:: template with an
582 * incomplete type right now). (Note that in contrast we know it
583 * is ok to do this with fbvector because we own it.)
585 std::aligned_storage<
586 sizeof(std::unordered_map<int,int>),
587 alignof(std::unordered_map<int,int>)
588 >::type objectBuffer;
592 //////////////////////////////////////////////////////////////////////
596 #include <folly/dynamic-inl.h>