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