Quota: Remove ifdef macros used for callback cleanup
[chromium-blink-merge.git] / base / values.h
bloba77cd3bdf702e5088faf6b04b88921a6173a956c
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"
34 namespace base {
36 class DictionaryValue;
37 class FundamentalValue;
38 class ListValue;
39 class StringValue;
40 class Value;
42 typedef std::vector<Value*> ValueVector;
43 typedef std::map<std::string, Value*> ValueMap;
45 // The Value class is the base class for Values. A Value can be instantiated
46 // via the Create*Value() factory methods, or by directly creating instances of
47 // the subclasses.
49 // See the file-level comment above for more information.
50 class BASE_EXPORT Value {
51 public:
52 enum Type {
53 TYPE_NULL = 0,
54 TYPE_BOOLEAN,
55 TYPE_INTEGER,
56 TYPE_DOUBLE,
57 TYPE_STRING,
58 TYPE_BINARY,
59 TYPE_DICTIONARY,
60 TYPE_LIST
61 // Note: Do not add more types. See the file-level comment above for why.
64 virtual ~Value();
66 static Value* CreateNullValue();
67 // DEPRECATED: Do not use the following 5 functions. Instead, use
68 // new FundamentalValue or new StringValue.
69 static FundamentalValue* CreateBooleanValue(bool in_value);
70 static FundamentalValue* CreateIntegerValue(int in_value);
71 static FundamentalValue* CreateDoubleValue(double in_value);
72 static StringValue* CreateStringValue(const std::string& in_value);
73 static StringValue* CreateStringValue(const string16& in_value);
75 // Returns the type of the value stored by the current Value object.
76 // Each type will be implemented by only one subclass of Value, so it's
77 // safe to use the Type to determine whether you can cast from
78 // Value* to (Implementing Class)*. Also, a Value object never changes
79 // its type after construction.
80 Type GetType() const { return type_; }
82 // Returns true if the current object represents a given type.
83 bool IsType(Type type) const { return type == type_; }
85 // These methods allow the convenient retrieval of the contents of the Value.
86 // If the current object can be converted into the given type, the value is
87 // returned through the |out_value| parameter and true is returned;
88 // otherwise, false is returned and |out_value| is unchanged.
89 virtual bool GetAsBoolean(bool* out_value) const;
90 virtual bool GetAsInteger(int* out_value) const;
91 virtual bool GetAsDouble(double* out_value) const;
92 virtual bool GetAsString(std::string* out_value) const;
93 virtual bool GetAsString(string16* out_value) const;
94 virtual bool GetAsString(const StringValue** out_value) const;
95 virtual bool GetAsList(ListValue** out_value);
96 virtual bool GetAsList(const ListValue** out_value) const;
97 virtual bool GetAsDictionary(DictionaryValue** out_value);
98 virtual bool GetAsDictionary(const DictionaryValue** out_value) const;
99 // Note: Do not add more types. See the file-level comment above for why.
101 // This creates a deep copy of the entire Value tree, and returns a pointer
102 // to the copy. The caller gets ownership of the copy, of course.
104 // Subclasses return their own type directly in their overrides;
105 // this works because C++ supports covariant return types.
106 virtual Value* DeepCopy() const;
108 // Compares if two Value objects have equal contents.
109 virtual bool Equals(const Value* other) const;
111 // Compares if two Value objects have equal contents. Can handle NULLs.
112 // NULLs are considered equal but different from Value::CreateNullValue().
113 static bool Equals(const Value* a, const Value* b);
115 protected:
116 // These aren't safe for end-users, but they are useful for subclasses.
117 explicit Value(Type type);
118 Value(const Value& that);
119 Value& operator=(const Value& that);
121 private:
122 Type type_;
125 // FundamentalValue represents the simple fundamental types of values.
126 class BASE_EXPORT 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();
133 // Overridden from Value:
134 virtual bool GetAsBoolean(bool* out_value) const OVERRIDE;
135 virtual bool GetAsInteger(int* out_value) const OVERRIDE;
136 virtual bool GetAsDouble(double* out_value) const OVERRIDE;
137 virtual FundamentalValue* DeepCopy() const OVERRIDE;
138 virtual 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 virtual ~StringValue();
158 // Returns |value_| as a pointer or reference.
159 std::string* GetString();
160 const std::string& GetString() const;
162 // Overridden from Value:
163 virtual bool GetAsString(std::string* out_value) const OVERRIDE;
164 virtual bool GetAsString(string16* out_value) const OVERRIDE;
165 virtual bool GetAsString(const StringValue** out_value) const OVERRIDE;
166 virtual StringValue* DeepCopy() const OVERRIDE;
167 virtual 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 virtual ~BinaryValue();
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 virtual BinaryValue* DeepCopy() const OVERRIDE;
197 virtual bool Equals(const Value* other) const OVERRIDE;
199 private:
200 scoped_ptr<char[]> buffer_;
201 size_t size_;
203 DISALLOW_COPY_AND_ASSIGN(BinaryValue);
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.
209 class BASE_EXPORT DictionaryValue : public Value {
210 public:
211 DictionaryValue();
212 virtual ~DictionaryValue();
214 // Overridden from Value:
215 virtual bool GetAsDictionary(DictionaryValue** out_value) OVERRIDE;
216 virtual bool GetAsDictionary(
217 const DictionaryValue** out_value) const OVERRIDE;
219 // Returns true if the current dictionary has a value for the given key.
220 bool HasKey(const std::string& key) const;
222 // Returns the number of Values in this dictionary.
223 size_t size() const { return dictionary_.size(); }
225 // Returns whether the dictionary is empty.
226 bool empty() const { return dictionary_.empty(); }
228 // Clears any current contents of this dictionary.
229 void Clear();
231 // Sets the Value associated with the given path starting from this object.
232 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
233 // into the next DictionaryValue down. Obviously, "." can't be used
234 // within a key, but there are no other restrictions on keys.
235 // If the key at any step of the way doesn't exist, or exists but isn't
236 // a DictionaryValue, a new DictionaryValue will be created and attached
237 // to the path in that location.
238 // Note that the dictionary takes ownership of the value referenced by
239 // |in_value|, and therefore |in_value| must be non-NULL.
240 void Set(const std::string& path, Value* in_value);
242 // Convenience forms of Set(). These methods will replace any existing
243 // value at that path, even if it has a different type.
244 void SetBoolean(const std::string& path, bool in_value);
245 void SetInteger(const std::string& path, int in_value);
246 void SetDouble(const std::string& path, double in_value);
247 void SetString(const std::string& path, const std::string& in_value);
248 void SetString(const std::string& path, const string16& in_value);
250 // Like Set(), but without special treatment of '.'. This allows e.g. URLs to
251 // be used as paths.
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 bool Get(const std::string& path, const Value** out_value) const;
271 bool Get(const std::string& path, Value** out_value);
273 // These are convenience forms of Get(). The value will be retrieved
274 // and the return value will be true if the path is valid and the value at
275 // the end of the path can be returned in the form specified.
276 bool GetBoolean(const std::string& path, bool* out_value) const;
277 bool GetInteger(const std::string& path, int* out_value) const;
278 bool GetDouble(const std::string& path, double* out_value) const;
279 bool GetString(const std::string& path, std::string* out_value) const;
280 bool GetString(const std::string& path, string16* out_value) const;
281 bool GetStringASCII(const std::string& path, std::string* out_value) const;
282 bool GetBinary(const std::string& path, const BinaryValue** out_value) const;
283 bool GetBinary(const std::string& path, BinaryValue** out_value);
284 bool GetDictionary(const std::string& path,
285 const DictionaryValue** out_value) const;
286 bool GetDictionary(const std::string& path, DictionaryValue** out_value);
287 bool GetList(const std::string& path, const ListValue** out_value) const;
288 bool GetList(const std::string& path, ListValue** out_value);
290 // Like Get(), but without special treatment of '.'. This allows e.g. URLs to
291 // be used as paths.
292 bool GetWithoutPathExpansion(const std::string& key,
293 const Value** out_value) const;
294 bool GetWithoutPathExpansion(const std::string& key, Value** out_value);
295 bool GetBooleanWithoutPathExpansion(const std::string& key,
296 bool* out_value) const;
297 bool GetIntegerWithoutPathExpansion(const std::string& key,
298 int* out_value) const;
299 bool GetDoubleWithoutPathExpansion(const std::string& key,
300 double* out_value) const;
301 bool GetStringWithoutPathExpansion(const std::string& key,
302 std::string* out_value) const;
303 bool GetStringWithoutPathExpansion(const std::string& key,
304 string16* out_value) const;
305 bool GetDictionaryWithoutPathExpansion(
306 const std::string& key,
307 const DictionaryValue** out_value) const;
308 bool GetDictionaryWithoutPathExpansion(const std::string& key,
309 DictionaryValue** out_value);
310 bool GetListWithoutPathExpansion(const std::string& key,
311 const ListValue** out_value) const;
312 bool GetListWithoutPathExpansion(const std::string& key,
313 ListValue** out_value);
315 // Removes the Value with the specified path from this dictionary (or one
316 // of its child dictionaries, if the path is more than just a local key).
317 // If |out_value| is non-NULL, the removed Value will be passed out via
318 // |out_value|. If |out_value| is NULL, the removed value will be deleted.
319 // This method returns true if |path| is a valid path; otherwise it will
320 // return false and the DictionaryValue object will be unchanged.
321 virtual bool Remove(const std::string& path, scoped_ptr<Value>* out_value);
323 // Like Remove(), but without special treatment of '.'. This allows e.g. URLs
324 // to be used as paths.
325 virtual bool RemoveWithoutPathExpansion(const std::string& key,
326 scoped_ptr<Value>* out_value);
328 // Removes a path, clearing out all dictionaries on |path| that remain empty
329 // after removing the value at |path|.
330 virtual bool RemovePath(const std::string& path,
331 scoped_ptr<Value>* out_value);
333 // Makes a copy of |this| but doesn't include empty dictionaries and lists in
334 // the copy. This never returns NULL, even if |this| itself is empty.
335 DictionaryValue* DeepCopyWithoutEmptyChildren() const;
337 // Merge |dictionary| into this dictionary. This is done recursively, i.e. any
338 // sub-dictionaries will be merged as well. In case of key collisions, the
339 // passed in dictionary takes precedence and data already present will be
340 // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
341 // be freed any time after this call.
342 void MergeDictionary(const DictionaryValue* dictionary);
344 // Swaps contents with the |other| dictionary.
345 virtual void Swap(DictionaryValue* other);
347 // This class provides an iterator over both keys and values in the
348 // dictionary. It can't be used to modify the dictionary.
349 class BASE_EXPORT Iterator {
350 public:
351 explicit Iterator(const DictionaryValue& target);
352 ~Iterator();
354 bool IsAtEnd() const { return it_ == target_.dictionary_.end(); }
355 void Advance() { ++it_; }
357 const std::string& key() const { return it_->first; }
358 const Value& value() const { return *it_->second; }
360 private:
361 const DictionaryValue& target_;
362 ValueMap::const_iterator it_;
365 // Overridden from Value:
366 virtual DictionaryValue* DeepCopy() const OVERRIDE;
367 virtual bool Equals(const Value* other) const OVERRIDE;
369 private:
370 ValueMap dictionary_;
372 DISALLOW_COPY_AND_ASSIGN(DictionaryValue);
375 // This type of Value represents a list of other Value values.
376 class BASE_EXPORT ListValue : public Value {
377 public:
378 typedef ValueVector::iterator iterator;
379 typedef ValueVector::const_iterator const_iterator;
381 ListValue();
382 virtual ~ListValue();
384 // Clears the contents of this ListValue
385 void Clear();
387 // Returns the number of Values in this list.
388 size_t GetSize() const { return list_.size(); }
390 // Returns whether the list is empty.
391 bool empty() const { return list_.empty(); }
393 // Sets the list item at the given index to be the Value specified by
394 // the value given. If the index beyond the current end of the list, null
395 // Values will be used to pad out the list.
396 // Returns true if successful, or false if the index was negative or
397 // the value is a null pointer.
398 bool Set(size_t index, Value* in_value);
400 // Gets the Value at the given index. Modifies |out_value| (and returns true)
401 // only if the index falls within the current list range.
402 // Note that the list always owns the Value passed out via |out_value|.
403 bool Get(size_t index, const Value** out_value) const;
404 bool Get(size_t index, Value** out_value);
406 // Convenience forms of Get(). Modifies |out_value| (and returns true)
407 // only if the index is valid and the Value at that index can be returned
408 // in the specified form.
409 bool GetBoolean(size_t index, bool* out_value) const;
410 bool GetInteger(size_t index, int* out_value) const;
411 bool GetDouble(size_t index, double* out_value) const;
412 bool GetString(size_t index, std::string* out_value) const;
413 bool GetString(size_t index, string16* out_value) const;
414 bool GetBinary(size_t index, const BinaryValue** out_value) const;
415 bool GetBinary(size_t index, BinaryValue** out_value);
416 bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
417 bool GetDictionary(size_t index, DictionaryValue** out_value);
418 bool GetList(size_t index, const ListValue** out_value) const;
419 bool GetList(size_t index, ListValue** out_value);
421 // Removes the Value with the specified index from this list.
422 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
423 // passed out via |out_value|. If |out_value| is NULL, the removed value will
424 // be deleted. This method returns true if |index| is valid; otherwise
425 // it will return false and the ListValue object will be unchanged.
426 virtual bool Remove(size_t index, scoped_ptr<Value>* out_value);
428 // Removes the first instance of |value| found in the list, if any, and
429 // deletes it. |index| is the location where |value| was found. Returns false
430 // if not found.
431 bool Remove(const Value& value, size_t* index);
433 // Removes the element at |iter|. If |out_value| is NULL, the value will be
434 // deleted, otherwise ownership of the value is passed back to the caller.
435 // Returns an iterator pointing to the location of the element that
436 // followed the erased element.
437 iterator Erase(iterator iter, scoped_ptr<Value>* out_value);
439 // Appends a Value to the end of the list.
440 void Append(Value* in_value);
442 // Convenience forms of Append.
443 void AppendBoolean(bool in_value);
444 void AppendInteger(int in_value);
445 void AppendDouble(double in_value);
446 void AppendString(const std::string& in_value);
447 void AppendString(const string16& in_value);
448 void AppendStrings(const std::vector<std::string>& in_values);
449 void AppendStrings(const std::vector<string16>& in_values);
451 // Appends a Value if it's not already present. Takes ownership of the
452 // |in_value|. Returns true if successful, or false if the value was already
453 // present. If the value was already present the |in_value| is deleted.
454 bool AppendIfNotPresent(Value* in_value);
456 // Insert a Value at index.
457 // Returns true if successful, or false if the index was out of range.
458 bool Insert(size_t index, Value* in_value);
460 // Searches for the first instance of |value| in the list using the Equals
461 // method of the Value type.
462 // Returns a const_iterator to the found item or to end() if none exists.
463 const_iterator Find(const Value& value) const;
465 // Swaps contents with the |other| list.
466 virtual void Swap(ListValue* other);
468 // Iteration.
469 iterator begin() { return list_.begin(); }
470 iterator end() { return list_.end(); }
472 const_iterator begin() const { return list_.begin(); }
473 const_iterator end() const { return list_.end(); }
475 // Overridden from Value:
476 virtual bool GetAsList(ListValue** out_value) OVERRIDE;
477 virtual bool GetAsList(const ListValue** out_value) const OVERRIDE;
478 virtual ListValue* DeepCopy() const OVERRIDE;
479 virtual bool Equals(const Value* other) const OVERRIDE;
481 private:
482 ValueVector list_;
484 DISALLOW_COPY_AND_ASSIGN(ListValue);
487 // This interface is implemented by classes that know how to serialize and
488 // deserialize Value objects.
489 class BASE_EXPORT ValueSerializer {
490 public:
491 virtual ~ValueSerializer();
493 virtual bool Serialize(const Value& root) = 0;
495 // This method deserializes the subclass-specific format into a Value object.
496 // If the return value is non-NULL, the caller takes ownership of returned
497 // Value. If the return value is NULL, and if error_code is non-NULL,
498 // error_code will be set with the underlying error.
499 // If |error_message| is non-null, it will be filled in with a formatted
500 // error message including the location of the error if appropriate.
501 virtual Value* Deserialize(int* error_code, std::string* error_str) = 0;
504 // Stream operator so Values can be used in assertion statements. In order that
505 // gtest uses this operator to print readable output on test failures, we must
506 // override each specific type. Otherwise, the default template implementation
507 // is preferred over an upcast.
508 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
510 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
511 const FundamentalValue& value) {
512 return out << static_cast<const Value&>(value);
515 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
516 const StringValue& value) {
517 return out << static_cast<const Value&>(value);
520 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
521 const DictionaryValue& value) {
522 return out << static_cast<const Value&>(value);
525 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
526 const ListValue& value) {
527 return out << static_cast<const Value&>(value);
530 } // namespace base
532 #endif // BASE_VALUES_H_