Revert 171679
[chromium-blink-merge.git] / base / values.h
blobe105818e5d3953edddcb7e410b015f7807d8ccbb
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.
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:
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);
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.
21 #ifndef BASE_VALUES_H_
22 #define BASE_VALUES_H_
24 #include <iterator>
25 #include <map>
26 #include <string>
27 #include <vector>
29 #include "base/base_export.h"
30 #include "base/basictypes.h"
31 #include "base/compiler_specific.h"
32 #include "base/string16.h"
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
39 namespace base {
41 class BinaryValue;
42 class DictionaryValue;
43 class FundamentalValue;
44 class ListValue;
45 class StringValue;
46 class Value;
48 typedef std::vector<Value*> ValueVector;
49 typedef std::map<std::string, Value*> ValueMap;
51 // The Value class is the base class for Values. A Value can be instantiated
52 // via the Create*Value() factory methods, or by directly creating instances of
53 // the subclasses.
54 class BASE_EXPORT Value {
55 public:
56 enum Type {
57 TYPE_NULL = 0,
58 TYPE_BOOLEAN,
59 TYPE_INTEGER,
60 TYPE_DOUBLE,
61 TYPE_STRING,
62 TYPE_BINARY,
63 TYPE_DICTIONARY,
64 TYPE_LIST
67 virtual ~Value();
69 static Value* CreateNullValue();
70 // DEPRECATED: Do not use the following 5 functions. Instead, use
71 // new FundamentalValue or new StringValue.
72 static FundamentalValue* CreateBooleanValue(bool in_value);
73 static FundamentalValue* CreateIntegerValue(int in_value);
74 static FundamentalValue* CreateDoubleValue(double in_value);
75 static StringValue* CreateStringValue(const std::string& in_value);
76 static StringValue* CreateStringValue(const string16& in_value);
78 // Returns the type of the value stored by the current Value object.
79 // Each type will be implemented by only one subclass of Value, so it's
80 // safe to use the Type to determine whether you can cast from
81 // Value* to (Implementing Class)*. Also, a Value object never changes
82 // its type after construction.
83 Type GetType() const { return type_; }
85 // Returns true if the current object represents a given type.
86 bool IsType(Type type) const { return type == type_; }
88 // These methods allow the convenient retrieval of settings.
89 // If the current setting object can be converted into the given type,
90 // the value is returned through the |out_value| parameter and true is
91 // returned; otherwise, false is returned and |out_value| is unchanged.
92 virtual bool GetAsBoolean(bool* out_value) const;
93 virtual bool GetAsInteger(int* out_value) const;
94 virtual bool GetAsDouble(double* out_value) const;
95 virtual bool GetAsString(std::string* out_value) const;
96 virtual bool GetAsString(string16* out_value) const;
97 virtual bool GetAsList(ListValue** out_value);
98 virtual bool GetAsList(const ListValue** out_value) const;
99 virtual bool GetAsDictionary(DictionaryValue** out_value);
100 virtual bool GetAsDictionary(const DictionaryValue** out_value) const;
102 // This creates a deep copy of the entire Value tree, and returns a pointer
103 // to the copy. The caller gets ownership of the copy, of course.
105 // Subclasses return their own type directly in their overrides;
106 // this works because C++ supports covariant return types.
107 virtual Value* DeepCopy() const;
109 // Compares if two Value objects have equal contents.
110 virtual bool Equals(const Value* other) const;
112 // Compares if two Value objects have equal contents. Can handle NULLs.
113 // NULLs are considered equal but different from Value::CreateNullValue().
114 static bool Equals(const Value* a, const Value* b);
116 protected:
117 // These aren't safe for end-users, but they are useful for subclasses.
118 explicit Value(Type type);
119 Value(const Value& that);
120 Value& operator=(const Value& that);
122 private:
123 Type type_;
126 // FundamentalValue represents the simple fundamental types of values.
127 class BASE_EXPORT FundamentalValue : public Value {
128 public:
129 explicit FundamentalValue(bool in_value);
130 explicit FundamentalValue(int in_value);
131 explicit FundamentalValue(double in_value);
132 virtual ~FundamentalValue();
134 // Overridden from Value:
135 virtual bool GetAsBoolean(bool* out_value) const OVERRIDE;
136 virtual bool GetAsInteger(int* out_value) const OVERRIDE;
137 virtual bool GetAsDouble(double* out_value) const OVERRIDE;
138 virtual FundamentalValue* DeepCopy() const OVERRIDE;
139 virtual bool Equals(const Value* other) const OVERRIDE;
141 private:
142 union {
143 bool boolean_value_;
144 int integer_value_;
145 double double_value_;
149 class BASE_EXPORT StringValue : public Value {
150 public:
151 // Initializes a StringValue with a UTF-8 narrow character string.
152 explicit StringValue(const std::string& in_value);
154 // Initializes a StringValue with a string16.
155 explicit StringValue(const string16& in_value);
157 virtual ~StringValue();
159 // Overridden from Value:
160 virtual bool GetAsString(std::string* out_value) const OVERRIDE;
161 virtual bool GetAsString(string16* out_value) const OVERRIDE;
162 virtual StringValue* DeepCopy() const OVERRIDE;
163 virtual bool Equals(const Value* other) const OVERRIDE;
165 private:
166 std::string value_;
169 class BASE_EXPORT BinaryValue: public Value {
170 public:
171 virtual ~BinaryValue();
173 // Creates a Value to represent a binary buffer. The new object takes
174 // ownership of the pointer passed in, if successful.
175 // Returns NULL if buffer is NULL.
176 static BinaryValue* Create(char* buffer, size_t size);
178 // For situations where you want to keep ownership of your buffer, this
179 // factory method creates a new BinaryValue by copying the contents of the
180 // buffer that's passed in.
181 // Returns NULL if buffer is NULL.
182 static BinaryValue* CreateWithCopiedBuffer(const char* buffer, size_t size);
184 size_t GetSize() const { return size_; }
185 char* GetBuffer() { return buffer_; }
186 const char* GetBuffer() const { return buffer_; }
188 // Overridden from Value:
189 virtual BinaryValue* DeepCopy() const OVERRIDE;
190 virtual bool Equals(const Value* other) const OVERRIDE;
192 private:
193 // Constructor is private so that only objects with valid buffer pointers
194 // and size values can be created.
195 BinaryValue(char* buffer, size_t size);
197 char* buffer_;
198 size_t size_;
200 DISALLOW_COPY_AND_ASSIGN(BinaryValue);
203 // DictionaryValue provides a key-value dictionary with (optional) "path"
204 // parsing for recursive access; see the comment at the top of the file. Keys
205 // are |std::string|s and should be UTF-8 encoded.
206 class BASE_EXPORT DictionaryValue : public Value {
207 public:
208 DictionaryValue();
209 virtual ~DictionaryValue();
211 // Overridden from Value:
212 virtual bool GetAsDictionary(DictionaryValue** out_value) OVERRIDE;
213 virtual bool GetAsDictionary(
214 const DictionaryValue** out_value) const OVERRIDE;
216 // Returns true if the current dictionary has a value for the given key.
217 bool HasKey(const std::string& key) const;
219 // Returns the number of Values in this dictionary.
220 size_t size() const { return dictionary_.size(); }
222 // Returns whether the dictionary is empty.
223 bool empty() const { return dictionary_.empty(); }
225 // Clears any current contents of this dictionary.
226 void Clear();
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::string& path, Value* in_value);
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::string& path, bool in_value);
242 void SetInteger(const std::string& path, int in_value);
243 void SetDouble(const std::string& path, double in_value);
244 void SetString(const std::string& path, const std::string& in_value);
245 void SetString(const std::string& path, const string16& in_value);
247 // Like Set(), but without special treatment of '.'. This allows e.g. URLs to
248 // be used as paths.
249 void SetWithoutPathExpansion(const std::string& key, Value* in_value);
251 // Convenience forms of SetWithoutPathExpansion().
252 void SetBooleanWithoutPathExpansion(const std::string& path, bool in_value);
253 void SetIntegerWithoutPathExpansion(const std::string& path, int in_value);
254 void SetDoubleWithoutPathExpansion(const std::string& path, double in_value);
255 void SetStringWithoutPathExpansion(const std::string& path,
256 const std::string& in_value);
257 void SetStringWithoutPathExpansion(const std::string& path,
258 const string16& in_value);
260 // Gets the Value associated with the given path starting from this object.
261 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
262 // into the next DictionaryValue down. If the path can be resolved
263 // successfully, the value for the last key in the path will be returned
264 // through the |out_value| parameter, and the function will return true.
265 // Otherwise, it will return false and |out_value| will be untouched.
266 // Note that the dictionary always owns the value that's returned.
267 bool Get(const std::string& path, const Value** out_value) const;
268 bool Get(const std::string& path, Value** out_value);
270 // These are convenience forms of Get(). The value will be retrieved
271 // and the return value will be true if the path is valid and the value at
272 // the end of the path can be returned in the form specified.
273 bool GetBoolean(const std::string& path, bool* out_value) const;
274 bool GetInteger(const std::string& path, int* out_value) const;
275 bool GetDouble(const std::string& path, double* out_value) const;
276 bool GetString(const std::string& path, std::string* out_value) const;
277 bool GetString(const std::string& path, string16* out_value) const;
278 bool GetStringASCII(const std::string& path, std::string* out_value) const;
279 bool GetBinary(const std::string& path, const BinaryValue** out_value) const;
280 bool GetBinary(const std::string& path, BinaryValue** out_value);
281 bool GetDictionary(const std::string& path,
282 const DictionaryValue** out_value) const;
283 bool GetDictionary(const std::string& path, DictionaryValue** out_value);
284 bool GetList(const std::string& path, const ListValue** out_value) const;
285 bool GetList(const std::string& path, ListValue** out_value);
287 // Like Get(), but without special treatment of '.'. This allows e.g. URLs to
288 // be used as paths.
289 bool GetWithoutPathExpansion(const std::string& key,
290 const Value** out_value) const;
291 bool GetWithoutPathExpansion(const std::string& key, Value** out_value);
292 bool GetBooleanWithoutPathExpansion(const std::string& key,
293 bool* out_value) const;
294 bool GetIntegerWithoutPathExpansion(const std::string& key,
295 int* out_value) const;
296 bool GetDoubleWithoutPathExpansion(const std::string& key,
297 double* out_value) const;
298 bool GetStringWithoutPathExpansion(const std::string& key,
299 std::string* out_value) const;
300 bool GetStringWithoutPathExpansion(const std::string& key,
301 string16* out_value) const;
302 bool GetDictionaryWithoutPathExpansion(
303 const std::string& key,
304 const DictionaryValue** out_value) const;
305 bool GetDictionaryWithoutPathExpansion(const std::string& key,
306 DictionaryValue** out_value);
307 bool GetListWithoutPathExpansion(const std::string& key,
308 const ListValue** out_value) const;
309 bool GetListWithoutPathExpansion(const std::string& key,
310 ListValue** out_value);
312 // Removes the Value with the specified path from this dictionary (or one
313 // of its child dictionaries, if the path is more than just a local key).
314 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
315 // passed out via out_value. If |out_value| is NULL, the removed value will
316 // be deleted. This method returns true if |path| is a valid path; otherwise
317 // it will return false and the DictionaryValue object will be unchanged.
318 virtual bool Remove(const std::string& path, Value** out_value);
320 // Like Remove(), but without special treatment of '.'. This allows e.g. URLs
321 // to be used as paths.
322 virtual bool RemoveWithoutPathExpansion(const std::string& key,
323 Value** out_value);
325 // Makes a copy of |this| but doesn't include empty dictionaries and lists in
326 // the copy. This never returns NULL, even if |this| itself is empty.
327 DictionaryValue* DeepCopyWithoutEmptyChildren();
329 // Merge |dictionary| into this dictionary. This is done recursively, i.e. any
330 // sub-dictionaries will be merged as well. In case of key collisions, the
331 // passed in dictionary takes precedence and data already present will be
332 // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
333 // be freed any time after this call.
334 void MergeDictionary(const DictionaryValue* dictionary);
336 // Swaps contents with the |other| dictionary.
337 virtual void Swap(DictionaryValue* other);
339 // This class provides an iterator for the keys in the dictionary.
340 // It can't be used to modify the dictionary.
342 // YOU SHOULD ALWAYS USE THE XXXWithoutPathExpansion() APIs WITH THESE, NOT
343 // THE NORMAL XXX() APIs. This makes sure things will work correctly if any
344 // keys have '.'s in them.
345 class BASE_EXPORT key_iterator
346 : private std::iterator<std::input_iterator_tag, const std::string> {
347 public:
348 explicit key_iterator(ValueMap::const_iterator itr);
349 // Not explicit, because this is a copy constructor.
350 key_iterator(const key_iterator& rhs);
351 key_iterator operator++() {
352 ++itr_;
353 return *this;
355 const std::string& operator*() { return itr_->first; }
356 bool operator!=(const key_iterator& other) { return itr_ != other.itr_; }
357 bool operator==(const key_iterator& other) { return itr_ == other.itr_; }
359 private:
360 ValueMap::const_iterator itr_;
363 key_iterator begin_keys() const { return key_iterator(dictionary_.begin()); }
364 key_iterator end_keys() const { return key_iterator(dictionary_.end()); }
366 // This class provides an iterator over both keys and values in the
367 // dictionary. It can't be used to modify the dictionary.
368 class BASE_EXPORT Iterator {
369 public:
370 explicit Iterator(const DictionaryValue& target);
372 bool HasNext() const { return it_ != target_.dictionary_.end(); }
373 void Advance() { ++it_; }
375 const std::string& key() const { return it_->first; }
376 const Value& value() const { return *it_->second; }
378 private:
379 const DictionaryValue& target_;
380 ValueMap::const_iterator it_;
383 // Overridden from Value:
384 virtual DictionaryValue* DeepCopy() const OVERRIDE;
385 virtual bool Equals(const Value* other) const OVERRIDE;
387 private:
388 ValueMap dictionary_;
390 DISALLOW_COPY_AND_ASSIGN(DictionaryValue);
393 // This type of Value represents a list of other Value values.
394 class BASE_EXPORT ListValue : public Value {
395 public:
396 typedef ValueVector::iterator iterator;
397 typedef ValueVector::const_iterator const_iterator;
399 ListValue();
400 virtual ~ListValue();
402 // Clears the contents of this ListValue
403 void Clear();
405 // Returns the number of Values in this list.
406 size_t GetSize() const { return list_.size(); }
408 // Returns whether the list is empty.
409 bool empty() const { return list_.empty(); }
411 // Sets the list item at the given index to be the Value specified by
412 // the value given. If the index beyond the current end of the list, null
413 // Values will be used to pad out the list.
414 // Returns true if successful, or false if the index was negative or
415 // the value is a null pointer.
416 bool Set(size_t index, Value* in_value);
418 // Gets the Value at the given index. Modifies |out_value| (and returns true)
419 // only if the index falls within the current list range.
420 // Note that the list always owns the Value passed out via |out_value|.
421 bool Get(size_t index, const Value** out_value) const;
422 bool Get(size_t index, Value** out_value);
424 // Convenience forms of Get(). Modifies |out_value| (and returns true)
425 // only if the index is valid and the Value at that index can be returned
426 // in the specified form.
427 bool GetBoolean(size_t index, bool* out_value) const;
428 bool GetInteger(size_t index, int* out_value) const;
429 bool GetDouble(size_t index, double* out_value) const;
430 bool GetString(size_t index, std::string* out_value) const;
431 bool GetString(size_t index, string16* out_value) const;
432 bool GetBinary(size_t index, const BinaryValue** out_value) const;
433 bool GetBinary(size_t index, BinaryValue** out_value);
434 bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
435 bool GetDictionary(size_t index, DictionaryValue** out_value);
436 bool GetList(size_t index, const ListValue** out_value) const;
437 bool GetList(size_t index, ListValue** out_value);
439 // Removes the Value with the specified index from this list.
440 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
441 // passed out via |out_value|. If |out_value| is NULL, the removed value will
442 // be deleted. This method returns true if |index| is valid; otherwise
443 // it will return false and the ListValue object will be unchanged.
444 virtual bool Remove(size_t index, Value** out_value);
446 // Removes the first instance of |value| found in the list, if any, and
447 // deletes it. |index| is the location where |value| was found. Returns false
448 // if not found.
449 bool Remove(const Value& value, size_t* index);
451 // Removes the element at |iter|. If |out_value| is NULL, the value will be
452 // deleted, otherwise ownership of the value is passed back to the caller.
453 void Erase(iterator iter, Value** out_value);
455 // Appends a Value to the end of the list.
456 void Append(Value* in_value);
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);
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);
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);
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;
481 // Swaps contents with the |other| list.
482 virtual void Swap(ListValue* other);
484 // Iteration.
485 iterator begin() { return list_.begin(); }
486 iterator end() { return list_.end(); }
488 const_iterator begin() const { return list_.begin(); }
489 const_iterator end() const { return list_.end(); }
491 // Overridden from Value:
492 virtual bool GetAsList(ListValue** out_value) OVERRIDE;
493 virtual bool GetAsList(const ListValue** out_value) const OVERRIDE;
494 virtual ListValue* DeepCopy() const OVERRIDE;
495 virtual bool Equals(const Value* other) const OVERRIDE;
497 private:
498 ValueVector list_;
500 DISALLOW_COPY_AND_ASSIGN(ListValue);
503 // This interface is implemented by classes that know how to serialize and
504 // deserialize Value objects.
505 class BASE_EXPORT ValueSerializer {
506 public:
507 virtual ~ValueSerializer();
509 virtual bool Serialize(const Value& root) = 0;
511 // This method deserializes the subclass-specific format into a Value object.
512 // If the return value is non-NULL, the caller takes ownership of returned
513 // Value. If the return value is NULL, and if error_code is non-NULL,
514 // error_code will be set with the underlying error.
515 // If |error_message| is non-null, it will be filled in with a formatted
516 // error message including the location of the error if appropriate.
517 virtual Value* Deserialize(int* error_code, std::string* error_str) = 0;
520 // Stream operator so Values can be used in assertion statements.
521 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
523 } // namespace base
525 // http://crbug.com/88666
526 using base::DictionaryValue;
527 using base::ListValue;
528 using base::StringValue;
529 using base::Value;
531 #endif // BASE_VALUES_H_