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