values.h revision c407dc5cd9bdc5668497f21b26b09d988ab439de
1// Copyright (c) 2010 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
6// intended for storing setting and other persistable data.
7// It includes the ability to specify (recursive) lists and dictionaries, so
8// it's fairly expressive.  However, the API is optimized for the common case,
9// namely storing a hierarchical tree of simple values.  Given a
10// DictionaryValue root, you can easily do things like:
11//
12// root->SetString(L"global.pages.homepage", L"http://goateleporter.com");
13// std::wstring homepage = L"http://google.com";  // default/fallback value
14// root->GetString(L"global.pages.homepage", &homepage);
15//
16// where "global" and "pages" are also DictionaryValues, and "homepage"
17// is a string setting.  If some elements of the path didn't exist yet,
18// the SetString() method would create the missing elements and attach them
19// to root before attaching the homepage value.
20
21#ifndef BASE_VALUES_H_
22#define BASE_VALUES_H_
23
24#include <iterator>
25#include <map>
26#include <string>
27#include <vector>
28
29#include "base/basictypes.h"
30#include "base/string16.h"
31#include "build/build_config.h"
32
33class Value;
34class FundamentalValue;
35class StringValue;
36class BinaryValue;
37class DictionaryValue;
38class ListValue;
39
40typedef std::vector<Value*> ValueVector;
41typedef std::map<std::wstring, Value*> ValueMap;
42
43// The Value class is the base class for Values.  A Value can be
44// instantiated via the Create*Value() factory methods, or by directly
45// creating instances of the subclasses.
46class Value {
47 public:
48  virtual ~Value();
49
50  // Convenience methods for creating Value objects for various
51  // kinds of values without thinking about which class implements them.
52  // These can always be expected to return a valid Value*.
53  static Value* CreateNullValue();
54  static Value* CreateBooleanValue(bool in_value);
55  static Value* CreateIntegerValue(int in_value);
56  static Value* CreateRealValue(double in_value);
57  static Value* CreateStringValue(const std::string& in_value);
58  static Value* CreateStringValue(const std::wstring& in_value);
59  static Value* CreateStringValueFromUTF16(const string16& in_value);
60
61  // This one can return NULL if the input isn't valid.  If the return value
62  // is non-null, the new object has taken ownership of the buffer pointer.
63  static BinaryValue* CreateBinaryValue(char* buffer, size_t size);
64
65  typedef enum {
66    TYPE_NULL = 0,
67    TYPE_BOOLEAN,
68    TYPE_INTEGER,
69    TYPE_REAL,
70    TYPE_STRING,
71    TYPE_BINARY,
72    TYPE_DICTIONARY,
73    TYPE_LIST
74  } ValueType;
75
76  // Returns the type of the value stored by the current Value object.
77  // Each type will be implemented by only one subclass of Value, so it's
78  // safe to use the ValueType to determine whether you can cast from
79  // Value* to (Implementing Class)*.  Also, a Value object never changes
80  // its type after construction.
81  ValueType GetType() const { return type_; }
82
83  // Returns true if the current object represents a given type.
84  bool IsType(ValueType type) const { return type == type_; }
85
86  // These methods allow the convenient retrieval of settings.
87  // If the current setting object can be converted into the given type,
88  // the value is returned through the |out_value| parameter and true is
89  // returned;  otherwise, false is returned and |out_value| is unchanged.
90  virtual bool GetAsBoolean(bool* out_value) const;
91  virtual bool GetAsInteger(int* out_value) const;
92  virtual bool GetAsReal(double* out_value) const;
93  virtual bool GetAsString(std::string* out_value) const;
94  virtual bool GetAsString(std::wstring* out_value) const;
95  virtual bool GetAsUTF16(string16* out_value) const;
96
97  // This creates a deep copy of the entire Value tree, and returns a pointer
98  // to the copy.  The caller gets ownership of the copy, of course.
99  virtual Value* DeepCopy() const;
100
101  // Compares if two Value objects have equal contents.
102  virtual bool Equals(const Value* other) const;
103
104 protected:
105  // This isn't safe for end-users (they should use the Create*Value()
106  // static methods above), but it's useful for subclasses.
107  explicit Value(ValueType type);
108
109 private:
110  Value();
111
112  ValueType type_;
113
114  DISALLOW_COPY_AND_ASSIGN(Value);
115};
116
117// FundamentalValue represents the simple fundamental types of values.
118class FundamentalValue : public Value {
119 public:
120  explicit FundamentalValue(bool in_value);
121  explicit FundamentalValue(int in_value);
122  explicit FundamentalValue(double in_value);
123  ~FundamentalValue();
124
125  // Subclassed methods
126  virtual bool GetAsBoolean(bool* out_value) const;
127  virtual bool GetAsInteger(int* out_value) const;
128  virtual bool GetAsReal(double* out_value) const;
129  virtual Value* DeepCopy() const;
130  virtual bool Equals(const Value* other) const;
131
132 private:
133  union {
134    bool boolean_value_;
135    int integer_value_;
136    double real_value_;
137  };
138
139  DISALLOW_COPY_AND_ASSIGN(FundamentalValue);
140};
141
142class StringValue : public Value {
143 public:
144  // Initializes a StringValue with a UTF-8 narrow character string.
145  explicit StringValue(const std::string& in_value);
146
147  // Initializes a StringValue with a wide character string.
148  explicit StringValue(const std::wstring& in_value);
149
150#if !defined(WCHAR_T_IS_UTF16)
151  // Initializes a StringValue with a string16.
152  explicit StringValue(const string16& in_value);
153#endif
154
155  ~StringValue();
156
157  // Subclassed methods
158  bool GetAsString(std::string* out_value) const;
159  bool GetAsString(std::wstring* out_value) const;
160  bool GetAsUTF16(string16* out_value) const;
161  Value* DeepCopy() const;
162  virtual bool Equals(const Value* other) const;
163
164 private:
165  std::string value_;
166
167  DISALLOW_COPY_AND_ASSIGN(StringValue);
168};
169
170class BinaryValue: public Value {
171 public:
172  // Creates a Value to represent a binary buffer.  The new object takes
173  // ownership of the pointer passed in, if successful.
174  // Returns NULL if buffer is NULL.
175  static BinaryValue* Create(char* buffer, size_t size);
176
177  // For situations where you want to keep ownership of your buffer, this
178  // factory method creates a new BinaryValue by copying the contents of the
179  // buffer that's passed in.
180  // Returns NULL if buffer is NULL.
181  static BinaryValue* CreateWithCopiedBuffer(const char* buffer, size_t size);
182
183  ~BinaryValue();
184
185  // Subclassed methods
186  Value* DeepCopy() const;
187  virtual bool Equals(const Value* other) const;
188
189  size_t GetSize() const { return size_; }
190  char* GetBuffer() { return buffer_; }
191  const char* GetBuffer() const { return buffer_; }
192
193 private:
194  // Constructor is private so that only objects with valid buffer pointers
195  // and size values can be created.
196  BinaryValue(char* buffer, size_t size);
197
198  char* buffer_;
199  size_t size_;
200
201  DISALLOW_COPY_AND_ASSIGN(BinaryValue);
202};
203
204class DictionaryValue : public Value {
205 public:
206  DictionaryValue();
207  ~DictionaryValue();
208
209  // Subclassed methods
210  Value* DeepCopy() const;
211  virtual bool Equals(const Value* other) const;
212
213  // Returns true if the current dictionary has a value for the given key.
214  bool HasKeyASCII(const std::string& key) const;
215  // Deprecated version of the above.  TODO: add a string16 version for Unicode.
216  // http://code.google.com/p/chromium/issues/detail?id=23581
217  bool HasKey(const std::wstring& key) const;
218
219  // Returns the number of Values in this dictionary.
220  size_t size() const { return dictionary_.size(); }
221
222  // Returns whether the dictionary is empty.
223  bool empty() const { return dictionary_.empty(); }
224
225  // Clears any current contents of this dictionary.
226  void Clear();
227
228  // Sets the Value associated with the given path starting from this object.
229  // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
230  // into the next DictionaryValue down.  Obviously, "." can't be used
231  // within a key, but there are no other restrictions on keys.
232  // If the key at any step of the way doesn't exist, or exists but isn't
233  // a DictionaryValue, a new DictionaryValue will be created and attached
234  // to the path in that location.
235  // Note that the dictionary takes ownership of the value referenced by
236  // |in_value|, and therefore |in_value| must be non-NULL.
237  void Set(const std::wstring& path, Value* in_value);
238
239  // Convenience forms of Set().  These methods will replace any existing
240  // value at that path, even if it has a different type.
241  void SetBoolean(const std::wstring& path, bool in_value);
242  void SetInteger(const std::wstring& path, int in_value);
243  void SetReal(const std::wstring& path, double in_value);
244  void SetString(const std::wstring& path, const std::string& in_value);
245  void SetString(const std::wstring& path, const std::wstring& in_value);
246  void SetStringFromUTF16(const std::wstring& path, const string16& in_value);
247
248  // Like Set(), but without special treatment of '.'.  This allows e.g. URLs to
249  // be used as paths.
250  void SetWithoutPathExpansion(const std::wstring& key, Value* in_value);
251
252  // Gets the Value associated with the given path starting from this object.
253  // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
254  // into the next DictionaryValue down.  If the path can be resolved
255  // successfully, the value for the last key in the path will be returned
256  // through the |out_value| parameter, and the function will return true.
257  // Otherwise, it will return false and |out_value| will be untouched.
258  // Note that the dictionary always owns the value that's returned.
259  bool Get(const std::wstring& path, Value** out_value) const;
260
261  // These are convenience forms of Get().  The value will be retrieved
262  // and the return value will be true if the path is valid and the value at
263  // the end of the path can be returned in the form specified.
264  bool GetBoolean(const std::wstring& path, bool* out_value) const;
265  bool GetInteger(const std::wstring& path, int* out_value) const;
266  bool GetReal(const std::wstring& path, double* out_value) const;
267  bool GetString(const std::string& path, string16* out_value) const;
268  bool GetStringASCII(const std::string& path, std::string* out_value) const;
269  // TODO: deprecate wstring accessors.
270  // http://code.google.com/p/chromium/issues/detail?id=23581
271  bool GetString(const std::wstring& path, std::string* out_value) const;
272  bool GetString(const std::wstring& path, std::wstring* out_value) const;
273  bool GetStringAsUTF16(const std::wstring& path, string16* out_value) const;
274  bool GetBinary(const std::wstring& path, BinaryValue** out_value) const;
275  bool GetDictionary(const std::wstring& path,
276                     DictionaryValue** out_value) const;
277  bool GetList(const std::wstring& path, ListValue** out_value) const;
278
279  // Like Get(), but without special treatment of '.'.  This allows e.g. URLs to
280  // be used as paths.
281  bool GetWithoutPathExpansion(const std::wstring& key,
282                               Value** out_value) const;
283  bool GetIntegerWithoutPathExpansion(const std::wstring& path,
284                                      int* out_value) const;
285  bool GetStringWithoutPathExpansion(const std::wstring& path,
286                                     std::string* out_value) const;
287  bool GetStringWithoutPathExpansion(const std::wstring& path,
288                                     std::wstring* out_value) const;
289  bool GetStringAsUTF16WithoutPathExpansion(const std::wstring& path,
290                                            string16* out_value) const;
291  bool GetDictionaryWithoutPathExpansion(const std::wstring& path,
292                                         DictionaryValue** out_value) const;
293  bool GetListWithoutPathExpansion(const std::wstring& path,
294                                   ListValue** out_value) const;
295
296  // Removes the Value with the specified path from this dictionary (or one
297  // of its child dictionaries, if the path is more than just a local key).
298  // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
299  // passed out via out_value.  If |out_value| is NULL, the removed value will
300  // be deleted.  This method returns true if |path| is a valid path; otherwise
301  // it will return false and the DictionaryValue object will be unchanged.
302  bool Remove(const std::wstring& path, Value** out_value);
303
304  // Like Remove(), but without special treatment of '.'.  This allows e.g. URLs
305  // to be used as paths.
306  bool RemoveWithoutPathExpansion(const std::wstring& key, Value** out_value);
307
308  // Makes a copy of |this| but doesn't include empty dictionaries and lists in
309  // the copy.  This never returns NULL, even if |this| itself is empty.
310  DictionaryValue* DeepCopyWithoutEmptyChildren();
311
312  // Merge a given dictionary into this dictionary. This is done recursively,
313  // i.e. any subdictionaries will be merged as well. In case of key collisions,
314  // the passed in dictionary takes precedence and data already present will be
315  // replaced.
316  void MergeDictionary(const DictionaryValue* dictionary);
317
318  // This class provides an iterator for the keys in the dictionary.
319  // It can't be used to modify the dictionary.
320  //
321  // YOU SHOULD ALWAYS USE THE XXXWithoutPathExpansion() APIs WITH THESE, NOT
322  // THE NORMAL XXX() APIs.  This makes sure things will work correctly if any
323  // keys have '.'s in them.
324  class key_iterator
325    : private std::iterator<std::input_iterator_tag, const std::wstring> {
326   public:
327    explicit key_iterator(ValueMap::const_iterator itr) { itr_ = itr; }
328    key_iterator operator++() {
329      ++itr_;
330      return *this;
331    }
332    const std::wstring& operator*() { return itr_->first; }
333    bool operator!=(const key_iterator& other) { return itr_ != other.itr_; }
334    bool operator==(const key_iterator& other) { return itr_ == other.itr_; }
335
336   private:
337    ValueMap::const_iterator itr_;
338  };
339
340  key_iterator begin_keys() const { return key_iterator(dictionary_.begin()); }
341  key_iterator end_keys() const { return key_iterator(dictionary_.end()); }
342
343 private:
344  ValueMap dictionary_;
345
346  DISALLOW_COPY_AND_ASSIGN(DictionaryValue);
347};
348
349// This type of Value represents a list of other Value values.
350class ListValue : public Value {
351 public:
352  ListValue();
353  ~ListValue();
354
355  // Subclassed methods
356  Value* DeepCopy() const;
357  virtual bool Equals(const Value* other) const;
358
359  // Clears the contents of this ListValue
360  void Clear();
361
362  // Returns the number of Values in this list.
363  size_t GetSize() const { return list_.size(); }
364
365  // Returns whether the list is empty.
366  bool empty() const { return list_.empty(); }
367
368  // Sets the list item at the given index to be the Value specified by
369  // the value given.  If the index beyond the current end of the list, null
370  // Values will be used to pad out the list.
371  // Returns true if successful, or false if the index was negative or
372  // the value is a null pointer.
373  bool Set(size_t index, Value* in_value);
374
375  // Gets the Value at the given index.  Modifies |out_value| (and returns true)
376  // only if the index falls within the current list range.
377  // Note that the list always owns the Value passed out via |out_value|.
378  bool Get(size_t index, Value** out_value) const;
379
380  // Convenience forms of Get().  Modifies |out_value| (and returns true)
381  // only if the index is valid and the Value at that index can be returned
382  // in the specified form.
383  bool GetBoolean(size_t index, bool* out_value) const;
384  bool GetInteger(size_t index, int* out_value) const;
385  bool GetReal(size_t index, double* out_value) const;
386  bool GetString(size_t index, std::string* out_value) const;
387  bool GetString(size_t index, std::wstring* out_value) const;
388  bool GetStringAsUTF16(size_t index, string16* out_value) const;
389  bool GetBinary(size_t index, BinaryValue** out_value) const;
390  bool GetDictionary(size_t index, DictionaryValue** out_value) const;
391  bool GetList(size_t index, ListValue** out_value) const;
392
393  // Removes the Value with the specified index from this list.
394  // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
395  // passed out via |out_value|.  If |out_value| is NULL, the removed value will
396  // be deleted.  This method returns true if |index| is valid; otherwise
397  // it will return false and the ListValue object will be unchanged.
398  bool Remove(size_t index, Value** out_value);
399
400  // Removes the first instance of |value| found in the list, if any, and
401  // deletes it.  Returns the index that it was located at (-1 for not present).
402  int Remove(const Value& value);
403
404  // Appends a Value to the end of the list.
405  void Append(Value* in_value);
406
407  // Appends a Value if it's not already present.
408  // Returns true if successful, or false if the value was already present.
409  bool AppendIfNotPresent(Value* in_value);
410
411  // Insert a Value at index.
412  // Returns true if successful, or false if the index was out of range.
413  bool Insert(size_t index, Value* in_value);
414
415  // Iteration
416  typedef ValueVector::iterator iterator;
417  typedef ValueVector::const_iterator const_iterator;
418
419  ListValue::iterator begin() { return list_.begin(); }
420  ListValue::iterator end() { return list_.end(); }
421
422  ListValue::const_iterator begin() const { return list_.begin(); }
423  ListValue::const_iterator end() const { return list_.end(); }
424
425 private:
426  ValueVector list_;
427
428  DISALLOW_COPY_AND_ASSIGN(ListValue);
429};
430
431// This interface is implemented by classes that know how to serialize and
432// deserialize Value objects.
433class ValueSerializer {
434 public:
435  virtual ~ValueSerializer();
436
437  virtual bool Serialize(const Value& root) = 0;
438
439  // This method deserializes the subclass-specific format into a Value object.
440  // If the return value is non-NULL, the caller takes ownership of returned
441  // Value. If the return value is NULL, and if error_code is non-NULL,
442  // error_code will be set with the underlying error.
443  // If |error_message| is non-null, it will be filled in with a formatted
444  // error message including the location of the error if appropriate.
445  virtual Value* Deserialize(int* error_code, std::string* error_str) = 0;
446};
447
448#endif  // BASE_VALUES_H_
449