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.
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_
30 #include "base/base_export.h"
31 #include "base/basictypes.h"
32 #include "base/compiler_specific.h"
33 #include "base/string16.h"
35 // This file declares "using base::Value", etc. at the bottom, so that
36 // current code can use these classes without the base namespace. In
37 // new code, please always use base::Value, etc. or add your own
38 // "using" declaration.
39 // http://crbug.com/88666
43 class DictionaryValue
;
44 class FundamentalValue
;
49 typedef std::vector
<Value
*> ValueVector
;
50 typedef std::map
<std::string
, Value
*> ValueMap
;
52 // The Value class is the base class for Values. A Value can be instantiated
53 // via the Create*Value() factory methods, or by directly creating instances of
55 class BASE_EXPORT Value
{
70 // Convenience methods for creating Value objects for various
71 // kinds of values without thinking about which class implements them.
72 // These can always be expected to return a valid Value*.
73 static Value
* CreateNullValue();
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
);
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_
; }
87 // Returns true if the current object represents a given type.
88 bool IsType(Type type
) const { return type
== type_
; }
90 // These methods allow the convenient retrieval of settings.
91 // If the current setting object can be converted into the given type,
92 // the value is returned through the |out_value| parameter and true is
93 // returned; 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;
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
);
117 // This isn't safe for end-users (they should use the Create*Value()
118 // static methods above), but it's useful for subclasses.
119 explicit Value(Type type
);
126 DISALLOW_COPY_AND_ASSIGN(Value
);
129 // FundamentalValue represents the simple fundamental types of values.
130 class BASE_EXPORT FundamentalValue
: public Value
{
132 explicit FundamentalValue(bool in_value
);
133 explicit FundamentalValue(int in_value
);
134 explicit FundamentalValue(double in_value
);
135 virtual ~FundamentalValue();
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
;
148 double double_value_
;
151 DISALLOW_COPY_AND_ASSIGN(FundamentalValue
);
154 class BASE_EXPORT StringValue
: public Value
{
156 // Initializes a StringValue with a UTF-8 narrow character string.
157 explicit StringValue(const std::string
& in_value
);
159 // Initializes a StringValue with a string16.
160 explicit StringValue(const string16
& in_value
);
162 virtual ~StringValue();
164 // Overridden from Value:
165 virtual bool GetAsString(std::string
* out_value
) const OVERRIDE
;
166 virtual bool GetAsString(string16
* out_value
) const OVERRIDE
;
167 virtual StringValue
* DeepCopy() const OVERRIDE
;
168 virtual bool Equals(const Value
* other
) const OVERRIDE
;
173 DISALLOW_COPY_AND_ASSIGN(StringValue
);
176 class BASE_EXPORT BinaryValue
: public Value
{
178 virtual ~BinaryValue();
180 // Creates a Value to represent a binary buffer. The new object takes
181 // ownership of the pointer passed in, if successful.
182 // Returns NULL if buffer is NULL.
183 static BinaryValue
* Create(char* buffer
, size_t size
);
185 // For situations where you want to keep ownership of your buffer, this
186 // factory method creates a new BinaryValue by copying the contents of the
187 // buffer that's passed in.
188 // Returns NULL if buffer is NULL.
189 static BinaryValue
* CreateWithCopiedBuffer(const char* buffer
, size_t size
);
191 size_t GetSize() const { return size_
; }
192 char* GetBuffer() { return buffer_
; }
193 const char* GetBuffer() const { return buffer_
; }
195 // Overridden from Value:
196 virtual BinaryValue
* DeepCopy() const OVERRIDE
;
197 virtual bool Equals(const Value
* other
) const OVERRIDE
;
200 // Constructor is private so that only objects with valid buffer pointers
201 // and size values can be created.
202 BinaryValue(char* buffer
, size_t size
);
207 DISALLOW_COPY_AND_ASSIGN(BinaryValue
);
210 // DictionaryValue provides a key-value dictionary with (optional) "path"
211 // parsing for recursive access; see the comment at the top of the file. Keys
212 // are |std::string|s and should be UTF-8 encoded.
213 class BASE_EXPORT DictionaryValue
: public Value
{
216 virtual ~DictionaryValue();
218 // Returns true if the current dictionary has a value for the given key.
219 bool HasKey(const std::string
& key
) const;
221 // Returns the number of Values in this dictionary.
222 size_t size() const { return dictionary_
.size(); }
224 // Returns whether the dictionary is empty.
225 bool empty() const { return dictionary_
.empty(); }
227 // Clears any current contents of this dictionary.
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
);
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
);
249 // Like Set(), but without special treatment of '.'. This allows e.g. URLs to
251 void SetWithoutPathExpansion(const std::string
& key
, Value
* in_value
);
253 // Gets the Value associated with the given path starting from this object.
254 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
255 // into the next DictionaryValue down. If the path can be resolved
256 // successfully, the value for the last key in the path will be returned
257 // through the |out_value| parameter, and the function will return true.
258 // Otherwise, it will return false and |out_value| will be untouched.
259 // Note that the dictionary always owns the value that's returned.
260 bool Get(const std::string
& path
, Value
** out_value
) const;
262 // These are convenience forms of Get(). The value will be retrieved
263 // and the return value will be true if the path is valid and the value at
264 // the end of the path can be returned in the form specified.
265 bool GetBoolean(const std::string
& path
, bool* out_value
) const;
266 bool GetInteger(const std::string
& path
, int* out_value
) const;
267 bool GetDouble(const std::string
& path
, double* out_value
) const;
268 bool GetString(const std::string
& path
, std::string
* out_value
) const;
269 bool GetString(const std::string
& path
, string16
* out_value
) const;
270 bool GetStringASCII(const std::string
& path
, std::string
* out_value
) const;
271 bool GetBinary(const std::string
& path
, BinaryValue
** out_value
) const;
272 bool GetDictionary(const std::string
& path
,
273 DictionaryValue
** out_value
) const;
274 bool GetList(const std::string
& path
, ListValue
** out_value
) const;
276 // Like Get(), but without special treatment of '.'. This allows e.g. URLs to
278 bool GetWithoutPathExpansion(const std::string
& key
,
279 Value
** out_value
) const;
280 bool GetIntegerWithoutPathExpansion(const std::string
& key
,
281 int* out_value
) const;
282 bool GetDoubleWithoutPathExpansion(const std::string
& key
,
283 double* out_value
) const;
284 bool GetStringWithoutPathExpansion(const std::string
& key
,
285 std::string
* out_value
) const;
286 bool GetStringWithoutPathExpansion(const std::string
& key
,
287 string16
* out_value
) const;
288 bool GetDictionaryWithoutPathExpansion(const std::string
& key
,
289 DictionaryValue
** out_value
) const;
290 bool GetListWithoutPathExpansion(const std::string
& key
,
291 ListValue
** out_value
) const;
293 // Removes the Value with the specified path from this dictionary (or one
294 // of its child dictionaries, if the path is more than just a local key).
295 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
296 // passed out via out_value. If |out_value| is NULL, the removed value will
297 // be deleted. This method returns true if |path| is a valid path; otherwise
298 // it will return false and the DictionaryValue object will be unchanged.
299 bool Remove(const std::string
& path
, Value
** out_value
);
301 // Like Remove(), but without special treatment of '.'. This allows e.g. URLs
302 // to be used as paths.
303 bool RemoveWithoutPathExpansion(const std::string
& key
, Value
** out_value
);
305 // Makes a copy of |this| but doesn't include empty dictionaries and lists in
306 // the copy. This never returns NULL, even if |this| itself is empty.
307 DictionaryValue
* DeepCopyWithoutEmptyChildren();
309 // Merge a given dictionary into this dictionary. This is done recursively,
310 // i.e. any subdictionaries will be merged as well. In case of key collisions,
311 // the passed in dictionary takes precedence and data already present will be
313 void MergeDictionary(const DictionaryValue
* dictionary
);
315 // Swaps contents with the |other| dictionary.
316 void Swap(DictionaryValue
* other
) {
317 dictionary_
.swap(other
->dictionary_
);
320 // This class provides an iterator for the keys in the dictionary.
321 // It can't be used to modify the dictionary.
323 // YOU SHOULD ALWAYS USE THE XXXWithoutPathExpansion() APIs WITH THESE, NOT
324 // THE NORMAL XXX() APIs. This makes sure things will work correctly if any
325 // keys have '.'s in them.
327 : private std::iterator
<std::input_iterator_tag
, const std::string
> {
329 explicit key_iterator(ValueMap::const_iterator itr
) { itr_
= itr
; }
330 key_iterator
operator++() {
334 const std::string
& operator*() { return itr_
->first
; }
335 bool operator!=(const key_iterator
& other
) { return itr_
!= other
.itr_
; }
336 bool operator==(const key_iterator
& other
) { return itr_
== other
.itr_
; }
339 ValueMap::const_iterator itr_
;
342 key_iterator
begin_keys() const { return key_iterator(dictionary_
.begin()); }
343 key_iterator
end_keys() const { return key_iterator(dictionary_
.end()); }
345 // This class provides an iterator over both keys and values in the
346 // dictionary. It can't be used to modify the dictionary.
349 explicit Iterator(const DictionaryValue
& target
)
350 : target_(target
), it_(target
.dictionary_
.begin()) {}
352 bool HasNext() const { return it_
!= target_
.dictionary_
.end(); }
353 void Advance() { ++it_
; }
355 const std::string
& key() const { return it_
->first
; }
356 const Value
& value() const { return *it_
->second
; }
359 const DictionaryValue
& target_
;
360 ValueMap::const_iterator it_
;
363 // Overridden from Value:
364 virtual DictionaryValue
* DeepCopy() const OVERRIDE
;
365 virtual bool Equals(const Value
* other
) const OVERRIDE
;
368 ValueMap dictionary_
;
370 DISALLOW_COPY_AND_ASSIGN(DictionaryValue
);
373 // This type of Value represents a list of other Value values.
374 class BASE_EXPORT ListValue
: public Value
{
376 typedef ValueVector::iterator iterator
;
377 typedef ValueVector::const_iterator const_iterator
;
380 virtual ~ListValue();
382 // Clears the contents of this ListValue
385 // Returns the number of Values in this list.
386 size_t GetSize() const { return list_
.size(); }
388 // Returns whether the list is empty.
389 bool empty() const { return list_
.empty(); }
391 // Sets the list item at the given index to be the Value specified by
392 // the value given. If the index beyond the current end of the list, null
393 // Values will be used to pad out the list.
394 // Returns true if successful, or false if the index was negative or
395 // the value is a null pointer.
396 bool Set(size_t index
, Value
* in_value
);
398 // Gets the Value at the given index. Modifies |out_value| (and returns true)
399 // only if the index falls within the current list range.
400 // Note that the list always owns the Value passed out via |out_value|.
401 bool Get(size_t index
, Value
** out_value
) const;
403 // Convenience forms of Get(). Modifies |out_value| (and returns true)
404 // only if the index is valid and the Value at that index can be returned
405 // in the specified form.
406 bool GetBoolean(size_t index
, bool* out_value
) const;
407 bool GetInteger(size_t index
, int* out_value
) const;
408 bool GetDouble(size_t index
, double* out_value
) const;
409 bool GetString(size_t index
, std::string
* out_value
) const;
410 bool GetString(size_t index
, string16
* out_value
) const;
411 bool GetBinary(size_t index
, BinaryValue
** out_value
) const;
412 bool GetDictionary(size_t index
, DictionaryValue
** out_value
) const;
413 bool GetList(size_t index
, ListValue
** out_value
) const;
415 // Removes the Value with the specified index from this list.
416 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
417 // passed out via |out_value|. If |out_value| is NULL, the removed value will
418 // be deleted. This method returns true if |index| is valid; otherwise
419 // it will return false and the ListValue object will be unchanged.
420 bool Remove(size_t index
, Value
** out_value
);
422 // Removes the first instance of |value| found in the list, if any, and
423 // deletes it. |index| is the location where |value| was found. Returns false
425 bool Remove(const Value
& value
, size_t* index
);
427 // Appends a Value to the end of the list.
428 void Append(Value
* in_value
);
430 // Appends a Value if it's not already present. Takes ownership of the
431 // |in_value|. Returns true if successful, or false if the value was already
432 // present. If the value was already present the |in_value| is deleted.
433 bool AppendIfNotPresent(Value
* in_value
);
435 // Insert a Value at index.
436 // Returns true if successful, or false if the index was out of range.
437 bool Insert(size_t index
, Value
* in_value
);
439 // Searches for the first instance of |value| in the list using the Equals
440 // method of the Value type.
441 // Returns a const_iterator to the found item or to end() if none exists.
442 const_iterator
Find(const Value
& value
) const;
444 // Swaps contents with the |other| list.
445 void Swap(ListValue
* other
) {
446 list_
.swap(other
->list_
);
450 iterator
begin() { return list_
.begin(); }
451 iterator
end() { return list_
.end(); }
453 const_iterator
begin() const { return list_
.begin(); }
454 const_iterator
end() const { return list_
.end(); }
456 // Overridden from Value:
457 virtual bool GetAsList(ListValue
** out_value
) OVERRIDE
;
458 virtual bool GetAsList(const ListValue
** out_value
) const OVERRIDE
;
459 virtual ListValue
* DeepCopy() const OVERRIDE
;
460 virtual bool Equals(const Value
* other
) const OVERRIDE
;
465 DISALLOW_COPY_AND_ASSIGN(ListValue
);
468 // This interface is implemented by classes that know how to serialize and
469 // deserialize Value objects.
470 class BASE_EXPORT ValueSerializer
{
472 virtual ~ValueSerializer();
474 virtual bool Serialize(const Value
& root
) = 0;
476 // This method deserializes the subclass-specific format into a Value object.
477 // If the return value is non-NULL, the caller takes ownership of returned
478 // Value. If the return value is NULL, and if error_code is non-NULL,
479 // error_code will be set with the underlying error.
480 // If |error_message| is non-null, it will be filled in with a formatted
481 // error message including the location of the error if appropriate.
482 virtual Value
* Deserialize(int* error_code
, std::string
* error_str
) = 0;
487 // http://crbug.com/88666
488 using base::DictionaryValue
;
489 using base::ListValue
;
490 using base::StringValue
;
493 #endif // BASE_VALUES_H_