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