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