Autofill: improve handling of nameless, ID-less inputs.
[chromium-blink-merge.git] / base / values.h
blob4c22f3ddc3e24445ad85bb75bd648b1b0d8a0488
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();
68 // Returns the type of the value stored by the current Value object.
69 // Each type will be implemented by only one subclass of Value, so it's
70 // safe to use the Type to determine whether you can cast from
71 // Value* to (Implementing Class)*. Also, a Value object never changes
72 // its type after construction.
73 Type GetType() const { return type_; }
75 // Returns true if the current object represents a given type.
76 bool IsType(Type type) const { return type == type_; }
78 // These methods allow the convenient retrieval of the contents of the Value.
79 // If the current object can be converted into the given type, the value is
80 // returned through the |out_value| parameter and true is returned;
81 // otherwise, false is returned and |out_value| is unchanged.
82 virtual bool GetAsBoolean(bool* out_value) const;
83 virtual bool GetAsInteger(int* out_value) const;
84 virtual bool GetAsDouble(double* out_value) const;
85 virtual bool GetAsString(std::string* out_value) const;
86 virtual bool GetAsString(string16* out_value) const;
87 virtual bool GetAsString(const StringValue** out_value) const;
88 virtual bool GetAsList(ListValue** out_value);
89 virtual bool GetAsList(const ListValue** out_value) const;
90 virtual bool GetAsDictionary(DictionaryValue** out_value);
91 virtual bool GetAsDictionary(const DictionaryValue** out_value) const;
92 // Note: Do not add more types. See the file-level comment above for why.
94 // This creates a deep copy of the entire Value tree, and returns a pointer
95 // to the copy. The caller gets ownership of the copy, of course.
97 // Subclasses return their own type directly in their overrides;
98 // this works because C++ supports covariant return types.
99 virtual Value* DeepCopy() const;
101 // Compares if two Value objects have equal contents.
102 virtual bool Equals(const Value* other) const;
104 // Compares if two Value objects have equal contents. Can handle NULLs.
105 // NULLs are considered equal but different from Value::CreateNullValue().
106 static bool Equals(const Value* a, const Value* b);
108 protected:
109 // These aren't safe for end-users, but they are useful for subclasses.
110 explicit Value(Type type);
111 Value(const Value& that);
112 Value& operator=(const Value& that);
114 private:
115 Type type_;
118 // FundamentalValue represents the simple fundamental types of values.
119 class BASE_EXPORT FundamentalValue : public Value {
120 public:
121 explicit FundamentalValue(bool in_value);
122 explicit FundamentalValue(int in_value);
123 explicit FundamentalValue(double in_value);
124 ~FundamentalValue() override;
126 // Overridden from Value:
127 bool GetAsBoolean(bool* out_value) const override;
128 bool GetAsInteger(int* out_value) const override;
129 // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
130 // doubles.
131 bool GetAsDouble(double* out_value) const override;
132 FundamentalValue* DeepCopy() const override;
133 bool Equals(const Value* other) const override;
135 private:
136 union {
137 bool boolean_value_;
138 int integer_value_;
139 double double_value_;
143 class BASE_EXPORT StringValue : public Value {
144 public:
145 // Initializes a StringValue with a UTF-8 narrow character string.
146 explicit StringValue(const std::string& in_value);
148 // Initializes a StringValue with a string16.
149 explicit StringValue(const string16& in_value);
151 ~StringValue() override;
153 // Returns |value_| as a pointer or reference.
154 std::string* GetString();
155 const std::string& GetString() const;
157 // Overridden from Value:
158 bool GetAsString(std::string* out_value) const override;
159 bool GetAsString(string16* out_value) const override;
160 bool GetAsString(const StringValue** out_value) const override;
161 StringValue* DeepCopy() const override;
162 bool Equals(const Value* other) const override;
164 private:
165 std::string value_;
168 class BASE_EXPORT BinaryValue: public Value {
169 public:
170 // Creates a BinaryValue with a null buffer and size of 0.
171 BinaryValue();
173 // Creates a BinaryValue, taking ownership of the bytes pointed to by
174 // |buffer|.
175 BinaryValue(scoped_ptr<char[]> buffer, size_t size);
177 ~BinaryValue() override;
179 // For situations where you want to keep ownership of your buffer, this
180 // factory method creates a new BinaryValue by copying the contents of the
181 // buffer that's passed in.
182 static BinaryValue* CreateWithCopiedBuffer(const char* buffer, size_t size);
184 size_t GetSize() const { return size_; }
186 // May return NULL.
187 char* GetBuffer() { return buffer_.get(); }
188 const char* GetBuffer() const { return buffer_.get(); }
190 // Overridden from Value:
191 BinaryValue* DeepCopy() const override;
192 bool Equals(const Value* other) const override;
194 private:
195 scoped_ptr<char[]> buffer_;
196 size_t size_;
198 DISALLOW_COPY_AND_ASSIGN(BinaryValue);
201 // DictionaryValue provides a key-value dictionary with (optional) "path"
202 // parsing for recursive access; see the comment at the top of the file. Keys
203 // are |std::string|s and should be UTF-8 encoded.
204 class BASE_EXPORT DictionaryValue : public Value {
205 public:
206 DictionaryValue();
207 ~DictionaryValue() override;
209 // Overridden from Value:
210 bool GetAsDictionary(DictionaryValue** out_value) override;
211 bool GetAsDictionary(const DictionaryValue** out_value) const override;
213 // Returns true if the current dictionary has a value for the given key.
214 bool HasKey(const std::string& key) const;
216 // Returns the number of Values in this dictionary.
217 size_t size() const { return dictionary_.size(); }
219 // Returns whether the dictionary is empty.
220 bool empty() const { return dictionary_.empty(); }
222 // Clears any current contents of this dictionary.
223 void Clear();
225 // Sets the Value associated with the given path starting from this object.
226 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
227 // into the next DictionaryValue down. Obviously, "." can't be used
228 // within a key, but there are no other restrictions on keys.
229 // If the key at any step of the way doesn't exist, or exists but isn't
230 // a DictionaryValue, a new DictionaryValue will be created and attached
231 // to the path in that location. |in_value| must be non-null.
232 void Set(const std::string& path, scoped_ptr<Value> in_value);
233 // Deprecated version of the above. TODO(estade): remove.
234 void Set(const std::string& path, Value* in_value);
236 // Convenience forms of Set(). These methods will replace any existing
237 // value at that path, even if it has a different type.
238 void SetBoolean(const std::string& path, bool in_value);
239 void SetInteger(const std::string& path, int in_value);
240 void SetDouble(const std::string& path, double in_value);
241 void SetString(const std::string& path, const std::string& in_value);
242 void SetString(const std::string& path, const string16& in_value);
244 // Like Set(), but without special treatment of '.'. This allows e.g. URLs to
245 // be used as paths.
246 void SetWithoutPathExpansion(const std::string& key,
247 scoped_ptr<Value> in_value);
248 // Deprecated version of the above. TODO(estade): remove.
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 // |out_value| is optional and will only be set if non-NULL.
268 bool Get(const std::string& path, const Value** out_value) const;
269 bool Get(const std::string& path, Value** out_value);
271 // These are convenience forms of Get(). The value will be retrieved
272 // and the return value will be true if the path is valid and the value at
273 // the end of the path can be returned in the form specified.
274 // |out_value| is optional and will only be set if non-NULL.
275 bool GetBoolean(const std::string& path, bool* out_value) const;
276 bool GetInteger(const std::string& path, int* out_value) const;
277 // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
278 // doubles.
279 bool GetDouble(const std::string& path, double* out_value) const;
280 bool GetString(const std::string& path, std::string* out_value) const;
281 bool GetString(const std::string& path, string16* out_value) const;
282 bool GetStringASCII(const std::string& path, std::string* out_value) const;
283 bool GetBinary(const std::string& path, const BinaryValue** out_value) const;
284 bool GetBinary(const std::string& path, BinaryValue** out_value);
285 bool GetDictionary(const std::string& path,
286 const DictionaryValue** out_value) const;
287 bool GetDictionary(const std::string& path, DictionaryValue** out_value);
288 bool GetList(const std::string& path, const ListValue** out_value) const;
289 bool GetList(const std::string& path, ListValue** out_value);
291 // Like Get(), but without special treatment of '.'. This allows e.g. URLs to
292 // be used as paths.
293 bool GetWithoutPathExpansion(const std::string& key,
294 const Value** out_value) const;
295 bool GetWithoutPathExpansion(const std::string& key, Value** out_value);
296 bool GetBooleanWithoutPathExpansion(const std::string& key,
297 bool* out_value) const;
298 bool GetIntegerWithoutPathExpansion(const std::string& key,
299 int* out_value) const;
300 bool GetDoubleWithoutPathExpansion(const std::string& key,
301 double* out_value) const;
302 bool GetStringWithoutPathExpansion(const std::string& key,
303 std::string* out_value) const;
304 bool GetStringWithoutPathExpansion(const std::string& key,
305 string16* out_value) const;
306 bool GetDictionaryWithoutPathExpansion(
307 const std::string& key,
308 const DictionaryValue** out_value) const;
309 bool GetDictionaryWithoutPathExpansion(const std::string& key,
310 DictionaryValue** out_value);
311 bool GetListWithoutPathExpansion(const std::string& key,
312 const ListValue** out_value) const;
313 bool GetListWithoutPathExpansion(const std::string& key,
314 ListValue** out_value);
316 // Removes the Value with the specified path from this dictionary (or one
317 // of its child dictionaries, if the path is more than just a local key).
318 // If |out_value| is non-NULL, the removed Value will be passed out via
319 // |out_value|. If |out_value| is NULL, the removed value will be deleted.
320 // This method returns true if |path| is a valid path; otherwise it will
321 // return false and the DictionaryValue object will be unchanged.
322 virtual bool Remove(const std::string& path, scoped_ptr<Value>* out_value);
324 // Like Remove(), but without special treatment of '.'. This allows e.g. URLs
325 // to be used as paths.
326 virtual bool RemoveWithoutPathExpansion(const std::string& key,
327 scoped_ptr<Value>* out_value);
329 // Removes a path, clearing out all dictionaries on |path| that remain empty
330 // after removing the value at |path|.
331 virtual bool RemovePath(const std::string& path,
332 scoped_ptr<Value>* out_value);
334 // Makes a copy of |this| but doesn't include empty dictionaries and lists in
335 // the copy. This never returns NULL, even if |this| itself is empty.
336 DictionaryValue* DeepCopyWithoutEmptyChildren() const;
338 // Merge |dictionary| into this dictionary. This is done recursively, i.e. any
339 // sub-dictionaries will be merged as well. In case of key collisions, the
340 // passed in dictionary takes precedence and data already present will be
341 // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
342 // be freed any time after this call.
343 void MergeDictionary(const DictionaryValue* dictionary);
345 // Swaps contents with the |other| dictionary.
346 virtual void Swap(DictionaryValue* other);
348 // This class provides an iterator over both keys and values in the
349 // dictionary. It can't be used to modify the dictionary.
350 class BASE_EXPORT Iterator {
351 public:
352 explicit Iterator(const DictionaryValue& target);
353 ~Iterator();
355 bool IsAtEnd() const { return it_ == target_.dictionary_.end(); }
356 void Advance() { ++it_; }
358 const std::string& key() const { return it_->first; }
359 const Value& value() const { return *it_->second; }
361 private:
362 const DictionaryValue& target_;
363 ValueMap::const_iterator it_;
366 // Overridden from Value:
367 DictionaryValue* DeepCopy() const override;
368 bool Equals(const Value* other) const override;
370 private:
371 ValueMap dictionary_;
373 DISALLOW_COPY_AND_ASSIGN(DictionaryValue);
376 // This type of Value represents a list of other Value values.
377 class BASE_EXPORT ListValue : public Value {
378 public:
379 typedef ValueVector::iterator iterator;
380 typedef ValueVector::const_iterator const_iterator;
382 ListValue();
383 ~ListValue() override;
385 // Clears the contents of this ListValue
386 void Clear();
388 // Returns the number of Values in this list.
389 size_t GetSize() const { return list_.size(); }
391 // Returns whether the list is empty.
392 bool empty() const { return list_.empty(); }
394 // Sets the list item at the given index to be the Value specified by
395 // the value given. If the index beyond the current end of the list, null
396 // Values will be used to pad out the list.
397 // Returns true if successful, or false if the index was negative or
398 // the value is a null pointer.
399 bool Set(size_t index, Value* in_value);
401 // Gets the Value at the given index. Modifies |out_value| (and returns true)
402 // only if the index falls within the current list range.
403 // Note that the list always owns the Value passed out via |out_value|.
404 // |out_value| is optional and will only be set if non-NULL.
405 bool Get(size_t index, const Value** out_value) const;
406 bool Get(size_t index, Value** out_value);
408 // Convenience forms of Get(). Modifies |out_value| (and returns true)
409 // only if the index is valid and the Value at that index can be returned
410 // in the specified form.
411 // |out_value| is optional and will only be set if non-NULL.
412 bool GetBoolean(size_t index, bool* out_value) const;
413 bool GetInteger(size_t index, int* out_value) const;
414 // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
415 // doubles.
416 bool GetDouble(size_t index, double* out_value) const;
417 bool GetString(size_t index, std::string* out_value) const;
418 bool GetString(size_t index, string16* out_value) const;
419 bool GetBinary(size_t index, const BinaryValue** out_value) const;
420 bool GetBinary(size_t index, BinaryValue** out_value);
421 bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
422 bool GetDictionary(size_t index, DictionaryValue** out_value);
423 bool GetList(size_t index, const ListValue** out_value) const;
424 bool GetList(size_t index, ListValue** out_value);
426 // Removes the Value with the specified index from this list.
427 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
428 // passed out via |out_value|. If |out_value| is NULL, the removed value will
429 // be deleted. This method returns true if |index| is valid; otherwise
430 // it will return false and the ListValue object will be unchanged.
431 virtual bool Remove(size_t index, scoped_ptr<Value>* out_value);
433 // Removes the first instance of |value| found in the list, if any, and
434 // deletes it. |index| is the location where |value| was found. Returns false
435 // if not found.
436 bool Remove(const Value& value, size_t* index);
438 // Removes the element at |iter|. If |out_value| is NULL, the value will be
439 // deleted, otherwise ownership of the value is passed back to the caller.
440 // Returns an iterator pointing to the location of the element that
441 // followed the erased element.
442 iterator Erase(iterator iter, scoped_ptr<Value>* out_value);
444 // Appends a Value to the end of the list.
445 void Append(Value* in_value);
447 // Convenience forms of Append.
448 void AppendBoolean(bool in_value);
449 void AppendInteger(int in_value);
450 void AppendDouble(double in_value);
451 void AppendString(const std::string& in_value);
452 void AppendString(const string16& in_value);
453 void AppendStrings(const std::vector<std::string>& in_values);
454 void AppendStrings(const std::vector<string16>& in_values);
456 // Appends a Value if it's not already present. Takes ownership of the
457 // |in_value|. Returns true if successful, or false if the value was already
458 // present. If the value was already present the |in_value| is deleted.
459 bool AppendIfNotPresent(Value* in_value);
461 // Insert a Value at index.
462 // Returns true if successful, or false if the index was out of range.
463 bool Insert(size_t index, Value* in_value);
465 // Searches for the first instance of |value| in the list using the Equals
466 // method of the Value type.
467 // Returns a const_iterator to the found item or to end() if none exists.
468 const_iterator Find(const Value& value) const;
470 // Swaps contents with the |other| list.
471 virtual void Swap(ListValue* other);
473 // Iteration.
474 iterator begin() { return list_.begin(); }
475 iterator end() { return list_.end(); }
477 const_iterator begin() const { return list_.begin(); }
478 const_iterator end() const { return list_.end(); }
480 // Overridden from Value:
481 bool GetAsList(ListValue** out_value) override;
482 bool GetAsList(const ListValue** out_value) const override;
483 ListValue* DeepCopy() const override;
484 bool Equals(const Value* other) const override;
486 private:
487 ValueVector list_;
489 DISALLOW_COPY_AND_ASSIGN(ListValue);
492 // This interface is implemented by classes that know how to serialize and
493 // deserialize Value objects.
494 class BASE_EXPORT ValueSerializer {
495 public:
496 virtual ~ValueSerializer();
498 virtual bool Serialize(const Value& root) = 0;
500 // This method deserializes the subclass-specific format into a Value object.
501 // If the return value is non-NULL, the caller takes ownership of returned
502 // Value. If the return value is NULL, and if error_code is non-NULL,
503 // error_code will be set with the underlying error.
504 // If |error_message| is non-null, it will be filled in with a formatted
505 // error message including the location of the error if appropriate.
506 virtual Value* Deserialize(int* error_code, std::string* error_str) = 0;
509 // Stream operator so Values can be used in assertion statements. In order that
510 // gtest uses this operator to print readable output on test failures, we must
511 // override each specific type. Otherwise, the default template implementation
512 // is preferred over an upcast.
513 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
515 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
516 const FundamentalValue& value) {
517 return out << static_cast<const Value&>(value);
520 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
521 const StringValue& value) {
522 return out << static_cast<const Value&>(value);
525 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
526 const DictionaryValue& value) {
527 return out << static_cast<const Value&>(value);
530 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
531 const ListValue& value) {
532 return out << static_cast<const Value&>(value);
535 } // namespace base
537 #endif // BASE_VALUES_H_