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 settings and other persistable data.
8 // A Value represents something that can be stored in JSON or passed to/from
9 // JavaScript. As such, it is NOT a generalized variant type, since only the
10 // types supported by JavaScript/JSON are supported.
12 // IN PARTICULAR this means that there is no support for int64 or unsigned
13 // numbers. Writing JSON with such types would violate the spec. If you need
14 // something like this, either use a double or make a string value containing
15 // the number you want.
17 #ifndef BASE_VALUES_H_
18 #define BASE_VALUES_H_
28 #include "base/base_export.h"
29 #include "base/basictypes.h"
30 #include "base/compiler_specific.h"
31 #include "base/memory/scoped_ptr.h"
32 #include "base/strings/string16.h"
37 class DictionaryValue
;
38 class FundamentalValue
;
43 typedef std::vector
<Value
*> ValueVector
;
44 typedef std::map
<std::string
, Value
*> ValueMap
;
46 // The Value class is the base class for Values. A Value can be instantiated
47 // via the Create*Value() factory methods, or by directly creating instances of
50 // See the file-level comment above for more information.
51 class BASE_EXPORT Value
{
62 // Note: Do not add more types. See the file-level comment above for why.
67 static Value
* CreateNullValue();
69 // Returns the type of the value stored by the current Value object.
70 // Each type will be implemented by only one subclass of Value, so it's
71 // safe to use the Type to determine whether you can cast from
72 // Value* to (Implementing Class)*. Also, a Value object never changes
73 // its type after construction.
74 Type
GetType() const { return type_
; }
76 // Returns true if the current object represents a given type.
77 bool IsType(Type type
) const { return type
== type_
; }
79 // These methods allow the convenient retrieval of the contents of the Value.
80 // If the current object can be converted into the given type, the value is
81 // returned through the |out_value| parameter and true is returned;
82 // otherwise, false is returned and |out_value| is unchanged.
83 virtual bool GetAsBoolean(bool* out_value
) const;
84 virtual bool GetAsInteger(int* out_value
) const;
85 virtual bool GetAsDouble(double* out_value
) const;
86 virtual bool GetAsString(std::string
* out_value
) const;
87 virtual bool GetAsString(string16
* out_value
) const;
88 virtual bool GetAsString(const StringValue
** out_value
) const;
89 virtual bool GetAsBinary(const BinaryValue
** out_value
) const;
90 virtual bool GetAsList(ListValue
** out_value
);
91 virtual bool GetAsList(const ListValue
** out_value
) const;
92 virtual bool GetAsDictionary(DictionaryValue
** out_value
);
93 virtual bool GetAsDictionary(const DictionaryValue
** out_value
) const;
94 // Note: Do not add more types. See the file-level comment above for why.
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.
99 // Subclasses return their own type directly in their overrides;
100 // this works because C++ supports covariant return types.
101 virtual Value
* DeepCopy() const;
103 // Compares if two Value objects have equal contents.
104 virtual bool Equals(const Value
* other
) const;
106 // Compares if two Value objects have equal contents. Can handle NULLs.
107 // NULLs are considered equal but different from Value::CreateNullValue().
108 static bool Equals(const Value
* a
, const Value
* b
);
111 // These aren't safe for end-users, but they are useful for subclasses.
112 explicit Value(Type type
);
113 Value(const Value
& that
);
114 Value
& operator=(const Value
& that
);
120 // FundamentalValue represents the simple fundamental types of values.
121 class BASE_EXPORT FundamentalValue
: public Value
{
123 explicit FundamentalValue(bool in_value
);
124 explicit FundamentalValue(int in_value
);
125 explicit FundamentalValue(double in_value
);
126 ~FundamentalValue() override
;
128 // Overridden from Value:
129 bool GetAsBoolean(bool* out_value
) const override
;
130 bool GetAsInteger(int* out_value
) const override
;
131 // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
133 bool GetAsDouble(double* out_value
) const override
;
134 FundamentalValue
* DeepCopy() const override
;
135 bool Equals(const Value
* other
) const override
;
141 double double_value_
;
145 class BASE_EXPORT StringValue
: public Value
{
147 // Initializes a StringValue with a UTF-8 narrow character string.
148 explicit StringValue(const std::string
& in_value
);
150 // Initializes a StringValue with a string16.
151 explicit StringValue(const string16
& in_value
);
153 ~StringValue() override
;
155 // Returns |value_| as a pointer or reference.
156 std::string
* GetString();
157 const std::string
& GetString() const;
159 // Overridden from Value:
160 bool GetAsString(std::string
* out_value
) const override
;
161 bool GetAsString(string16
* out_value
) const override
;
162 bool GetAsString(const StringValue
** out_value
) const override
;
163 StringValue
* DeepCopy() const override
;
164 bool Equals(const Value
* other
) const override
;
170 class BASE_EXPORT BinaryValue
: public Value
{
172 // Creates a BinaryValue with a null buffer and size of 0.
175 // Creates a BinaryValue, taking ownership of the bytes pointed to by
177 BinaryValue(scoped_ptr
<char[]> buffer
, size_t size
);
179 ~BinaryValue() override
;
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 static BinaryValue
* CreateWithCopiedBuffer(const char* buffer
, size_t size
);
186 size_t GetSize() const { return size_
; }
189 char* GetBuffer() { return buffer_
.get(); }
190 const char* GetBuffer() const { return buffer_
.get(); }
192 // Overridden from Value:
193 bool GetAsBinary(const BinaryValue
** out_value
) const override
;
194 BinaryValue
* DeepCopy() const override
;
195 bool Equals(const Value
* other
) const override
;
198 scoped_ptr
<char[]> buffer_
;
201 DISALLOW_COPY_AND_ASSIGN(BinaryValue
);
204 // DictionaryValue provides a key-value dictionary with (optional) "path"
205 // parsing for recursive access; see the comment at the top of the file. Keys
206 // are |std::string|s and should be UTF-8 encoded.
207 class BASE_EXPORT DictionaryValue
: public Value
{
210 ~DictionaryValue() override
;
212 // Overridden from Value:
213 bool GetAsDictionary(DictionaryValue
** out_value
) override
;
214 bool GetAsDictionary(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.
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. |in_value| must be non-null.
235 void Set(const std::string
& path
, scoped_ptr
<Value
> in_value
);
236 // Deprecated version of the above. TODO(estade): remove.
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
249 void SetWithoutPathExpansion(const std::string
& key
,
250 scoped_ptr
<Value
> in_value
);
251 // Deprecated version of the above. TODO(estade): remove.
252 void SetWithoutPathExpansion(const std::string
& key
, Value
* in_value
);
254 // Convenience forms of SetWithoutPathExpansion().
255 void SetBooleanWithoutPathExpansion(const std::string
& path
, bool in_value
);
256 void SetIntegerWithoutPathExpansion(const std::string
& path
, int in_value
);
257 void SetDoubleWithoutPathExpansion(const std::string
& path
, double in_value
);
258 void SetStringWithoutPathExpansion(const std::string
& path
,
259 const std::string
& in_value
);
260 void SetStringWithoutPathExpansion(const std::string
& path
,
261 const string16
& in_value
);
263 // Gets the Value associated with the given path starting from this object.
264 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
265 // into the next DictionaryValue down. If the path can be resolved
266 // successfully, the value for the last key in the path will be returned
267 // through the |out_value| parameter, and the function will return true.
268 // Otherwise, it will return false and |out_value| will be untouched.
269 // Note that the dictionary always owns the value that's returned.
270 // |out_value| is optional and will only be set if non-NULL.
271 bool Get(const std::string
& path
, const Value
** out_value
) const;
272 bool Get(const std::string
& path
, Value
** out_value
);
274 // These are convenience forms of Get(). The value will be retrieved
275 // and the return value will be true if the path is valid and the value at
276 // the end of the path can be returned in the form specified.
277 // |out_value| is optional and will only be set if non-NULL.
278 bool GetBoolean(const std::string
& path
, bool* out_value
) const;
279 bool GetInteger(const std::string
& path
, int* out_value
) const;
280 // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
282 bool GetDouble(const std::string
& path
, double* out_value
) const;
283 bool GetString(const std::string
& path
, std::string
* out_value
) const;
284 bool GetString(const std::string
& path
, string16
* out_value
) const;
285 bool GetStringASCII(const std::string
& path
, std::string
* out_value
) const;
286 bool GetBinary(const std::string
& path
, const BinaryValue
** out_value
) const;
287 bool GetBinary(const std::string
& path
, BinaryValue
** out_value
);
288 bool GetDictionary(const std::string
& path
,
289 const DictionaryValue
** out_value
) const;
290 bool GetDictionary(const std::string
& path
, DictionaryValue
** out_value
);
291 bool GetList(const std::string
& path
, const ListValue
** out_value
) const;
292 bool GetList(const std::string
& path
, ListValue
** out_value
);
294 // Like Get(), but without special treatment of '.'. This allows e.g. URLs to
296 bool GetWithoutPathExpansion(const std::string
& key
,
297 const Value
** out_value
) const;
298 bool GetWithoutPathExpansion(const std::string
& key
, Value
** out_value
);
299 bool GetBooleanWithoutPathExpansion(const std::string
& key
,
300 bool* out_value
) const;
301 bool GetIntegerWithoutPathExpansion(const std::string
& key
,
302 int* out_value
) const;
303 bool GetDoubleWithoutPathExpansion(const std::string
& key
,
304 double* out_value
) const;
305 bool GetStringWithoutPathExpansion(const std::string
& key
,
306 std::string
* out_value
) const;
307 bool GetStringWithoutPathExpansion(const std::string
& key
,
308 string16
* out_value
) const;
309 bool GetDictionaryWithoutPathExpansion(
310 const std::string
& key
,
311 const DictionaryValue
** out_value
) const;
312 bool GetDictionaryWithoutPathExpansion(const std::string
& key
,
313 DictionaryValue
** out_value
);
314 bool GetListWithoutPathExpansion(const std::string
& key
,
315 const ListValue
** out_value
) const;
316 bool GetListWithoutPathExpansion(const std::string
& key
,
317 ListValue
** out_value
);
319 // Removes the Value with the specified path from this dictionary (or one
320 // of its child dictionaries, if the path is more than just a local key).
321 // If |out_value| is non-NULL, the removed Value will be passed out via
322 // |out_value|. If |out_value| is NULL, the removed value will be deleted.
323 // This method returns true if |path| is a valid path; otherwise it will
324 // return false and the DictionaryValue object will be unchanged.
325 virtual bool Remove(const std::string
& path
, scoped_ptr
<Value
>* out_value
);
327 // Like Remove(), but without special treatment of '.'. This allows e.g. URLs
328 // to be used as paths.
329 virtual bool RemoveWithoutPathExpansion(const std::string
& key
,
330 scoped_ptr
<Value
>* out_value
);
332 // Removes a path, clearing out all dictionaries on |path| that remain empty
333 // after removing the value at |path|.
334 virtual bool RemovePath(const std::string
& path
,
335 scoped_ptr
<Value
>* out_value
);
337 // Makes a copy of |this| but doesn't include empty dictionaries and lists in
338 // the copy. This never returns NULL, even if |this| itself is empty.
339 DictionaryValue
* DeepCopyWithoutEmptyChildren() const;
341 // Merge |dictionary| into this dictionary. This is done recursively, i.e. any
342 // sub-dictionaries will be merged as well. In case of key collisions, the
343 // passed in dictionary takes precedence and data already present will be
344 // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
345 // be freed any time after this call.
346 void MergeDictionary(const DictionaryValue
* dictionary
);
348 // Swaps contents with the |other| dictionary.
349 virtual void Swap(DictionaryValue
* other
);
351 // This class provides an iterator over both keys and values in the
352 // dictionary. It can't be used to modify the dictionary.
353 class BASE_EXPORT Iterator
{
355 explicit Iterator(const DictionaryValue
& target
);
358 bool IsAtEnd() const { return it_
== target_
.dictionary_
.end(); }
359 void Advance() { ++it_
; }
361 const std::string
& key() const { return it_
->first
; }
362 const Value
& value() const { return *it_
->second
; }
365 const DictionaryValue
& target_
;
366 ValueMap::const_iterator it_
;
369 // Overridden from Value:
370 DictionaryValue
* DeepCopy() const override
;
371 bool Equals(const Value
* other
) const override
;
374 ValueMap dictionary_
;
376 DISALLOW_COPY_AND_ASSIGN(DictionaryValue
);
379 // This type of Value represents a list of other Value values.
380 class BASE_EXPORT ListValue
: public Value
{
382 typedef ValueVector::iterator iterator
;
383 typedef ValueVector::const_iterator const_iterator
;
386 ~ListValue() override
;
388 // Clears the contents of this ListValue
391 // Returns the number of Values in this list.
392 size_t GetSize() const { return list_
.size(); }
394 // Returns whether the list is empty.
395 bool empty() const { return list_
.empty(); }
397 // Sets the list item at the given index to be the Value specified by
398 // the value given. If the index beyond the current end of the list, null
399 // Values will be used to pad out the list.
400 // Returns true if successful, or false if the index was negative or
401 // the value is a null pointer.
402 bool Set(size_t index
, Value
* in_value
);
404 // Gets the Value at the given index. Modifies |out_value| (and returns true)
405 // only if the index falls within the current list range.
406 // Note that the list always owns the Value passed out via |out_value|.
407 // |out_value| is optional and will only be set if non-NULL.
408 bool Get(size_t index
, const Value
** out_value
) const;
409 bool Get(size_t index
, Value
** out_value
);
411 // Convenience forms of Get(). Modifies |out_value| (and returns true)
412 // only if the index is valid and the Value at that index can be returned
413 // in the specified form.
414 // |out_value| is optional and will only be set if non-NULL.
415 bool GetBoolean(size_t index
, bool* out_value
) const;
416 bool GetInteger(size_t index
, int* out_value
) const;
417 // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
419 bool GetDouble(size_t index
, double* out_value
) const;
420 bool GetString(size_t index
, std::string
* out_value
) const;
421 bool GetString(size_t index
, string16
* out_value
) const;
422 bool GetBinary(size_t index
, const BinaryValue
** out_value
) const;
423 bool GetBinary(size_t index
, BinaryValue
** out_value
);
424 bool GetDictionary(size_t index
, const DictionaryValue
** out_value
) const;
425 bool GetDictionary(size_t index
, DictionaryValue
** out_value
);
426 bool GetList(size_t index
, const ListValue
** out_value
) const;
427 bool GetList(size_t index
, ListValue
** out_value
);
429 // Removes the Value with the specified index from this list.
430 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
431 // passed out via |out_value|. If |out_value| is NULL, the removed value will
432 // be deleted. This method returns true if |index| is valid; otherwise
433 // it will return false and the ListValue object will be unchanged.
434 virtual bool Remove(size_t index
, scoped_ptr
<Value
>* out_value
);
436 // Removes the first instance of |value| found in the list, if any, and
437 // deletes it. |index| is the location where |value| was found. Returns false
439 bool Remove(const Value
& value
, size_t* index
);
441 // Removes the element at |iter|. If |out_value| is NULL, the value will be
442 // deleted, otherwise ownership of the value is passed back to the caller.
443 // Returns an iterator pointing to the location of the element that
444 // followed the erased element.
445 iterator
Erase(iterator iter
, scoped_ptr
<Value
>* out_value
);
447 // Appends a Value to the end of the list.
448 void Append(Value
* in_value
);
450 // Convenience forms of Append.
451 void AppendBoolean(bool in_value
);
452 void AppendInteger(int in_value
);
453 void AppendDouble(double in_value
);
454 void AppendString(const std::string
& in_value
);
455 void AppendString(const string16
& in_value
);
456 void AppendStrings(const std::vector
<std::string
>& in_values
);
457 void AppendStrings(const std::vector
<string16
>& in_values
);
459 // Appends a Value if it's not already present. Takes ownership of the
460 // |in_value|. Returns true if successful, or false if the value was already
461 // present. If the value was already present the |in_value| is deleted.
462 bool AppendIfNotPresent(Value
* in_value
);
464 // Insert a Value at index.
465 // Returns true if successful, or false if the index was out of range.
466 bool Insert(size_t index
, Value
* in_value
);
468 // Searches for the first instance of |value| in the list using the Equals
469 // method of the Value type.
470 // Returns a const_iterator to the found item or to end() if none exists.
471 const_iterator
Find(const Value
& value
) const;
473 // Swaps contents with the |other| list.
474 virtual void Swap(ListValue
* other
);
477 iterator
begin() { return list_
.begin(); }
478 iterator
end() { return list_
.end(); }
480 const_iterator
begin() const { return list_
.begin(); }
481 const_iterator
end() const { return list_
.end(); }
483 // Overridden from Value:
484 bool GetAsList(ListValue
** out_value
) override
;
485 bool GetAsList(const ListValue
** out_value
) const override
;
486 ListValue
* DeepCopy() const override
;
487 bool Equals(const Value
* other
) const override
;
492 DISALLOW_COPY_AND_ASSIGN(ListValue
);
495 // This interface is implemented by classes that know how to serialize
497 class BASE_EXPORT ValueSerializer
{
499 virtual ~ValueSerializer();
501 virtual bool Serialize(const Value
& root
) = 0;
504 // This interface is implemented by classes that know how to deserialize Value
506 class BASE_EXPORT ValueDeserializer
{
508 virtual ~ValueDeserializer();
510 // This method deserializes the subclass-specific format into a Value object.
511 // If the return value is non-NULL, the caller takes ownership of returned
512 // Value. If the return value is NULL, and if error_code is non-NULL,
513 // error_code will be set with the underlying error.
514 // If |error_message| is non-null, it will be filled in with a formatted
515 // error message including the location of the error if appropriate.
516 virtual Value
* Deserialize(int* error_code
, std::string
* error_str
) = 0;
519 // Stream operator so Values can be used in assertion statements. In order that
520 // gtest uses this operator to print readable output on test failures, we must
521 // override each specific type. Otherwise, the default template implementation
522 // is preferred over an upcast.
523 BASE_EXPORT
std::ostream
& operator<<(std::ostream
& out
, const Value
& value
);
525 BASE_EXPORT
inline std::ostream
& operator<<(std::ostream
& out
,
526 const FundamentalValue
& value
) {
527 return out
<< static_cast<const Value
&>(value
);
530 BASE_EXPORT
inline std::ostream
& operator<<(std::ostream
& out
,
531 const StringValue
& value
) {
532 return out
<< static_cast<const Value
&>(value
);
535 BASE_EXPORT
inline std::ostream
& operator<<(std::ostream
& out
,
536 const DictionaryValue
& value
) {
537 return out
<< static_cast<const Value
&>(value
);
540 BASE_EXPORT
inline std::ostream
& operator<<(std::ostream
& out
,
541 const ListValue
& value
) {
542 return out
<< static_cast<const Value
&>(value
);
547 #endif // BASE_VALUES_H_