Roll src/third_party/WebKit 6d85854:7e30d51 (svn 202247:202248)
[chromium-blink-merge.git] / base / values.h
blob56be542d7477b8c02d725aa7690e1b82dacc70d3
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.
7 //
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_
20 #include <stddef.h>
22 #include <iosfwd>
23 #include <map>
24 #include <string>
25 #include <utility>
26 #include <vector>
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"
33 #include "base/strings/string_piece.h"
35 namespace base {
37 class BinaryValue;
38 class DictionaryValue;
39 class FundamentalValue;
40 class ListValue;
41 class StringValue;
42 class Value;
44 typedef std::vector<Value*> ValueVector;
45 typedef std::map<std::string, Value*> ValueMap;
47 // The Value class is the base class for Values. A Value can be instantiated
48 // via the Create*Value() factory methods, or by directly creating instances of
49 // the subclasses.
51 // See the file-level comment above for more information.
52 class BASE_EXPORT Value {
53 public:
54 enum Type {
55 TYPE_NULL = 0,
56 TYPE_BOOLEAN,
57 TYPE_INTEGER,
58 TYPE_DOUBLE,
59 TYPE_STRING,
60 TYPE_BINARY,
61 TYPE_DICTIONARY,
62 TYPE_LIST
63 // Note: Do not add more types. See the file-level comment above for why.
66 virtual ~Value();
68 static scoped_ptr<Value> CreateNullValue();
70 // Returns the type of the value stored by the current Value object.
71 // Each type will be implemented by only one subclass of Value, so it's
72 // safe to use the Type to determine whether you can cast from
73 // Value* to (Implementing Class)*. Also, a Value object never changes
74 // its type after construction.
75 Type GetType() const { return type_; }
77 // Returns true if the current object represents a given type.
78 bool IsType(Type type) const { return type == type_; }
80 // These methods allow the convenient retrieval of the contents of the Value.
81 // If the current object can be converted into the given type, the value is
82 // returned through the |out_value| parameter and true is returned;
83 // otherwise, false is returned and |out_value| is unchanged.
84 virtual bool GetAsBoolean(bool* out_value) const;
85 virtual bool GetAsInteger(int* out_value) const;
86 virtual bool GetAsDouble(double* out_value) const;
87 virtual bool GetAsString(std::string* out_value) const;
88 virtual bool GetAsString(string16* out_value) const;
89 virtual bool GetAsString(const StringValue** out_value) const;
90 virtual bool GetAsBinary(const BinaryValue** out_value) const;
91 virtual bool GetAsList(ListValue** out_value);
92 virtual bool GetAsList(const ListValue** out_value) const;
93 virtual bool GetAsDictionary(DictionaryValue** out_value);
94 virtual bool GetAsDictionary(const DictionaryValue** out_value) const;
95 // Note: Do not add more types. See the file-level comment above for why.
97 // This creates a deep copy of the entire Value tree, and returns a pointer
98 // to the copy. The caller gets ownership of the copy, of course.
100 // Subclasses return their own type directly in their overrides;
101 // this works because C++ supports covariant return types.
102 virtual Value* DeepCopy() const;
103 // Preferred version of DeepCopy. TODO(estade): remove the above.
104 scoped_ptr<Value> CreateDeepCopy() const;
106 // Compares if two Value objects have equal contents.
107 virtual bool Equals(const Value* other) const;
109 // Compares if two Value objects have equal contents. Can handle NULLs.
110 // NULLs are considered equal but different from Value::CreateNullValue().
111 static bool Equals(const Value* a, const Value* b);
113 protected:
114 // These aren't safe for end-users, but they are useful for subclasses.
115 explicit Value(Type type);
116 Value(const Value& that);
117 Value& operator=(const Value& that);
119 private:
120 Type type_;
123 // FundamentalValue represents the simple fundamental types of values.
124 class BASE_EXPORT FundamentalValue : public Value {
125 public:
126 explicit FundamentalValue(bool in_value);
127 explicit FundamentalValue(int in_value);
128 explicit FundamentalValue(double in_value);
129 ~FundamentalValue() override;
131 // Overridden from Value:
132 bool GetAsBoolean(bool* out_value) const override;
133 bool GetAsInteger(int* out_value) const override;
134 // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
135 // doubles.
136 bool GetAsDouble(double* out_value) const override;
137 FundamentalValue* DeepCopy() const override;
138 bool Equals(const Value* other) const override;
140 private:
141 union {
142 bool boolean_value_;
143 int integer_value_;
144 double double_value_;
148 class BASE_EXPORT StringValue : public Value {
149 public:
150 // Initializes a StringValue with a UTF-8 narrow character string.
151 explicit StringValue(const std::string& in_value);
153 // Initializes a StringValue with a string16.
154 explicit StringValue(const string16& in_value);
156 ~StringValue() override;
158 // Returns |value_| as a pointer or reference.
159 std::string* GetString();
160 const std::string& GetString() const;
162 // Overridden from Value:
163 bool GetAsString(std::string* out_value) const override;
164 bool GetAsString(string16* out_value) const override;
165 bool GetAsString(const StringValue** out_value) const override;
166 StringValue* DeepCopy() const override;
167 bool Equals(const Value* other) const override;
169 private:
170 std::string value_;
173 class BASE_EXPORT BinaryValue: public Value {
174 public:
175 // Creates a BinaryValue with a null buffer and size of 0.
176 BinaryValue();
178 // Creates a BinaryValue, taking ownership of the bytes pointed to by
179 // |buffer|.
180 BinaryValue(scoped_ptr<char[]> buffer, size_t size);
182 ~BinaryValue() override;
184 // For situations where you want to keep ownership of your buffer, this
185 // factory method creates a new BinaryValue by copying the contents of the
186 // buffer that's passed in.
187 static BinaryValue* CreateWithCopiedBuffer(const char* buffer, size_t size);
189 size_t GetSize() const { return size_; }
191 // May return NULL.
192 char* GetBuffer() { return buffer_.get(); }
193 const char* GetBuffer() const { return buffer_.get(); }
195 // Overridden from Value:
196 bool GetAsBinary(const BinaryValue** out_value) const override;
197 BinaryValue* DeepCopy() const override;
198 bool Equals(const Value* other) const override;
200 private:
201 scoped_ptr<char[]> buffer_;
202 size_t size_;
204 DISALLOW_COPY_AND_ASSIGN(BinaryValue);
207 // DictionaryValue provides a key-value dictionary with (optional) "path"
208 // parsing for recursive access; see the comment at the top of the file. Keys
209 // are |std::string|s and should be UTF-8 encoded.
210 class BASE_EXPORT DictionaryValue : public Value {
211 public:
212 // Returns |value| if it is a dictionary, nullptr otherwise.
213 static scoped_ptr<DictionaryValue> From(scoped_ptr<Value> value);
215 DictionaryValue();
216 ~DictionaryValue() override;
218 // Overridden from Value:
219 bool GetAsDictionary(DictionaryValue** out_value) override;
220 bool GetAsDictionary(const DictionaryValue** out_value) const override;
222 // Returns true if the current dictionary has a value for the given key.
223 bool HasKey(const std::string& key) const;
225 // Returns the number of Values in this dictionary.
226 size_t size() const { return dictionary_.size(); }
228 // Returns whether the dictionary is empty.
229 bool empty() const { return dictionary_.empty(); }
231 // Clears any current contents of this dictionary.
232 void Clear();
234 // Sets the Value associated with the given path starting from this object.
235 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
236 // into the next DictionaryValue down. Obviously, "." can't be used
237 // within a key, but there are no other restrictions on keys.
238 // If the key at any step of the way doesn't exist, or exists but isn't
239 // a DictionaryValue, a new DictionaryValue will be created and attached
240 // to the path in that location. |in_value| must be non-null.
241 void Set(const std::string& path, scoped_ptr<Value> in_value);
242 // Deprecated version of the above. TODO(estade): remove.
243 void Set(const std::string& path, Value* in_value);
245 // Convenience forms of Set(). These methods will replace any existing
246 // value at that path, even if it has a different type.
247 void SetBoolean(const std::string& path, bool in_value);
248 void SetInteger(const std::string& path, int in_value);
249 void SetDouble(const std::string& path, double in_value);
250 void SetString(const std::string& path, const std::string& in_value);
251 void SetString(const std::string& path, const string16& in_value);
253 // Like Set(), but without special treatment of '.'. This allows e.g. URLs to
254 // be used as paths.
255 void SetWithoutPathExpansion(const std::string& key,
256 scoped_ptr<Value> in_value);
257 // Deprecated version of the above. TODO(estade): remove.
258 void SetWithoutPathExpansion(const std::string& key, Value* in_value);
260 // Convenience forms of SetWithoutPathExpansion().
261 void SetBooleanWithoutPathExpansion(const std::string& path, bool in_value);
262 void SetIntegerWithoutPathExpansion(const std::string& path, int in_value);
263 void SetDoubleWithoutPathExpansion(const std::string& path, double in_value);
264 void SetStringWithoutPathExpansion(const std::string& path,
265 const std::string& in_value);
266 void SetStringWithoutPathExpansion(const std::string& path,
267 const string16& in_value);
269 // Gets the Value associated with the given path starting from this object.
270 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
271 // into the next DictionaryValue down. If the path can be resolved
272 // successfully, the value for the last key in the path will be returned
273 // through the |out_value| parameter, and the function will return true.
274 // Otherwise, it will return false and |out_value| will be untouched.
275 // Note that the dictionary always owns the value that's returned.
276 // |out_value| is optional and will only be set if non-NULL.
277 bool Get(StringPiece path, const Value** out_value) const;
278 bool Get(StringPiece path, Value** out_value);
280 // These are convenience forms of Get(). The value will be retrieved
281 // and the return value will be true if the path is valid and the value at
282 // the end of the path can be returned in the form specified.
283 // |out_value| is optional and will only be set if non-NULL.
284 bool GetBoolean(const std::string& path, bool* out_value) const;
285 bool GetInteger(const std::string& path, int* out_value) const;
286 // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
287 // doubles.
288 bool GetDouble(const std::string& path, double* out_value) const;
289 bool GetString(const std::string& path, std::string* out_value) const;
290 bool GetString(const std::string& path, string16* out_value) const;
291 bool GetStringASCII(const std::string& path, std::string* out_value) const;
292 bool GetBinary(const std::string& path, const BinaryValue** out_value) const;
293 bool GetBinary(const std::string& path, BinaryValue** out_value);
294 bool GetDictionary(StringPiece path,
295 const DictionaryValue** out_value) const;
296 bool GetDictionary(StringPiece path, DictionaryValue** out_value);
297 bool GetList(const std::string& path, const ListValue** out_value) const;
298 bool GetList(const std::string& path, ListValue** out_value);
300 // Like Get(), but without special treatment of '.'. This allows e.g. URLs to
301 // be used as paths.
302 bool GetWithoutPathExpansion(const std::string& key,
303 const Value** out_value) const;
304 bool GetWithoutPathExpansion(const std::string& key, Value** out_value);
305 bool GetBooleanWithoutPathExpansion(const std::string& key,
306 bool* out_value) const;
307 bool GetIntegerWithoutPathExpansion(const std::string& key,
308 int* out_value) const;
309 bool GetDoubleWithoutPathExpansion(const std::string& key,
310 double* out_value) const;
311 bool GetStringWithoutPathExpansion(const std::string& key,
312 std::string* out_value) const;
313 bool GetStringWithoutPathExpansion(const std::string& key,
314 string16* out_value) const;
315 bool GetDictionaryWithoutPathExpansion(
316 const std::string& key,
317 const DictionaryValue** out_value) const;
318 bool GetDictionaryWithoutPathExpansion(const std::string& key,
319 DictionaryValue** out_value);
320 bool GetListWithoutPathExpansion(const std::string& key,
321 const ListValue** out_value) const;
322 bool GetListWithoutPathExpansion(const std::string& key,
323 ListValue** out_value);
325 // Removes the Value with the specified path from this dictionary (or one
326 // of its child dictionaries, if the path is more than just a local key).
327 // If |out_value| is non-NULL, the removed Value will be passed out via
328 // |out_value|. If |out_value| is NULL, the removed value will be deleted.
329 // This method returns true if |path| is a valid path; otherwise it will
330 // return false and the DictionaryValue object will be unchanged.
331 virtual bool Remove(const std::string& path, scoped_ptr<Value>* out_value);
333 // Like Remove(), but without special treatment of '.'. This allows e.g. URLs
334 // to be used as paths.
335 virtual bool RemoveWithoutPathExpansion(const std::string& key,
336 scoped_ptr<Value>* out_value);
338 // Removes a path, clearing out all dictionaries on |path| that remain empty
339 // after removing the value at |path|.
340 virtual bool RemovePath(const std::string& path,
341 scoped_ptr<Value>* out_value);
343 // Makes a copy of |this| but doesn't include empty dictionaries and lists in
344 // the copy. This never returns NULL, even if |this| itself is empty.
345 scoped_ptr<DictionaryValue> DeepCopyWithoutEmptyChildren() const;
347 // Merge |dictionary| into this dictionary. This is done recursively, i.e. any
348 // sub-dictionaries will be merged as well. In case of key collisions, the
349 // passed in dictionary takes precedence and data already present will be
350 // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
351 // be freed any time after this call.
352 void MergeDictionary(const DictionaryValue* dictionary);
354 // Swaps contents with the |other| dictionary.
355 virtual void Swap(DictionaryValue* other);
357 // This class provides an iterator over both keys and values in the
358 // dictionary. It can't be used to modify the dictionary.
359 class BASE_EXPORT Iterator {
360 public:
361 explicit Iterator(const DictionaryValue& target);
362 ~Iterator();
364 bool IsAtEnd() const { return it_ == target_.dictionary_.end(); }
365 void Advance() { ++it_; }
367 const std::string& key() const { return it_->first; }
368 const Value& value() const { return *it_->second; }
370 private:
371 const DictionaryValue& target_;
372 ValueMap::const_iterator it_;
375 // Overridden from Value:
376 DictionaryValue* DeepCopy() const override;
377 // Preferred version of DeepCopy. TODO(estade): remove the above.
378 scoped_ptr<DictionaryValue> CreateDeepCopy() const;
379 bool Equals(const Value* other) const override;
381 private:
382 ValueMap dictionary_;
384 DISALLOW_COPY_AND_ASSIGN(DictionaryValue);
387 // This type of Value represents a list of other Value values.
388 class BASE_EXPORT ListValue : public Value {
389 public:
390 typedef ValueVector::iterator iterator;
391 typedef ValueVector::const_iterator const_iterator;
393 // Returns |value| if it is a list, nullptr otherwise.
394 static scoped_ptr<ListValue> From(scoped_ptr<Value> value);
396 ListValue();
397 ~ListValue() override;
399 // Clears the contents of this ListValue
400 void Clear();
402 // Returns the number of Values in this list.
403 size_t GetSize() const { return list_.size(); }
405 // Returns whether the list is empty.
406 bool empty() const { return list_.empty(); }
408 // Sets the list item at the given index to be the Value specified by
409 // the value given. If the index beyond the current end of the list, null
410 // Values will be used to pad out the list.
411 // Returns true if successful, or false if the index was negative or
412 // the value is a null pointer.
413 bool Set(size_t index, Value* in_value);
414 // Preferred version of the above. TODO(estade): remove the above.
415 bool Set(size_t index, scoped_ptr<Value> in_value);
417 // Gets the Value at the given index. Modifies |out_value| (and returns true)
418 // only if the index falls within the current list range.
419 // Note that the list always owns the Value passed out via |out_value|.
420 // |out_value| is optional and will only be set if non-NULL.
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 // |out_value| is optional and will only be set if non-NULL.
428 bool GetBoolean(size_t index, bool* out_value) const;
429 bool GetInteger(size_t index, int* out_value) const;
430 // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
431 // doubles.
432 bool GetDouble(size_t index, double* out_value) const;
433 bool GetString(size_t index, std::string* out_value) const;
434 bool GetString(size_t index, string16* out_value) const;
435 bool GetBinary(size_t index, const BinaryValue** out_value) const;
436 bool GetBinary(size_t index, BinaryValue** out_value);
437 bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
438 bool GetDictionary(size_t index, DictionaryValue** out_value);
439 bool GetList(size_t index, const ListValue** out_value) const;
440 bool GetList(size_t index, ListValue** out_value);
442 // Removes the Value with the specified index from this list.
443 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
444 // passed out via |out_value|. If |out_value| is NULL, the removed value will
445 // be deleted. This method returns true if |index| is valid; otherwise
446 // it will return false and the ListValue object will be unchanged.
447 virtual bool Remove(size_t index, scoped_ptr<Value>* out_value);
449 // Removes the first instance of |value| found in the list, if any, and
450 // deletes it. |index| is the location where |value| was found. Returns false
451 // if not found.
452 bool Remove(const Value& value, size_t* index);
454 // Removes the element at |iter|. If |out_value| is NULL, the value will be
455 // deleted, otherwise ownership of the value is passed back to the caller.
456 // Returns an iterator pointing to the location of the element that
457 // followed the erased element.
458 iterator Erase(iterator iter, scoped_ptr<Value>* out_value);
460 // Appends a Value to the end of the list.
461 void Append(scoped_ptr<Value> in_value);
462 // Deprecated version of the above. TODO(estade): remove.
463 void Append(Value* in_value);
465 // Convenience forms of Append.
466 void AppendBoolean(bool in_value);
467 void AppendInteger(int in_value);
468 void AppendDouble(double in_value);
469 void AppendString(const std::string& in_value);
470 void AppendString(const string16& in_value);
471 void AppendStrings(const std::vector<std::string>& in_values);
472 void AppendStrings(const std::vector<string16>& in_values);
474 // Appends a Value if it's not already present. Takes ownership of the
475 // |in_value|. Returns true if successful, or false if the value was already
476 // present. If the value was already present the |in_value| is deleted.
477 bool AppendIfNotPresent(Value* in_value);
479 // Insert a Value at index.
480 // Returns true if successful, or false if the index was out of range.
481 bool Insert(size_t index, Value* in_value);
483 // Searches for the first instance of |value| in the list using the Equals
484 // method of the Value type.
485 // Returns a const_iterator to the found item or to end() if none exists.
486 const_iterator Find(const Value& value) const;
488 // Swaps contents with the |other| list.
489 virtual void Swap(ListValue* other);
491 // Iteration.
492 iterator begin() { return list_.begin(); }
493 iterator end() { return list_.end(); }
495 const_iterator begin() const { return list_.begin(); }
496 const_iterator end() const { return list_.end(); }
498 // Overridden from Value:
499 bool GetAsList(ListValue** out_value) override;
500 bool GetAsList(const ListValue** out_value) const override;
501 ListValue* DeepCopy() const override;
502 bool Equals(const Value* other) const override;
504 // Preferred version of DeepCopy. TODO(estade): remove DeepCopy.
505 scoped_ptr<ListValue> CreateDeepCopy() const;
507 private:
508 ValueVector list_;
510 DISALLOW_COPY_AND_ASSIGN(ListValue);
513 // This interface is implemented by classes that know how to serialize
514 // Value objects.
515 class BASE_EXPORT ValueSerializer {
516 public:
517 virtual ~ValueSerializer();
519 virtual bool Serialize(const Value& root) = 0;
522 // This interface is implemented by classes that know how to deserialize Value
523 // objects.
524 class BASE_EXPORT ValueDeserializer {
525 public:
526 virtual ~ValueDeserializer();
528 // This method deserializes the subclass-specific format into a Value object.
529 // If the return value is non-NULL, the caller takes ownership of returned
530 // Value. If the return value is NULL, and if error_code is non-NULL,
531 // error_code will be set with the underlying error.
532 // If |error_message| is non-null, it will be filled in with a formatted
533 // error message including the location of the error if appropriate.
534 virtual Value* Deserialize(int* error_code, std::string* error_str) = 0;
537 // Stream operator so Values can be used in assertion statements. In order that
538 // gtest uses this operator to print readable output on test failures, we must
539 // override each specific type. Otherwise, the default template implementation
540 // is preferred over an upcast.
541 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
543 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
544 const FundamentalValue& value) {
545 return out << static_cast<const Value&>(value);
548 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
549 const StringValue& value) {
550 return out << static_cast<const Value&>(value);
553 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
554 const DictionaryValue& value) {
555 return out << static_cast<const Value&>(value);
558 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
559 const ListValue& value) {
560 return out << static_cast<const Value&>(value);
563 } // namespace base
565 #endif // BASE_VALUES_H_