• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // This file specifies a recursive data storage class called Value intended for
6 // storing settings and other persistable data.
7 //
8 // A Value represents something that can be stored in JSON or passed to/from
9 // JavaScript. As such, it is NOT a generalized variant type, since only the
10 // types supported by JavaScript/JSON are supported.
11 //
12 // IN PARTICULAR this means that there is no support for int64_t or unsigned
13 // numbers. Writing JSON with such types would violate the spec. If you need
14 // something like this, either use a double or make a string value containing
15 // the number you want.
16 
17 #ifndef BASE_VALUES_H_
18 #define BASE_VALUES_H_
19 
20 #include <stddef.h>
21 #include <stdint.h>
22 
23 #include <iosfwd>
24 #include <map>
25 #include <memory>
26 #include <string>
27 #include <utility>
28 #include <vector>
29 
30 #include "base/base_export.h"
31 #include "base/compiler_specific.h"
32 #include "base/macros.h"
33 #include "base/strings/string16.h"
34 #include "base/strings/string_piece.h"
35 
36 namespace base {
37 
38 class BinaryValue;
39 class DictionaryValue;
40 class FundamentalValue;
41 class ListValue;
42 class StringValue;
43 class Value;
44 
45 // The Value class is the base class for Values. A Value can be instantiated
46 // via the Create*Value() factory methods, or by directly creating instances of
47 // the subclasses.
48 //
49 // See the file-level comment above for more information.
50 class BASE_EXPORT Value {
51  public:
52   enum Type {
53     TYPE_NULL = 0,
54     TYPE_BOOLEAN,
55     TYPE_INTEGER,
56     TYPE_DOUBLE,
57     TYPE_STRING,
58     TYPE_BINARY,
59     TYPE_DICTIONARY,
60     TYPE_LIST
61     // Note: Do not add more types. See the file-level comment above for why.
62   };
63 
64   virtual ~Value();
65 
66   static std::unique_ptr<Value> CreateNullValue();
67 
68   // Returns the type of the value stored by the current Value object.
69   // Each type will be implemented by only one subclass of Value, so it's
70   // safe to use the Type to determine whether you can cast from
71   // Value* to (Implementing Class)*.  Also, a Value object never changes
72   // its type after construction.
GetType()73   Type GetType() const { return type_; }
74 
75   // Returns true if the current object represents a given type.
IsType(Type type)76   bool IsType(Type type) const { return type == type_; }
77 
78   // These methods allow the convenient retrieval of the contents of the Value.
79   // If the current object can be converted into the given type, the value is
80   // returned through the |out_value| parameter and true is returned;
81   // otherwise, false is returned and |out_value| is unchanged.
82   virtual bool GetAsBoolean(bool* out_value) const;
83   virtual bool GetAsInteger(int* out_value) const;
84   virtual bool GetAsDouble(double* out_value) const;
85   virtual bool GetAsString(std::string* out_value) const;
86   virtual bool GetAsString(string16* out_value) const;
87   virtual bool GetAsString(const StringValue** out_value) const;
88   virtual bool GetAsBinary(const BinaryValue** out_value) const;
89   virtual bool GetAsList(ListValue** out_value);
90   virtual bool GetAsList(const ListValue** out_value) const;
91   virtual bool GetAsDictionary(DictionaryValue** out_value);
92   virtual bool GetAsDictionary(const DictionaryValue** out_value) const;
93   // Note: Do not add more types. See the file-level comment above for why.
94 
95   // This creates a deep copy of the entire Value tree, and returns a pointer
96   // to the copy.  The caller gets ownership of the copy, of course.
97   //
98   // Subclasses return their own type directly in their overrides;
99   // this works because C++ supports covariant return types.
100   virtual Value* DeepCopy() const;
101   // Preferred version of DeepCopy. TODO(estade): remove the above.
102   std::unique_ptr<Value> CreateDeepCopy() const;
103 
104   // Compares if two Value objects have equal contents.
105   virtual bool Equals(const Value* other) const;
106 
107   // Compares if two Value objects have equal contents. Can handle NULLs.
108   // NULLs are considered equal but different from Value::CreateNullValue().
109   static bool Equals(const Value* a, const Value* b);
110 
111  protected:
112   // These aren't safe for end-users, but they are useful for subclasses.
113   explicit Value(Type type);
114   Value(const Value& that);
115   Value& operator=(const Value& that);
116 
117  private:
118   Type type_;
119 };
120 
121 // FundamentalValue represents the simple fundamental types of values.
122 class BASE_EXPORT FundamentalValue : public Value {
123  public:
124   explicit FundamentalValue(bool in_value);
125   explicit FundamentalValue(int in_value);
126   explicit FundamentalValue(double in_value);
127   ~FundamentalValue() override;
128 
129   // Overridden from Value:
130   bool GetAsBoolean(bool* out_value) const override;
131   bool GetAsInteger(int* out_value) const override;
132   // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
133   // doubles.
134   bool GetAsDouble(double* out_value) const override;
135   FundamentalValue* DeepCopy() const override;
136   bool Equals(const Value* other) const override;
137 
138  private:
139   union {
140     bool boolean_value_;
141     int integer_value_;
142     double double_value_;
143   };
144 };
145 
146 class BASE_EXPORT StringValue : public Value {
147  public:
148   // Initializes a StringValue with a UTF-8 narrow character string.
149   explicit StringValue(const std::string& in_value);
150 
151   // Initializes a StringValue with a string16.
152   explicit StringValue(const string16& in_value);
153 
154   ~StringValue() override;
155 
156   // Returns |value_| as a pointer or reference.
157   std::string* GetString();
158   const std::string& GetString() const;
159 
160   // Overridden from Value:
161   bool GetAsString(std::string* out_value) const override;
162   bool GetAsString(string16* out_value) const override;
163   bool GetAsString(const StringValue** out_value) const override;
164   StringValue* DeepCopy() const override;
165   bool Equals(const Value* other) const override;
166 
167  private:
168   std::string value_;
169 };
170 
171 class BASE_EXPORT BinaryValue: public Value {
172  public:
173   // Creates a BinaryValue with a null buffer and size of 0.
174   BinaryValue();
175 
176   // Creates a BinaryValue, taking ownership of the bytes pointed to by
177   // |buffer|.
178   BinaryValue(std::unique_ptr<char[]> buffer, size_t size);
179 
180   ~BinaryValue() override;
181 
182   // For situations where you want to keep ownership of your buffer, this
183   // factory method creates a new BinaryValue by copying the contents of the
184   // buffer that's passed in.
185   static std::unique_ptr<BinaryValue> CreateWithCopiedBuffer(const char* buffer,
186                                                              size_t size);
187 
GetSize()188   size_t GetSize() const { return size_; }
189 
190   // May return NULL.
GetBuffer()191   char* GetBuffer() { return buffer_.get(); }
GetBuffer()192   const char* GetBuffer() const { return buffer_.get(); }
193 
194   // Overridden from Value:
195   bool GetAsBinary(const BinaryValue** out_value) const override;
196   BinaryValue* DeepCopy() const override;
197   bool Equals(const Value* other) const override;
198 
199  private:
200   std::unique_ptr<char[]> buffer_;
201   size_t size_;
202 
203   DISALLOW_COPY_AND_ASSIGN(BinaryValue);
204 };
205 
206 // DictionaryValue provides a key-value dictionary with (optional) "path"
207 // parsing for recursive access; see the comment at the top of the file. Keys
208 // are |std::string|s and should be UTF-8 encoded.
209 class BASE_EXPORT DictionaryValue : public Value {
210  public:
211   using Storage = std::map<std::string, std::unique_ptr<Value>>;
212   // Returns |value| if it is a dictionary, nullptr otherwise.
213   static std::unique_ptr<DictionaryValue> From(std::unique_ptr<Value> value);
214 
215   DictionaryValue();
216   ~DictionaryValue() override;
217 
218   // Overridden from Value:
219   bool GetAsDictionary(DictionaryValue** out_value) override;
220   bool GetAsDictionary(const DictionaryValue** out_value) const override;
221 
222   // Returns true if the current dictionary has a value for the given key.
223   bool HasKey(const std::string& key) const;
224 
225   // Returns the number of Values in this dictionary.
size()226   size_t size() const { return dictionary_.size(); }
227 
228   // Returns whether the dictionary is empty.
empty()229   bool empty() const { return dictionary_.empty(); }
230 
231   // Clears any current contents of this dictionary.
232   void Clear();
233 
234   // Sets the Value associated with the given path starting from this object.
235   // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
236   // into the next DictionaryValue down.  Obviously, "." can't be used
237   // within a key, but there are no other restrictions on keys.
238   // If the key at any step of the way doesn't exist, or exists but isn't
239   // a DictionaryValue, a new DictionaryValue will be created and attached
240   // to the path in that location. |in_value| must be non-null.
241   void Set(const std::string& path, std::unique_ptr<Value> in_value);
242   // Deprecated version of the above. TODO(estade): remove.
243   void Set(const std::string& path, Value* in_value);
244 
245   // Convenience forms of Set().  These methods will replace any existing
246   // value at that path, even if it has a different type.
247   void SetBoolean(const std::string& path, bool in_value);
248   void SetInteger(const std::string& path, int in_value);
249   void SetDouble(const std::string& path, double in_value);
250   void SetString(const std::string& path, const std::string& in_value);
251   void SetString(const std::string& path, const string16& in_value);
252 
253   // Like Set(), but without special treatment of '.'.  This allows e.g. URLs to
254   // be used as paths.
255   void SetWithoutPathExpansion(const std::string& key,
256                                std::unique_ptr<Value> in_value);
257   // Deprecated version of the above. TODO(estade): remove.
258   void SetWithoutPathExpansion(const std::string& key, Value* in_value);
259 
260   // Convenience forms of SetWithoutPathExpansion().
261   void SetBooleanWithoutPathExpansion(const std::string& path, bool in_value);
262   void SetIntegerWithoutPathExpansion(const std::string& path, int in_value);
263   void SetDoubleWithoutPathExpansion(const std::string& path, double in_value);
264   void SetStringWithoutPathExpansion(const std::string& path,
265                                      const std::string& in_value);
266   void SetStringWithoutPathExpansion(const std::string& path,
267                                      const string16& in_value);
268 
269   // Gets the Value associated with the given path starting from this object.
270   // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
271   // into the next DictionaryValue down.  If the path can be resolved
272   // successfully, the value for the last key in the path will be returned
273   // through the |out_value| parameter, and the function will return true.
274   // Otherwise, it will return false and |out_value| will be untouched.
275   // Note that the dictionary always owns the value that's returned.
276   // |out_value| is optional and will only be set if non-NULL.
277   bool Get(StringPiece path, const Value** out_value) const;
278   bool Get(StringPiece path, Value** out_value);
279 
280   // These are convenience forms of Get().  The value will be retrieved
281   // and the return value will be true if the path is valid and the value at
282   // the end of the path can be returned in the form specified.
283   // |out_value| is optional and will only be set if non-NULL.
284   bool GetBoolean(const std::string& path, bool* out_value) const;
285   bool GetInteger(const std::string& path, int* out_value) const;
286   // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
287   // doubles.
288   bool GetDouble(const std::string& path, double* out_value) const;
289   bool GetString(const std::string& path, std::string* out_value) const;
290   bool GetString(const std::string& path, string16* out_value) const;
291   bool GetStringASCII(const std::string& path, std::string* out_value) const;
292   bool GetBinary(const std::string& path, const BinaryValue** out_value) const;
293   bool GetBinary(const std::string& path, BinaryValue** out_value);
294   bool GetDictionary(StringPiece path,
295                      const DictionaryValue** out_value) const;
296   bool GetDictionary(StringPiece path, DictionaryValue** out_value);
297   bool GetList(const std::string& path, const ListValue** out_value) const;
298   bool GetList(const std::string& path, ListValue** out_value);
299 
300   // Like Get(), but without special treatment of '.'.  This allows e.g. URLs to
301   // be used as paths.
302   bool GetWithoutPathExpansion(const std::string& key,
303                                const Value** out_value) const;
304   bool GetWithoutPathExpansion(const std::string& key, Value** out_value);
305   bool GetBooleanWithoutPathExpansion(const std::string& key,
306                                       bool* out_value) const;
307   bool GetIntegerWithoutPathExpansion(const std::string& key,
308                                       int* out_value) const;
309   bool GetDoubleWithoutPathExpansion(const std::string& key,
310                                      double* out_value) const;
311   bool GetStringWithoutPathExpansion(const std::string& key,
312                                      std::string* out_value) const;
313   bool GetStringWithoutPathExpansion(const std::string& key,
314                                      string16* out_value) const;
315   bool GetDictionaryWithoutPathExpansion(
316       const std::string& key,
317       const DictionaryValue** out_value) const;
318   bool GetDictionaryWithoutPathExpansion(const std::string& key,
319                                          DictionaryValue** out_value);
320   bool GetListWithoutPathExpansion(const std::string& key,
321                                    const ListValue** out_value) const;
322   bool GetListWithoutPathExpansion(const std::string& key,
323                                    ListValue** out_value);
324 
325   // Removes the Value with the specified path from this dictionary (or one
326   // of its child dictionaries, if the path is more than just a local key).
327   // If |out_value| is non-NULL, the removed Value will be passed out via
328   // |out_value|.  If |out_value| is NULL, the removed value will be deleted.
329   // This method returns true if |path| is a valid path; otherwise it will
330   // return false and the DictionaryValue object will be unchanged.
331   virtual bool Remove(const std::string& path,
332                       std::unique_ptr<Value>* out_value);
333 
334   // Like Remove(), but without special treatment of '.'.  This allows e.g. URLs
335   // to be used as paths.
336   virtual bool RemoveWithoutPathExpansion(const std::string& key,
337                                           std::unique_ptr<Value>* out_value);
338 
339   // Removes a path, clearing out all dictionaries on |path| that remain empty
340   // after removing the value at |path|.
341   virtual bool RemovePath(const std::string& path,
342                           std::unique_ptr<Value>* out_value);
343 
344   // Makes a copy of |this| but doesn't include empty dictionaries and lists in
345   // the copy.  This never returns NULL, even if |this| itself is empty.
346   std::unique_ptr<DictionaryValue> DeepCopyWithoutEmptyChildren() const;
347 
348   // Merge |dictionary| into this dictionary. This is done recursively, i.e. any
349   // sub-dictionaries will be merged as well. In case of key collisions, the
350   // passed in dictionary takes precedence and data already present will be
351   // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
352   // be freed any time after this call.
353   void MergeDictionary(const DictionaryValue* dictionary);
354 
355   // Swaps contents with the |other| dictionary.
356   virtual void Swap(DictionaryValue* other);
357 
358   // This class provides an iterator over both keys and values in the
359   // dictionary.  It can't be used to modify the dictionary.
360   class BASE_EXPORT Iterator {
361    public:
362     explicit Iterator(const DictionaryValue& target);
363     Iterator(const Iterator& other);
364     ~Iterator();
365 
IsAtEnd()366     bool IsAtEnd() const { return it_ == target_.dictionary_.end(); }
Advance()367     void Advance() { ++it_; }
368 
key()369     const std::string& key() const { return it_->first; }
value()370     const Value& value() const { return *it_->second; }
371 
372    private:
373     const DictionaryValue& target_;
374     Storage::const_iterator it_;
375   };
376 
377   // Overridden from Value:
378   DictionaryValue* DeepCopy() const override;
379   // Preferred version of DeepCopy. TODO(estade): remove the above.
380   std::unique_ptr<DictionaryValue> CreateDeepCopy() const;
381   bool Equals(const Value* other) const override;
382 
383  private:
384   Storage dictionary_;
385 
386   DISALLOW_COPY_AND_ASSIGN(DictionaryValue);
387 };
388 
389 // This type of Value represents a list of other Value values.
390 class BASE_EXPORT ListValue : public Value {
391  public:
392   using Storage = std::vector<std::unique_ptr<Value>>;
393   using const_iterator = Storage::const_iterator;
394   using iterator = Storage::iterator;
395 
396   // Returns |value| if it is a list, nullptr otherwise.
397   static std::unique_ptr<ListValue> From(std::unique_ptr<Value> value);
398 
399   ListValue();
400   ~ListValue() override;
401 
402   // Clears the contents of this ListValue
403   void Clear();
404 
405   // Returns the number of Values in this list.
GetSize()406   size_t GetSize() const { return list_.size(); }
407 
408   // Returns whether the list is empty.
empty()409   bool empty() const { return list_.empty(); }
410 
411   // Sets the list item at the given index to be the Value specified by
412   // the value given.  If the index beyond the current end of the list, null
413   // Values will be used to pad out the list.
414   // Returns true if successful, or false if the index was negative or
415   // the value is a null pointer.
416   bool Set(size_t index, Value* in_value);
417   // Preferred version of the above. TODO(estade): remove the above.
418   bool Set(size_t index, std::unique_ptr<Value> in_value);
419 
420   // Gets the Value at the given index.  Modifies |out_value| (and returns true)
421   // only if the index falls within the current list range.
422   // Note that the list always owns the Value passed out via |out_value|.
423   // |out_value| is optional and will only be set if non-NULL.
424   bool Get(size_t index, const Value** out_value) const;
425   bool Get(size_t index, Value** out_value);
426 
427   // Convenience forms of Get().  Modifies |out_value| (and returns true)
428   // only if the index is valid and the Value at that index can be returned
429   // in the specified form.
430   // |out_value| is optional and will only be set if non-NULL.
431   bool GetBoolean(size_t index, bool* out_value) const;
432   bool GetInteger(size_t index, int* out_value) const;
433   // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
434   // doubles.
435   bool GetDouble(size_t index, double* out_value) const;
436   bool GetString(size_t index, std::string* out_value) const;
437   bool GetString(size_t index, string16* out_value) const;
438   bool GetBinary(size_t index, const BinaryValue** out_value) const;
439   bool GetBinary(size_t index, BinaryValue** out_value);
440   bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
441   bool GetDictionary(size_t index, DictionaryValue** out_value);
442   bool GetList(size_t index, const ListValue** out_value) const;
443   bool GetList(size_t index, ListValue** out_value);
444 
445   // Removes the Value with the specified index from this list.
446   // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
447   // passed out via |out_value|.  If |out_value| is NULL, the removed value will
448   // be deleted.  This method returns true if |index| is valid; otherwise
449   // it will return false and the ListValue object will be unchanged.
450   virtual bool Remove(size_t index, std::unique_ptr<Value>* out_value);
451 
452   // Removes the first instance of |value| found in the list, if any, and
453   // deletes it. |index| is the location where |value| was found. Returns false
454   // if not found.
455   bool Remove(const Value& value, size_t* index);
456 
457   // Removes the element at |iter|. If |out_value| is NULL, the value will be
458   // deleted, otherwise ownership of the value is passed back to the caller.
459   // Returns an iterator pointing to the location of the element that
460   // followed the erased element.
461   iterator Erase(iterator iter, std::unique_ptr<Value>* out_value);
462 
463   // Appends a Value to the end of the list.
464   void Append(std::unique_ptr<Value> in_value);
465   // Deprecated version of the above. TODO(estade): remove.
466   void Append(Value* in_value);
467 
468   // Convenience forms of Append.
469   void AppendBoolean(bool in_value);
470   void AppendInteger(int in_value);
471   void AppendDouble(double in_value);
472   void AppendString(const std::string& in_value);
473   void AppendString(const string16& in_value);
474   void AppendStrings(const std::vector<std::string>& in_values);
475   void AppendStrings(const std::vector<string16>& in_values);
476 
477   // Appends a Value if it's not already present. Takes ownership of the
478   // |in_value|. Returns true if successful, or false if the value was already
479   // present. If the value was already present the |in_value| is deleted.
480   bool AppendIfNotPresent(Value* in_value);
481 
482   // Insert a Value at index.
483   // Returns true if successful, or false if the index was out of range.
484   bool Insert(size_t index, Value* in_value);
485 
486   // Searches for the first instance of |value| in the list using the Equals
487   // method of the Value type.
488   // Returns a const_iterator to the found item or to end() if none exists.
489   const_iterator Find(const Value& value) const;
490 
491   // Swaps contents with the |other| list.
492   virtual void Swap(ListValue* other);
493 
494   // Iteration.
begin()495   iterator begin() { return list_.begin(); }
end()496   iterator end() { return list_.end(); }
497 
begin()498   const_iterator begin() const { return list_.begin(); }
end()499   const_iterator end() const { return list_.end(); }
500 
501   // Overridden from Value:
502   bool GetAsList(ListValue** out_value) override;
503   bool GetAsList(const ListValue** out_value) const override;
504   ListValue* DeepCopy() const override;
505   bool Equals(const Value* other) const override;
506 
507   // Preferred version of DeepCopy. TODO(estade): remove DeepCopy.
508   std::unique_ptr<ListValue> CreateDeepCopy() const;
509 
510  private:
511   Storage list_;
512 
513   DISALLOW_COPY_AND_ASSIGN(ListValue);
514 };
515 
516 // This interface is implemented by classes that know how to serialize
517 // Value objects.
518 class BASE_EXPORT ValueSerializer {
519  public:
520   virtual ~ValueSerializer();
521 
522   virtual bool Serialize(const Value& root) = 0;
523 };
524 
525 // This interface is implemented by classes that know how to deserialize Value
526 // objects.
527 class BASE_EXPORT ValueDeserializer {
528  public:
529   virtual ~ValueDeserializer();
530 
531   // This method deserializes the subclass-specific format into a Value object.
532   // If the return value is non-NULL, the caller takes ownership of returned
533   // Value. If the return value is NULL, and if error_code is non-NULL,
534   // error_code will be set with the underlying error.
535   // If |error_message| is non-null, it will be filled in with a formatted
536   // error message including the location of the error if appropriate.
537   virtual std::unique_ptr<Value> Deserialize(int* error_code,
538                                              std::string* error_str) = 0;
539 };
540 
541 // Stream operator so Values can be used in assertion statements.  In order that
542 // gtest uses this operator to print readable output on test failures, we must
543 // override each specific type. Otherwise, the default template implementation
544 // is preferred over an upcast.
545 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
546 
547 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
548                                             const FundamentalValue& value) {
549   return out << static_cast<const Value&>(value);
550 }
551 
552 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
553                                             const StringValue& value) {
554   return out << static_cast<const Value&>(value);
555 }
556 
557 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
558                                             const DictionaryValue& value) {
559   return out << static_cast<const Value&>(value);
560 }
561 
562 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
563                                             const ListValue& value) {
564   return out << static_cast<const Value&>(value);
565 }
566 
567 }  // namespace base
568 
569 #endif  // BASE_VALUES_H_
570