Removed an unneeded typename in dynamic.h
[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
171   /*
172    * Conversion constructors from most of the other types.
173    */
174   template<class T> /* implicit */ dynamic(T t);
175
176   /*
177    * Create a dynamic that is an array of the values from the supplied
178    * iterator range.
179    */
180   template<class Iterator> dynamic(Iterator first, Iterator last);
181
182   dynamic(dynamic const&);
183   dynamic(dynamic&&) noexcept;
184   ~dynamic() noexcept;
185
186   /*
187    * "Deep" equality comparison.  This will compare all the way down
188    * an object or array, and is potentially expensive.
189    */
190   bool operator==(dynamic const& o) const;
191
192   /*
193    * For all types except object this returns the natural ordering on
194    * those types.  For objects, we throw TypeError.
195    */
196   bool operator<(dynamic const& o) const;
197
198   /*
199    * General operators.
200    *
201    * These throw TypeError when used with types or type combinations
202    * that don't support them.
203    *
204    * These functions may also throw if you use 64-bit integers with
205    * doubles when the integers are too big to fit in a double.
206    */
207   dynamic& operator+=(dynamic const&);
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++();
216   dynamic& operator--();
217
218   /*
219    * Assignment from other dynamics.  Because of the implicit conversion
220    * to dynamic from its potential types, you can use this to change the
221    * type pretty intuitively.
222    *
223    * Basic guarantee only.
224    */
225   dynamic& operator=(dynamic const&);
226   dynamic& operator=(dynamic&&) noexcept;
227
228   /*
229    * For simple dynamics (not arrays or objects), this prints the
230    * value to an std::ostream in the expected way.  Respects the
231    * formatting manipulators that have been sent to the stream
232    * already.
233    *
234    * If the dynamic holds an object or array, this prints them in a
235    * format very similar to JSON.  (It will in fact actually be JSON
236    * as long as the dynamic validly represents a JSON object---i.e. it
237    * can't have non-string keys.)
238    */
239   friend std::ostream& operator<<(std::ostream&, dynamic const&);
240
241   /*
242    * Returns true if this dynamic is of the specified type.
243    */
244   bool isString() const;
245   bool isObject() const;
246   bool isBool() const;
247   bool isNull() const;
248   bool isArray() const;
249   bool isDouble() const;
250   bool isInt() const;
251
252   /*
253    * Returns: isInt() || isDouble().
254    */
255   bool isNumber() const;
256
257   /*
258    * Returns the type of this dynamic.
259    */
260   Type type() const;
261
262   /*
263    * Returns the type of this dynamic as a printable string.
264    */
265   const char* typeName() const;
266
267   /*
268    * Extract a value while trying to convert to the specified type.
269    * Throws exceptions if we cannot convert from the real type to the
270    * requested type.
271    *
272    * Note you can only use this to access integral types or strings,
273    * since arrays and objects are generally best dealt with as a
274    * dynamic.
275    */
276   fbstring asString() const;
277   double   asDouble() const;
278   int64_t  asInt() const;
279   bool     asBool() const;
280
281   /*
282    * Extract the value stored in this dynamic without type conversion.
283    *
284    * These will throw a TypeError if the dynamic has a different type.
285    */
286   const fbstring& getString() const;
287   double          getDouble() const;
288   int64_t         getInt() const;
289   bool            getBool() const;
290   fbstring& getString();
291   double&   getDouble();
292   int64_t&  getInt();
293   bool&     getBool();
294
295   /*
296    * It is occasionally useful to access a string's internal pointer
297    * directly, without the type conversion of `asString()`.
298    *
299    * These will throw a TypeError if the dynamic is not a string.
300    */
301   const char* data()  const&;
302   const char* data()  && = delete;
303   const char* c_str() const&;
304   const char* c_str() && = delete;
305   StringPiece stringPiece() const;
306
307   /*
308    * Returns: true if this dynamic is null, an empty array, an empty
309    * object, or an empty string.
310    */
311   bool empty() const;
312
313   /*
314    * If this is an array or an object, returns the number of elements
315    * contained.  If it is a string, returns the length.  Otherwise
316    * throws TypeError.
317    */
318   std::size_t size() const;
319
320   /*
321    * You can iterate over the values of the array.  Calling these on
322    * non-arrays will throw a TypeError.
323    */
324   const_iterator begin()  const;
325   const_iterator end()    const;
326
327 private:
328   /*
329    * Helper object returned by keys(), values(), and items().
330    */
331   template <class T> struct IterableProxy;
332
333 public:
334   /*
335    * You can iterate over the keys, values, or items (std::pair of key and
336    * value) in an object.  Calling these on non-objects will throw a TypeError.
337    */
338   IterableProxy<const_key_iterator> keys() const;
339   IterableProxy<const_value_iterator> values() const;
340   IterableProxy<const_item_iterator> items() const;
341
342   /*
343    * AssociativeContainer-style find interface for objects.  Throws if
344    * this is not an object.
345    *
346    * Returns: items().end() if the key is not present, or a
347    * const_item_iterator pointing to the item.
348    */
349   const_item_iterator find(dynamic const&) const;
350
351   /*
352    * If this is an object, returns whether it contains a field with
353    * the given name.  Otherwise throws TypeError.
354    */
355   std::size_t count(dynamic const&) const;
356
357   /*
358    * For objects or arrays, provides access to sub-fields by index or
359    * field name.
360    *
361    * Using these with dynamic objects that are not arrays or objects
362    * will throw a TypeError.  Using an index that is out of range or
363    * object-element that's not present throws std::out_of_range.
364    */
365   dynamic const& at(dynamic const&) const;
366   dynamic&       at(dynamic const&);
367
368   /*
369    * Like 'at', above, except it returns either a pointer to the contained
370    * object or nullptr if it wasn't found. This allows a key to be tested for
371    * containment and retrieved in one operation. Example:
372    *
373    *   if (auto* found = d.get_ptr(key))
374    *     // use *found;
375    *
376    * Using these with dynamic objects that are not arrays or objects
377    * will throw a TypeError.
378    */
379   const dynamic* get_ptr(dynamic const&) const&;
380   dynamic* get_ptr(dynamic const&) &;
381   dynamic* get_ptr(dynamic const&) && = delete;
382
383   /*
384    * This works for access to both objects and arrays.
385    *
386    * In the case of an array, the index must be an integer, and this will throw
387    * std::out_of_range if it is less than zero or greater than size().
388    *
389    * In the case of an object, the non-const overload inserts a null
390    * value if the key isn't present.  The const overload will throw
391    * std::out_of_range if the key is not present.
392    *
393    * These functions do not invalidate iterators.
394    */
395   dynamic&       operator[](dynamic const&);
396   dynamic const& operator[](dynamic const&) const;
397
398   /*
399    * Only defined for objects, throws TypeError otherwise.
400    *
401    * getDefault will return the value associated with the supplied key, the
402    * supplied default otherwise. setDefault will set the key to the supplied
403    * default if it is not yet set, otherwise leaving it. setDefault returns
404    * a reference to the existing value if present, the new value otherwise.
405    */
406   dynamic
407   getDefault(const dynamic& k, const dynamic& v = dynamic::object) const;
408   dynamic&& getDefault(const dynamic& k, dynamic&& v) const;
409   template<class K, class V = dynamic>
410   dynamic& setDefault(K&& k, V&& v = dynamic::object);
411
412   /*
413    * Resizes an array so it has at n elements, using the supplied
414    * default to fill new elements.  Throws TypeError if this dynamic
415    * is not an array.
416    *
417    * May invalidate iterators.
418    *
419    * Post: size() == n
420    */
421   void resize(std::size_t n, dynamic const& = nullptr);
422
423   /*
424    * Inserts the supplied key-value pair to an object, or throws if
425    * it's not an object.
426    *
427    * Invalidates iterators.
428    */
429   template<class K, class V> void insert(K&&, V&& val);
430
431   /*
432    * Erase an element from a dynamic object, by key.
433    *
434    * Invalidates iterators to the element being erased.
435    *
436    * Returns the number of elements erased (i.e. 1 or 0).
437    */
438   std::size_t erase(dynamic const& key);
439
440   /*
441    * Erase an element from a dynamic object or array, using an
442    * iterator or an iterator range.
443    *
444    * In arrays, invalidates iterators to elements after the element
445    * being erased.  In objects, invalidates iterators to the elements
446    * being erased.
447    *
448    * Returns a new iterator to the first element beyond any elements
449    * removed, or end() if there are none.  (The iteration order does
450    * not change.)
451    */
452   const_iterator erase(const_iterator it);
453   const_iterator erase(const_iterator first, const_iterator last);
454
455   const_key_iterator erase(const_key_iterator it);
456   const_key_iterator erase(const_key_iterator first, const_key_iterator last);
457
458   const_value_iterator erase(const_value_iterator it);
459   const_value_iterator erase(const_value_iterator first,
460                              const_value_iterator last);
461
462   const_item_iterator erase(const_item_iterator it);
463   const_item_iterator erase(const_item_iterator first,
464                             const_item_iterator last);
465   /*
466    * Append elements to an array.  If this is not an array, throws
467    * TypeError.
468    *
469    * Invalidates iterators.
470    */
471   void push_back(dynamic const&);
472   void push_back(dynamic&&);
473
474   /*
475    * Remove an element from the back of an array.  If this is not an array,
476    * throws TypeError.
477    *
478    * Does not invalidate iterators.
479    */
480   void pop_back();
481
482   /*
483    * Get a hash code.  This function is called by a std::hash<>
484    * specialization, also.
485    *
486    * Throws TypeError if this is an object, array, or null.
487    */
488   std::size_t hash() const;
489
490 private:
491   friend struct TypeError;
492   struct ObjectImpl;
493   template<class T> struct TypeInfo;
494   template<class T> struct CompareOp;
495   template<class T> struct GetAddrImpl;
496   template<class T> struct PrintImpl;
497
498   template<class T> T const& get() const;
499   template<class T> T&       get();
500   template<class T> T*       get_nothrow() & noexcept;
501   template<class T> T const* get_nothrow() const& noexcept;
502   template<class T> T*       get_nothrow() && noexcept = delete;
503   template<class T> T*       getAddress() noexcept;
504   template<class T> T const* getAddress() const noexcept;
505
506   template<class T> T asImpl() const;
507
508   static char const* typeName(Type);
509   void destroy() noexcept;
510   void print(std::ostream&) const;
511   void print_as_pseudo_json(std::ostream&) const; // see json.cpp
512
513 private:
514   Type type_;
515   union Data {
516     explicit Data() : nul(nullptr) {}
517     ~Data() {}
518
519     // XXX: gcc does an ICE if we use std::nullptr_t instead of void*
520     // here.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=50361
521     void* nul;
522     Array array;
523     bool boolean;
524     double doubl;
525     int64_t integer;
526     fbstring string;
527
528     /*
529      * Objects are placement new'd here.  We have to use a char buffer
530      * because we don't know the type here (std::unordered_map<> with
531      * dynamic would be parameterizing a std:: template with an
532      * incomplete type right now).  (Note that in contrast we know it
533      * is ok to do this with fbvector because we own it.)
534      */
535     std::aligned_storage<
536       sizeof(std::unordered_map<int,int>),
537       alignof(std::unordered_map<int,int>)
538     >::type objectBuffer;
539   } u_;
540 };
541
542 //////////////////////////////////////////////////////////////////////
543
544 }
545
546 #include <folly/dynamic-inl.h>
547
548 #endif