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