Update the folly/README
[folly.git] / folly / dynamic.h
1 /*
2  * Copyright 2012 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 /**
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.
22  *
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.
27  *
28  * Some examples:
29  *
30  *   dynamic twelve = 12;
31  *   dynamic str = "string";
32  *   dynamic map = dynamic::object;
33  *   map[str] = twelve;
34  *   map[str + "another_str"] = { "array", "of", 4, "elements" };
35  *   map.insert("null_element", nullptr);
36  *   ++map[str];
37  *   assert(map[str] == 13);
38  *
39  *   // Building a complex object with a sub array inline:
40  *   dynamic d = dynamic::object
41  *     ("key", "value")
42  *     ("key2", { "a", "array" })
43  *     ;
44  *
45  * Also see folly/json.h for the serialization and deserialization
46  * functions for JSON.
47  *
48  * Note: dynamic is not DefaultConstructible.  Rationale:
49  *
50  *   - The intuitive thing to initialize a defaulted dynamic to would
51  *     be nullptr.
52  *
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
56  *     empty array.
57  *
58  * Additional documentation is in folly/docs/Dynamic.md.
59  *
60  * @author Jordan DeLong <delong.j@fb.com>
61  */
62
63 #ifndef FOLLY_DYNAMIC_H_
64 #define FOLLY_DYNAMIC_H_
65
66 #include <unordered_map>
67 #include <memory>
68 #include <string>
69 #include <utility>
70 #include <ostream>
71 #include <type_traits>
72 #include <initializer_list>
73 #include <cstdint>
74 #include <boost/operators.hpp>
75
76 #include "folly/Traits.h"
77 #include "folly/FBVector.h"
78 #include "folly/FBString.h"
79
80 namespace folly {
81
82 //////////////////////////////////////////////////////////////////////
83
84 struct dynamic;
85 struct TypeError;
86 template<> FOLLY_ASSUME_RELOCATABLE(dynamic);
87
88 //////////////////////////////////////////////////////////////////////
89
90 struct dynamic : private boost::operators<dynamic> {
91   enum Type {
92     NULLT,
93     ARRAY,
94     BOOL,
95     DOUBLE,
96     INT64,
97     OBJECT,
98     STRING,
99   };
100
101   /*
102    * We support direct iteration of arrays, and indirect iteration of objects.
103    * See begin(), end(), keys(), values(), and items() for more.
104    *
105    * Array iterators dereference as the elements in the array.
106    * Object key iterators dereference as the keys in the object.
107    * Object value iterators dereference as the values in the object.
108    * Object item iterators dereference as pairs of (key, value).
109    */
110 private:
111   typedef fbvector<dynamic> Array;
112 public:
113   typedef Array::const_iterator const_iterator;
114   struct const_key_iterator;
115   struct const_value_iterator;
116   struct const_item_iterator;
117
118   /*
119    * Creation routines for making dynamic objects.  Objects are maps
120    * from key to value (so named due to json-related origins here).
121    *
122    * Example:
123    *
124    *   // Make a fairly complex dynamic:
125    *   dynamic d = dynamic::object("key", "value1")
126    *                              ("key2", { "value", "with", 4, "words" });
127    *
128    *   // Build an object in a few steps:
129    *   dynamic d = dynamic::object;
130    *   d["key"] = 12;
131    *   d["something_else"] = { 1, 2, 3, nullptr };
132    */
133 private:
134   struct ObjectMaker;
135
136 public:
137   template<class... Args> static ObjectMaker object(Args&&...);
138
139   /*
140    * String compatibility constructors.
141    */
142   /* implicit */ dynamic(char const* val);
143   /* implicit */ dynamic(std::string const& val);
144
145   /*
146    * This is part of the plumbing for object(), above.  Used to create
147    * a new object dynamic.
148    */
149   /* implicit */ dynamic(ObjectMaker (*)());
150   /* implicit */ dynamic(ObjectMaker const&) = delete;
151   /* implicit */ dynamic(ObjectMaker&&);
152
153   /*
154    * Create a new array from an initializer list.
155    *
156    * For example:
157    *
158    *   dynamic v = { 1, 2, 3, "foo" };
159    */
160   /* implicit */ dynamic(std::initializer_list<dynamic> il);
161
162   /*
163    * Conversion constructors from most of the other types.
164    */
165   template<class T> /* implicit */ dynamic(T t);
166
167   /*
168    * Create a dynamic that is an array of the values from the supplied
169    * iterator range.
170    */
171   template<class Iterator> dynamic(Iterator first, Iterator last);
172
173   dynamic(dynamic const&);
174   dynamic(dynamic&&);
175   ~dynamic();
176
177   /*
178    * "Deep" equality comparison.  This will compare all the way down
179    * an object or array, and is potentially expensive.
180    */
181   bool operator==(dynamic const& o) const;
182
183   /*
184    * For all types except object this returns the natural ordering on
185    * those types.  For objects, we throw TypeError.
186    */
187   bool operator<(dynamic const& o) const;
188
189   /*
190    * General operators.
191    *
192    * These throw TypeError when used with types or type combinations
193    * that don't support them.
194    *
195    * These functions may also throw if you use 64-bit integers with
196    * doubles when the integers are too big to fit in a double.
197    */
198   dynamic& operator+=(dynamic const&);
199   dynamic& operator-=(dynamic const&);
200   dynamic& operator*=(dynamic const&);
201   dynamic& operator/=(dynamic const&);
202   dynamic& operator%=(dynamic const&);
203   dynamic& operator|=(dynamic const&);
204   dynamic& operator&=(dynamic const&);
205   dynamic& operator^=(dynamic const&);
206   dynamic& operator++();
207   dynamic& operator--();
208
209   /*
210    * Assignment from other dynamics.  Because of the implicit conversion
211    * to dynamic from its potential types, you can use this to change the
212    * type pretty intuitively.
213    *
214    * Basic guarantee only.
215    */
216   dynamic& operator=(dynamic const&);
217   dynamic& operator=(dynamic&&);
218
219   /*
220    * For simple dynamics (not arrays or objects), this prints the
221    * value to an std::ostream in the expected way.  Respects the
222    * formatting manipulators that have been sent to the stream
223    * already.
224    *
225    * If the dynamic holds an object or array, this prints them in a
226    * format very similar to JSON.  (It will in fact actually be JSON
227    * as long as the dynamic validly represents a JSON object---i.e. it
228    * can't have non-string keys.)
229    */
230   friend std::ostream& operator<<(std::ostream&, dynamic const&);
231
232   /*
233    * Returns true if this dynamic is of the specified type.
234    */
235   bool isString() const;
236   bool isObject() const;
237   bool isBool() const;
238   bool isNull() const;
239   bool isArray() const;
240   bool isDouble() const;
241   bool isInt() const;
242
243   /*
244    * Returns: isInt() || isDouble().
245    */
246   bool isNumber() const;
247
248   /*
249    * Returns the type of this dynamic.
250    */
251   Type type() const;
252
253   /*
254    * Extract a value while trying to convert to the specified type.
255    * Throws exceptions if we cannot convert from the real type to the
256    * requested type.
257    *
258    * Note you can only use this to access integral types or strings,
259    * since arrays and objects are generally best delt with as a
260    * dynamic.
261    */
262   fbstring asString() const;
263   double   asDouble() const;
264   int64_t  asInt() const;
265   bool     asBool() const;
266
267   /*
268    * Returns: true if this dynamic is null, an empty array, an empty
269    * object, or an empty string.
270    */
271   bool empty() const;
272
273   /*
274    * If this is an array or an object, returns the number of elements
275    * contained.  If it is a string, returns the length.  Otherwise
276    * throws TypeError.
277    */
278   std::size_t size() const;
279
280   /*
281    * You can iterate over the values of the array.  Calling these on
282    * non-arrays will throw a TypeError.
283    */
284   const_iterator begin()  const;
285   const_iterator end()    const;
286
287 private:
288   /*
289    * Helper object returned by keys(), values(), and items().
290    */
291   template <class T> struct IterableProxy;
292
293 public:
294   /*
295    * You can iterate over the keys, values, or items (std::pair of key and
296    * value) in an object.  Calling these on non-objects will throw a TypeError.
297    */
298   IterableProxy<const_key_iterator> keys() const;
299   IterableProxy<const_value_iterator> values() const;
300   IterableProxy<const_item_iterator> items() const;
301
302   /*
303    * AssociativeContainer-style find interface for objects.  Throws if
304    * this is not an object.
305    *
306    * Returns: end() if the key is not present, or an iterator pointing
307    * to the item.
308    */
309   const_item_iterator find(dynamic const&) const;
310
311   /*
312    * If this is an object, returns whether it contains a field with
313    * the given name.  Otherwise throws TypeError.
314    */
315   std::size_t count(dynamic const&) const;
316
317   /*
318    * For objects or arrays, provides access to sub-fields by index or
319    * field name.
320    *
321    * Using these with dynamic objects that are not arrays or objects
322    * will throw a TypeError.  Using an index that is out of range or
323    * object-element that's not present throws std::out_of_range.
324    */
325   dynamic const& at(dynamic const&) const;
326   dynamic&       at(dynamic const&);
327
328   /*
329    * This works for access to both objects and arrays.
330    *
331    * In the case of an array, the index must be an integer, and this will throw
332    * std::out_of_range if it is less than zero or greater than size().
333    *
334    * In the case of an object, the non-const overload inserts a null
335    * value if the key isn't present.  The const overload will throw
336    * std::out_of_range if the key is not present.
337    *
338    * These functions do not invalidate iterators.
339    */
340   dynamic&       operator[](dynamic const&);
341   dynamic const& operator[](dynamic const&) const;
342
343   /*
344    * Only defined for objects, throws TypeError otherwise.
345    *
346    * getDefault will return the value associated with the supplied key, the
347    * supplied default otherwise. setDefault will set the key to the supplied
348    * default if it is not yet set, otherwise leaving it. setDefault returns
349    * a reference to the existing value if present, the new value otherwise.
350    */
351   dynamic
352   getDefault(const dynamic& k, const dynamic& v = dynamic::object) const;
353   dynamic&& getDefault(const dynamic& k, dynamic&& v) const;
354   template<class K, class V = dynamic>
355   dynamic& setDefault(K&& k, V&& v = dynamic::object);
356
357   /*
358    * Resizes an array so it has at n elements, using the supplied
359    * default to fill new elements.  Throws TypeError if this dynamic
360    * is not an array.
361    *
362    * May invalidate iterators.
363    *
364    * Post: size() == n
365    */
366   void resize(std::size_t n, dynamic const& = nullptr);
367
368   /*
369    * Inserts the supplied key-value pair to an object, or throws if
370    * it's not an object.
371    *
372    * Invalidates iterators.
373    */
374   template<class K, class V> void insert(K&&, V&& val);
375
376   /*
377    * Erase an element from a dynamic object, by key.
378    *
379    * Invalidates iterators to the element being erased.
380    *
381    * Returns the number of elements erased (i.e. 1 or 0).
382    */
383   std::size_t erase(dynamic const& key);
384
385   /*
386    * Erase an element from a dynamic object or array, using an
387    * iterator or an iterator range.
388    *
389    * In arrays, invalidates iterators to elements after the element
390    * being erased.  In objects, invalidates iterators to the elements
391    * being erased.
392    *
393    * Returns a new iterator to the first element beyond any elements
394    * removed, or end() if there are none.  (The iteration order does
395    * not change.)
396    */
397   const_iterator erase(const_iterator it);
398   const_iterator erase(const_iterator first, const_iterator last);
399
400   const_key_iterator erase(const_key_iterator it);
401   const_key_iterator erase(const_key_iterator first, const_key_iterator last);
402
403   const_value_iterator erase(const_value_iterator it);
404   const_value_iterator erase(const_value_iterator first,
405                              const_value_iterator last);
406
407   const_item_iterator erase(const_item_iterator it);
408   const_item_iterator erase(const_item_iterator first,
409                             const_item_iterator last);
410   /*
411    * Append elements to an array.  If this is not an array, throws
412    * TypeError.
413    *
414    * Invalidates iterators.
415    */
416   void push_back(dynamic const&);
417   void push_back(dynamic&&);
418
419   /*
420    * Get a hash code.  This function is called by a std::hash<>
421    * specialization, also.
422    *
423    * Throws TypeError if this is an object, array, or null.
424    */
425   std::size_t hash() const;
426
427 private:
428   friend struct TypeError;
429   struct ObjectImpl;
430   struct ObjectMaker;
431   template<class T> struct TypeInfo;
432   template<class T> struct CompareOp;
433   template<class T> struct GetAddrImpl;
434   template<class T> struct PrintImpl;
435
436   template<class T> T const& get() const;
437   template<class T> T&       get();
438   template<class T> T*       get_nothrow();
439   template<class T> T const* get_nothrow() const;
440   template<class T> T*       getAddress();
441   template<class T> T const* getAddress() const;
442
443   template<class T> T asImpl() const;
444
445   static char const* typeName(Type);
446   void destroy();
447   void print(std::ostream&) const;
448   void print_as_pseudo_json(std::ostream&) const; // see json.cpp
449
450 private:
451   Type type_;
452   union Data {
453     explicit Data() : nul(nullptr) {}
454     ~Data() {}
455
456     // XXX: gcc does an ICE if we use std::nullptr_t instead of void*
457     // here.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=50361
458     void* nul;
459     Array array;
460     bool boolean;
461     double doubl;
462     int64_t integer;
463     fbstring string;
464
465     /*
466      * Objects are placement new'd here.  We have to use a char buffer
467      * because we don't know the type here (std::unordered_map<> with
468      * dynamic would be parameterizing a std:: template with an
469      * incomplete type right now).  (Note that in contrast we know it
470      * is ok to do this with fbvector because we own it.)
471      */
472     typename std::aligned_storage<
473       sizeof(std::unordered_map<int,int>),
474       alignof(std::unordered_map<int,int>)
475     >::type objectBuffer;
476   } u_;
477 };
478
479 //////////////////////////////////////////////////////////////////////
480
481 }
482
483 #include "folly/dynamic-inl.h"
484
485 #endif