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