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