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