• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
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.
11 //
12 // IN PARTICULAR this means that there is no support for int64_t 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.
16 //
17 // NOTE: A Value parameter that is always a Value::STRING should just be passed
18 // as a std::string. Similarly for Values that are always Value::DICTIONARY
19 // (should be flat_map), Value::LIST (should be std::vector), et cetera.
20 
21 #ifndef BASE_VALUES_H_
22 #define BASE_VALUES_H_
23 
24 #include <stddef.h>
25 #include <stdint.h>
26 
27 #include <iosfwd>
28 #include <map>
29 #include <memory>
30 #include <string>
31 #include <utility>
32 #include <vector>
33 
34 #include "base/base_export.h"
35 #include "base/containers/flat_map.h"
36 #include "base/containers/span.h"
37 #include "base/macros.h"
38 #include "base/strings/string16.h"
39 #include "base/strings/string_piece.h"
40 #include "base/value_iterators.h"
41 
42 namespace base {
43 
44 class DictionaryValue;
45 class ListValue;
46 class Value;
47 
48 // The Value class is the base class for Values. A Value can be instantiated
49 // via passing the appropriate type or backing storage to the constructor.
50 //
51 // See the file-level comment above for more information.
52 //
53 // base::Value is currently in the process of being refactored. Design doc:
54 // https://docs.google.com/document/d/1uDLu5uTRlCWePxQUEHc8yNQdEoE1BDISYdpggWEABnw
55 //
56 // Previously (which is how most code that currently exists is written), Value
57 // used derived types to implement the individual data types, and base::Value
58 // was just a base class to refer to them. This required everything be heap
59 // allocated.
60 //
61 // OLD WAY:
62 //
63 //   std::unique_ptr<base::Value> GetFoo() {
64 //     std::unique_ptr<DictionaryValue> dict;
65 //     dict->SetString("mykey", foo);
66 //     return dict;
67 //   }
68 //
69 // The new design makes base::Value a variant type that holds everything in
70 // a union. It is now recommended to pass by value with std::move rather than
71 // use heap allocated values. The DictionaryValue and ListValue subclasses
72 // exist only as a compatibility shim that we're in the process of removing.
73 //
74 // NEW WAY:
75 //
76 //   base::Value GetFoo() {
77 //     base::Value dict(base::Value::Type::DICTIONARY);
78 //     dict.SetKey("mykey", base::Value(foo));
79 //     return dict;
80 //   }
81 class BASE_EXPORT Value {
82  public:
83   using BlobStorage = std::vector<char>;
84   using DictStorage = flat_map<std::string, std::unique_ptr<Value>>;
85   using ListStorage = std::vector<Value>;
86 
87   enum class Type {
88     NONE = 0,
89     BOOLEAN,
90     INTEGER,
91     DOUBLE,
92     STRING,
93     BINARY,
94     DICTIONARY,
95     LIST
96     // Note: Do not add more types. See the file-level comment above for why.
97   };
98 
99   // For situations where you want to keep ownership of your buffer, this
100   // factory method creates a new BinaryValue by copying the contents of the
101   // buffer that's passed in.
102   // DEPRECATED, use std::make_unique<Value>(const BlobStorage&) instead.
103   // TODO(crbug.com/646113): Delete this and migrate callsites.
104   static std::unique_ptr<Value> CreateWithCopiedBuffer(const char* buffer,
105                                                        size_t size);
106 
107   // Adaptors for converting from the old way to the new way and vice versa.
108   static Value FromUniquePtrValue(std::unique_ptr<Value> val);
109   static std::unique_ptr<Value> ToUniquePtrValue(Value val);
110 
111   Value(Value&& that) noexcept;
112   Value() noexcept;  // A null value.
113 
114   // Value's copy constructor and copy assignment operator are deleted. Use this
115   // to obtain a deep copy explicitly.
116   Value Clone() const;
117 
118   explicit Value(Type type);
119   explicit Value(bool in_bool);
120   explicit Value(int in_int);
121   explicit Value(double in_double);
122 
123   // Value(const char*) and Value(const char16*) are required despite
124   // Value(StringPiece) and Value(StringPiece16) because otherwise the
125   // compiler will choose the Value(bool) constructor for these arguments.
126   // Value(std::string&&) allow for efficient move construction.
127   explicit Value(const char* in_string);
128   explicit Value(StringPiece in_string);
129   explicit Value(std::string&& in_string) noexcept;
130   explicit Value(const char16* in_string16);
131   explicit Value(StringPiece16 in_string16);
132 
133   explicit Value(const BlobStorage& in_blob);
134   explicit Value(BlobStorage&& in_blob) noexcept;
135 
136   explicit Value(const DictStorage& in_dict);
137   explicit Value(DictStorage&& in_dict) noexcept;
138 
139   explicit Value(const ListStorage& in_list);
140   explicit Value(ListStorage&& in_list) noexcept;
141 
142   Value& operator=(Value&& that) noexcept;
143 
144   ~Value();
145 
146   // Returns the name for a given |type|.
147   static const char* GetTypeName(Type type);
148 
149   // Returns the type of the value stored by the current Value object.
type()150   Type type() const { return type_; }
151 
152   // Returns true if the current object represents a given type.
is_none()153   bool is_none() const { return type() == Type::NONE; }
is_bool()154   bool is_bool() const { return type() == Type::BOOLEAN; }
is_int()155   bool is_int() const { return type() == Type::INTEGER; }
is_double()156   bool is_double() const { return type() == Type::DOUBLE; }
is_string()157   bool is_string() const { return type() == Type::STRING; }
is_blob()158   bool is_blob() const { return type() == Type::BINARY; }
is_dict()159   bool is_dict() const { return type() == Type::DICTIONARY; }
is_list()160   bool is_list() const { return type() == Type::LIST; }
161 
162   // These will all fatally assert if the type doesn't match.
163   bool GetBool() const;
164   int GetInt() const;
165   double GetDouble() const;  // Implicitly converts from int if necessary.
166   const std::string& GetString() const;
167   const BlobStorage& GetBlob() const;
168 
169   ListStorage& GetList();
170   const ListStorage& GetList() const;
171 
172   // |FindKey| looks up |key| in the underlying dictionary. If found, it returns
173   // a pointer to the element. Otherwise it returns nullptr.
174   // returned. Callers are expected to perform a check against null before using
175   // the pointer.
176   // Note: This fatally asserts if type() is not Type::DICTIONARY.
177   //
178   // Example:
179   //   auto* found = FindKey("foo");
180   Value* FindKey(StringPiece key);
181   const Value* FindKey(StringPiece key) const;
182 
183   // |FindKeyOfType| is similar to |FindKey|, but it also requires the found
184   // value to have type |type|. If no type is found, or the found value is of a
185   // different type nullptr is returned.
186   // Callers are expected to perform a check against null before using the
187   // pointer.
188   // Note: This fatally asserts if type() is not Type::DICTIONARY.
189   //
190   // Example:
191   //   auto* found = FindKey("foo", Type::DOUBLE);
192   Value* FindKeyOfType(StringPiece key, Type type);
193   const Value* FindKeyOfType(StringPiece key, Type type) const;
194 
195   // |SetKey| looks up |key| in the underlying dictionary and sets the mapped
196   // value to |value|. If |key| could not be found, a new element is inserted.
197   // A pointer to the modified item is returned.
198   // Note: This fatally asserts if type() is not Type::DICTIONARY.
199   //
200   // Example:
201   //   SetKey("foo", std::move(myvalue));
202   Value* SetKey(StringPiece key, Value value);
203   // This overload results in a performance improvement for std::string&&.
204   Value* SetKey(std::string&& key, Value value);
205   // This overload is necessary to avoid ambiguity for const char* arguments.
206   Value* SetKey(const char* key, Value value);
207 
208   // This attemps to remove the value associated with |key|. In case of failure,
209   // e.g. the key does not exist, |false| is returned and the underlying
210   // dictionary is not changed. In case of success, |key| is deleted from the
211   // dictionary and the method returns |true|.
212   // Note: This fatally asserts if type() is not Type::DICTIONARY.
213   //
214   // Example:
215   //   bool success = RemoveKey("foo");
216   bool RemoveKey(StringPiece key);
217 
218   // Searches a hierarchy of dictionary values for a given value. If a path
219   // of dictionaries exist, returns the item at that path. If any of the path
220   // components do not exist or if any but the last path components are not
221   // dictionaries, returns nullptr.
222   //
223   // The type of the leaf Value is not checked.
224   //
225   // Implementation note: This can't return an iterator because the iterator
226   // will actually be into another Value, so it can't be compared to iterators
227   // from this one (in particular, the DictItems().end() iterator).
228   //
229   // Example:
230   //   auto* found = FindPath({"foo", "bar"});
231   //
232   //   std::vector<StringPiece> components = ...
233   //   auto* found = FindPath(components);
234   //
235   // Note: If there is only one component in the path, use FindKey() instead.
236   Value* FindPath(std::initializer_list<StringPiece> path);
237   Value* FindPath(span<const StringPiece> path);
238   const Value* FindPath(std::initializer_list<StringPiece> path) const;
239   const Value* FindPath(span<const StringPiece> path) const;
240 
241   // Like FindPath() but will only return the value if the leaf Value type
242   // matches the given type. Will return nullptr otherwise.
243   //
244   // Note: If there is only one component in the path, use FindKeyOfType()
245   // instead.
246   Value* FindPathOfType(std::initializer_list<StringPiece> path, Type type);
247   Value* FindPathOfType(span<const StringPiece> path, Type type);
248   const Value* FindPathOfType(std::initializer_list<StringPiece> path,
249                               Type type) const;
250   const Value* FindPathOfType(span<const StringPiece> path, Type type) const;
251 
252   // Sets the given path, expanding and creating dictionary keys as necessary.
253   //
254   // If the current value is not a dictionary, the function returns nullptr. If
255   // path components do not exist, they will be created. If any but the last
256   // components matches a value that is not a dictionary, the function will fail
257   // (it will not overwrite the value) and return nullptr. The last path
258   // component will be unconditionally overwritten if it exists, and created if
259   // it doesn't.
260   //
261   // Example:
262   //   value.SetPath({"foo", "bar"}, std::move(myvalue));
263   //
264   //   std::vector<StringPiece> components = ...
265   //   value.SetPath(components, std::move(myvalue));
266   //
267   // Note: If there is only one component in the path, use SetKey() instead.
268   Value* SetPath(std::initializer_list<StringPiece> path, Value value);
269   Value* SetPath(span<const StringPiece> path, Value value);
270 
271   // Tries to remove a Value at the given path.
272   //
273   // If the current value is not a dictionary or any path components does not
274   // exist, this operation fails, leaves underlying Values untouched and returns
275   // |false|. In case intermediate dictionaries become empty as a result of this
276   // path removal, they will be removed as well.
277   //
278   // Example:
279   //   bool success = value.RemovePath({"foo", "bar"});
280   //
281   //   std::vector<StringPiece> components = ...
282   //   bool success = value.RemovePath(components);
283   //
284   // Note: If there is only one component in the path, use RemoveKey() instead.
285   bool RemovePath(std::initializer_list<StringPiece> path);
286   bool RemovePath(span<const StringPiece> path);
287 
288   using dict_iterator_proxy = detail::dict_iterator_proxy;
289   using const_dict_iterator_proxy = detail::const_dict_iterator_proxy;
290 
291   // |DictItems| returns a proxy object that exposes iterators to the underlying
292   // dictionary. These are intended for iteration over all items in the
293   // dictionary and are compatible with for-each loops and standard library
294   // algorithms.
295   // Note: This fatally asserts if type() is not Type::DICTIONARY.
296   dict_iterator_proxy DictItems();
297   const_dict_iterator_proxy DictItems() const;
298 
299   // Returns the size of the dictionary, and if the dictionary is empty.
300   // Note: This fatally asserts if type() is not Type::DICTIONARY.
301   size_t DictSize() const;
302   bool DictEmpty() const;
303 
304   // These methods allow the convenient retrieval of the contents of the Value.
305   // If the current object can be converted into the given type, the value is
306   // returned through the |out_value| parameter and true is returned;
307   // otherwise, false is returned and |out_value| is unchanged.
308   // DEPRECATED, use GetBool() instead.
309   bool GetAsBoolean(bool* out_value) const;
310   // DEPRECATED, use GetInt() instead.
311   bool GetAsInteger(int* out_value) const;
312   // DEPRECATED, use GetDouble() instead.
313   bool GetAsDouble(double* out_value) const;
314   // DEPRECATED, use GetString() instead.
315   bool GetAsString(std::string* out_value) const;
316   bool GetAsString(string16* out_value) const;
317   bool GetAsString(const Value** out_value) const;
318   bool GetAsString(StringPiece* out_value) const;
319   // ListValue::From is the equivalent for std::unique_ptr conversions.
320   // DEPRECATED, use GetList() instead.
321   bool GetAsList(ListValue** out_value);
322   bool GetAsList(const ListValue** out_value) const;
323   // DictionaryValue::From is the equivalent for std::unique_ptr conversions.
324   bool GetAsDictionary(DictionaryValue** out_value);
325   bool GetAsDictionary(const DictionaryValue** out_value) const;
326   // Note: Do not add more types. See the file-level comment above for why.
327 
328   // This creates a deep copy of the entire Value tree, and returns a pointer
329   // to the copy. The caller gets ownership of the copy, of course.
330   // Subclasses return their own type directly in their overrides;
331   // this works because C++ supports covariant return types.
332   // DEPRECATED, use Value::Clone() instead.
333   // TODO(crbug.com/646113): Delete this and migrate callsites.
334   Value* DeepCopy() const;
335   // DEPRECATED, use Value::Clone() instead.
336   // TODO(crbug.com/646113): Delete this and migrate callsites.
337   std::unique_ptr<Value> CreateDeepCopy() const;
338 
339   // Comparison operators so that Values can easily be used with standard
340   // library algorithms and associative containers.
341   BASE_EXPORT friend bool operator==(const Value& lhs, const Value& rhs);
342   BASE_EXPORT friend bool operator!=(const Value& lhs, const Value& rhs);
343   BASE_EXPORT friend bool operator<(const Value& lhs, const Value& rhs);
344   BASE_EXPORT friend bool operator>(const Value& lhs, const Value& rhs);
345   BASE_EXPORT friend bool operator<=(const Value& lhs, const Value& rhs);
346   BASE_EXPORT friend bool operator>=(const Value& lhs, const Value& rhs);
347 
348   // Compares if two Value objects have equal contents.
349   // DEPRECATED, use operator==(const Value& lhs, const Value& rhs) instead.
350   // TODO(crbug.com/646113): Delete this and migrate callsites.
351   bool Equals(const Value* other) const;
352 
353   // Estimates dynamic memory usage.
354   // See base/trace_event/memory_usage_estimator.h for more info.
355   // size_t EstimateMemoryUsage() const;
356 
357  protected:
358   // TODO(crbug.com/646113): Make these private once DictionaryValue and
359   // ListValue are properly inlined.
360   Type type_;
361 
362   union {
363     bool bool_value_;
364     int int_value_;
365     double double_value_;
366     std::string string_value_;
367     BlobStorage binary_value_;
368     DictStorage dict_;
369     ListStorage list_;
370   };
371 
372  private:
373   void InternalMoveConstructFrom(Value&& that);
374   void InternalCleanup();
375 
376   DISALLOW_COPY_AND_ASSIGN(Value);
377 };
378 
379 // DictionaryValue provides a key-value dictionary with (optional) "path"
380 // parsing for recursive access; see the comment at the top of the file. Keys
381 // are |std::string|s and should be UTF-8 encoded.
382 class BASE_EXPORT DictionaryValue : public Value {
383  public:
384   using const_iterator = DictStorage::const_iterator;
385   using iterator = DictStorage::iterator;
386 
387   // Returns |value| if it is a dictionary, nullptr otherwise.
388   static std::unique_ptr<DictionaryValue> From(std::unique_ptr<Value> value);
389 
390   DictionaryValue();
391   explicit DictionaryValue(const DictStorage& in_dict);
392   explicit DictionaryValue(DictStorage&& in_dict) noexcept;
393 
394   // Returns true if the current dictionary has a value for the given key.
395   // DEPRECATED, use Value::FindKey(key) instead.
396   bool HasKey(StringPiece key) const;
397 
398   // Returns the number of Values in this dictionary.
size()399   size_t size() const { return dict_.size(); }
400 
401   // Returns whether the dictionary is empty.
empty()402   bool empty() const { return dict_.empty(); }
403 
404   // Clears any current contents of this dictionary.
405   void Clear();
406 
407   // Sets the Value associated with the given path starting from this object.
408   // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
409   // into the next DictionaryValue down.  Obviously, "." can't be used
410   // within a key, but there are no other restrictions on keys.
411   // If the key at any step of the way doesn't exist, or exists but isn't
412   // a DictionaryValue, a new DictionaryValue will be created and attached
413   // to the path in that location. |in_value| must be non-null.
414   // Returns a pointer to the inserted value.
415   // DEPRECATED, use Value::SetPath(path, value) instead.
416   Value* Set(StringPiece path, std::unique_ptr<Value> in_value);
417 
418   // Convenience forms of Set().  These methods will replace any existing
419   // value at that path, even if it has a different type.
420   // DEPRECATED, use Value::SetPath(path, Value(bool)) instead.
421   Value* SetBoolean(StringPiece path, bool in_value);
422   // DEPRECATED, use Value::SetPath(path, Value(int)) instead.
423   Value* SetInteger(StringPiece path, int in_value);
424   // DEPRECATED, use Value::SetPath(path, Value(double)) instead.
425   Value* SetDouble(StringPiece path, double in_value);
426   // DEPRECATED, use Value::SetPath(path, Value(StringPiece)) instead.
427   Value* SetString(StringPiece path, StringPiece in_value);
428   // DEPRECATED, use Value::SetPath(path, Value(const string& 16)) instead.
429   Value* SetString(StringPiece path, const string16& in_value);
430   // DEPRECATED, use Value::SetPath(path, Value(Type::DICTIONARY)) instead.
431   DictionaryValue* SetDictionary(StringPiece path,
432                                  std::unique_ptr<DictionaryValue> in_value);
433   // DEPRECATED, use Value::SetPath(path, Value(Type::LIST)) instead.
434   ListValue* SetList(StringPiece path, std::unique_ptr<ListValue> in_value);
435 
436   // Like Set(), but without special treatment of '.'.  This allows e.g. URLs to
437   // be used as paths.
438   // DEPRECATED, use Value::SetKey(key, value) instead.
439   Value* SetWithoutPathExpansion(StringPiece key,
440                                  std::unique_ptr<Value> in_value);
441 
442   // Gets the Value associated with the given path starting from this object.
443   // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
444   // into the next DictionaryValue down.  If the path can be resolved
445   // successfully, the value for the last key in the path will be returned
446   // through the |out_value| parameter, and the function will return true.
447   // Otherwise, it will return false and |out_value| will be untouched.
448   // Note that the dictionary always owns the value that's returned.
449   // |out_value| is optional and will only be set if non-NULL.
450   // DEPRECATED, use Value::FindPath(path) instead.
451   bool Get(StringPiece path, const Value** out_value) const;
452   // DEPRECATED, use Value::FindPath(path) instead.
453   bool Get(StringPiece path, Value** out_value);
454 
455   // These are convenience forms of Get().  The value will be retrieved
456   // and the return value will be true if the path is valid and the value at
457   // the end of the path can be returned in the form specified.
458   // |out_value| is optional and will only be set if non-NULL.
459   // DEPRECATED, use Value::FindPath(path) and Value::GetBool() instead.
460   bool GetBoolean(StringPiece path, bool* out_value) const;
461   // DEPRECATED, use Value::FindPath(path) and Value::GetInt() instead.
462   bool GetInteger(StringPiece path, int* out_value) const;
463   // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as
464   // doubles.
465   // DEPRECATED, use Value::FindPath(path) and Value::GetDouble() instead.
466   bool GetDouble(StringPiece path, double* out_value) const;
467   // DEPRECATED, use Value::FindPath(path) and Value::GetString() instead.
468   bool GetString(StringPiece path, std::string* out_value) const;
469   // DEPRECATED, use Value::FindPath(path) and Value::GetString() instead.
470   bool GetString(StringPiece path, string16* out_value) const;
471   // DEPRECATED, use Value::FindPath(path) and Value::GetString() instead.
472   bool GetStringASCII(StringPiece path, std::string* out_value) const;
473   // DEPRECATED, use Value::FindPath(path) and Value::GetBlob() instead.
474   bool GetBinary(StringPiece path, const Value** out_value) const;
475   // DEPRECATED, use Value::FindPath(path) and Value::GetBlob() instead.
476   bool GetBinary(StringPiece path, Value** out_value);
477   // DEPRECATED, use Value::FindPath(path) and Value's Dictionary API instead.
478   bool GetDictionary(StringPiece path,
479                      const DictionaryValue** out_value) const;
480   // DEPRECATED, use Value::FindPath(path) and Value's Dictionary API instead.
481   bool GetDictionary(StringPiece path, DictionaryValue** out_value);
482   // DEPRECATED, use Value::FindPath(path) and Value::GetList() instead.
483   bool GetList(StringPiece path, const ListValue** out_value) const;
484   // DEPRECATED, use Value::FindPath(path) and Value::GetList() instead.
485   bool GetList(StringPiece path, ListValue** out_value);
486 
487   // Like Get(), but without special treatment of '.'.  This allows e.g. URLs to
488   // be used as paths.
489   // DEPRECATED, use Value::FindKey(key) instead.
490   bool GetWithoutPathExpansion(StringPiece key, const Value** out_value) const;
491   // DEPRECATED, use Value::FindKey(key) instead.
492   bool GetWithoutPathExpansion(StringPiece key, Value** out_value);
493   // DEPRECATED, use Value::FindKey(key) and Value::GetBool() instead.
494   bool GetBooleanWithoutPathExpansion(StringPiece key, bool* out_value) const;
495   // DEPRECATED, use Value::FindKey(key) and Value::GetInt() instead.
496   bool GetIntegerWithoutPathExpansion(StringPiece key, int* out_value) const;
497   // DEPRECATED, use Value::FindKey(key) and Value::GetDouble() instead.
498   bool GetDoubleWithoutPathExpansion(StringPiece key, double* out_value) const;
499   // DEPRECATED, use Value::FindKey(key) and Value::GetString() instead.
500   bool GetStringWithoutPathExpansion(StringPiece key,
501                                      std::string* out_value) const;
502   // DEPRECATED, use Value::FindKey(key) and Value::GetString() instead.
503   bool GetStringWithoutPathExpansion(StringPiece key,
504                                      string16* out_value) const;
505   // DEPRECATED, use Value::FindKey(key) and Value's Dictionary API instead.
506   bool GetDictionaryWithoutPathExpansion(
507       StringPiece key,
508       const DictionaryValue** out_value) const;
509   // DEPRECATED, use Value::FindKey(key) and Value's Dictionary API instead.
510   bool GetDictionaryWithoutPathExpansion(StringPiece key,
511                                          DictionaryValue** out_value);
512   // DEPRECATED, use Value::FindKey(key) and Value::GetList() instead.
513   bool GetListWithoutPathExpansion(StringPiece key,
514                                    const ListValue** out_value) const;
515   // DEPRECATED, use Value::FindKey(key) and Value::GetList() instead.
516   bool GetListWithoutPathExpansion(StringPiece key, ListValue** out_value);
517 
518   // Removes the Value with the specified path from this dictionary (or one
519   // of its child dictionaries, if the path is more than just a local key).
520   // If |out_value| is non-NULL, the removed Value will be passed out via
521   // |out_value|.  If |out_value| is NULL, the removed value will be deleted.
522   // This method returns true if |path| is a valid path; otherwise it will
523   // return false and the DictionaryValue object will be unchanged.
524   // DEPRECATED, use Value::RemovePath(path) instead.
525   bool Remove(StringPiece path, std::unique_ptr<Value>* out_value);
526 
527   // Like Remove(), but without special treatment of '.'.  This allows e.g. URLs
528   // to be used as paths.
529   // DEPRECATED, use Value::RemoveKey(key) instead.
530   bool RemoveWithoutPathExpansion(StringPiece key,
531                                   std::unique_ptr<Value>* out_value);
532 
533   // Removes a path, clearing out all dictionaries on |path| that remain empty
534   // after removing the value at |path|.
535   // DEPRECATED, use Value::RemovePath(path) instead.
536   bool RemovePath(StringPiece path, std::unique_ptr<Value>* out_value);
537 
538   using Value::RemovePath;  // DictionaryValue::RemovePath shadows otherwise.
539 
540   // Makes a copy of |this| but doesn't include empty dictionaries and lists in
541   // the copy.  This never returns NULL, even if |this| itself is empty.
542   std::unique_ptr<DictionaryValue> DeepCopyWithoutEmptyChildren() const;
543 
544   // Merge |dictionary| into this dictionary. This is done recursively, i.e. any
545   // sub-dictionaries will be merged as well. In case of key collisions, the
546   // passed in dictionary takes precedence and data already present will be
547   // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
548   // be freed any time after this call.
549   void MergeDictionary(const DictionaryValue* dictionary);
550 
551   // Swaps contents with the |other| dictionary.
552   void Swap(DictionaryValue* other);
553 
554   // This class provides an iterator over both keys and values in the
555   // dictionary.  It can't be used to modify the dictionary.
556   // DEPRECATED, use Value::DictItems() instead.
557   class BASE_EXPORT Iterator {
558    public:
559     explicit Iterator(const DictionaryValue& target);
560     Iterator(const Iterator& other);
561     ~Iterator();
562 
IsAtEnd()563     bool IsAtEnd() const { return it_ == target_.dict_.end(); }
Advance()564     void Advance() { ++it_; }
565 
key()566     const std::string& key() const { return it_->first; }
value()567     const Value& value() const { return *it_->second; }
568 
569    private:
570     const DictionaryValue& target_;
571     DictStorage::const_iterator it_;
572   };
573 
574   // Iteration.
575   // DEPRECATED, use Value::DictItems() instead.
begin()576   iterator begin() { return dict_.begin(); }
end()577   iterator end() { return dict_.end(); }
578 
579   // DEPRECATED, use Value::DictItems() instead.
begin()580   const_iterator begin() const { return dict_.begin(); }
end()581   const_iterator end() const { return dict_.end(); }
582 
583   // DEPRECATED, use Value::Clone() instead.
584   // TODO(crbug.com/646113): Delete this and migrate callsites.
585   DictionaryValue* DeepCopy() const;
586   // DEPRECATED, use Value::Clone() instead.
587   // TODO(crbug.com/646113): Delete this and migrate callsites.
588   std::unique_ptr<DictionaryValue> CreateDeepCopy() const;
589 };
590 
591 // This type of Value represents a list of other Value values.
592 class BASE_EXPORT ListValue : public Value {
593  public:
594   using const_iterator = ListStorage::const_iterator;
595   using iterator = ListStorage::iterator;
596 
597   // Returns |value| if it is a list, nullptr otherwise.
598   static std::unique_ptr<ListValue> From(std::unique_ptr<Value> value);
599 
600   ListValue();
601   explicit ListValue(const ListStorage& in_list);
602   explicit ListValue(ListStorage&& in_list) noexcept;
603 
604   // Clears the contents of this ListValue
605   // DEPRECATED, use GetList()::clear() instead.
606   void Clear();
607 
608   // Returns the number of Values in this list.
609   // DEPRECATED, use GetList()::size() instead.
GetSize()610   size_t GetSize() const { return list_.size(); }
611 
612   // Returns whether the list is empty.
613   // DEPRECATED, use GetList()::empty() instead.
empty()614   bool empty() const { return list_.empty(); }
615 
616   // Reserves storage for at least |n| values.
617   // DEPRECATED, use GetList()::reserve() instead.
618   void Reserve(size_t n);
619 
620   // Sets the list item at the given index to be the Value specified by
621   // the value given.  If the index beyond the current end of the list, null
622   // Values will be used to pad out the list.
623   // Returns true if successful, or false if the index was negative or
624   // the value is a null pointer.
625   // DEPRECATED, use GetList()::operator[] instead.
626   bool Set(size_t index, std::unique_ptr<Value> in_value);
627 
628   // Gets the Value at the given index.  Modifies |out_value| (and returns true)
629   // only if the index falls within the current list range.
630   // Note that the list always owns the Value passed out via |out_value|.
631   // |out_value| is optional and will only be set if non-NULL.
632   // DEPRECATED, use GetList()::operator[] instead.
633   bool Get(size_t index, const Value** out_value) const;
634   bool Get(size_t index, Value** out_value);
635 
636   // Convenience forms of Get().  Modifies |out_value| (and returns true)
637   // only if the index is valid and the Value at that index can be returned
638   // in the specified form.
639   // |out_value| is optional and will only be set if non-NULL.
640   // DEPRECATED, use GetList()::operator[]::GetBool() instead.
641   bool GetBoolean(size_t index, bool* out_value) const;
642   // DEPRECATED, use GetList()::operator[]::GetInt() instead.
643   bool GetInteger(size_t index, int* out_value) const;
644   // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as
645   // doubles.
646   // DEPRECATED, use GetList()::operator[]::GetDouble() instead.
647   bool GetDouble(size_t index, double* out_value) const;
648   // DEPRECATED, use GetList()::operator[]::GetString() instead.
649   bool GetString(size_t index, std::string* out_value) const;
650   bool GetString(size_t index, string16* out_value) const;
651 
652   bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
653   bool GetDictionary(size_t index, DictionaryValue** out_value);
654 
655   using Value::GetList;
656   // DEPRECATED, use GetList()::operator[]::GetList() instead.
657   bool GetList(size_t index, const ListValue** out_value) const;
658   bool GetList(size_t index, ListValue** out_value);
659 
660   // Removes the Value with the specified index from this list.
661   // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
662   // passed out via |out_value|.  If |out_value| is NULL, the removed value will
663   // be deleted.  This method returns true if |index| is valid; otherwise
664   // it will return false and the ListValue object will be unchanged.
665   // DEPRECATED, use GetList()::erase() instead.
666   bool Remove(size_t index, std::unique_ptr<Value>* out_value);
667 
668   // Removes the first instance of |value| found in the list, if any, and
669   // deletes it. |index| is the location where |value| was found. Returns false
670   // if not found.
671   // DEPRECATED, use GetList()::erase() instead.
672   bool Remove(const Value& value, size_t* index);
673 
674   // Removes the element at |iter|. If |out_value| is NULL, the value will be
675   // deleted, otherwise ownership of the value is passed back to the caller.
676   // Returns an iterator pointing to the location of the element that
677   // followed the erased element.
678   // DEPRECATED, use GetList()::erase() instead.
679   iterator Erase(iterator iter, std::unique_ptr<Value>* out_value);
680 
681   // Appends a Value to the end of the list.
682   // DEPRECATED, use GetList()::push_back() instead.
683   void Append(std::unique_ptr<Value> in_value);
684 
685   // Convenience forms of Append.
686   // DEPRECATED, use GetList()::emplace_back() instead.
687   void AppendBoolean(bool in_value);
688   void AppendInteger(int in_value);
689   void AppendDouble(double in_value);
690   void AppendString(StringPiece in_value);
691   void AppendString(const string16& in_value);
692   // DEPRECATED, use GetList()::emplace_back() in a loop instead.
693   void AppendStrings(const std::vector<std::string>& in_values);
694   void AppendStrings(const std::vector<string16>& in_values);
695 
696   // Appends a Value if it's not already present. Returns true if successful,
697   // or false if the value was already
698   // DEPRECATED, use std::find() with GetList()::push_back() instead.
699   bool AppendIfNotPresent(std::unique_ptr<Value> in_value);
700 
701   // Insert a Value at index.
702   // Returns true if successful, or false if the index was out of range.
703   // DEPRECATED, use GetList()::insert() instead.
704   bool Insert(size_t index, std::unique_ptr<Value> in_value);
705 
706   // Searches for the first instance of |value| in the list using the Equals
707   // method of the Value type.
708   // Returns a const_iterator to the found item or to end() if none exists.
709   // DEPRECATED, use std::find() instead.
710   const_iterator Find(const Value& value) const;
711 
712   // Swaps contents with the |other| list.
713   // DEPRECATED, use GetList()::swap() instead.
714   void Swap(ListValue* other);
715 
716   // Iteration.
717   // DEPRECATED, use GetList()::begin() instead.
begin()718   iterator begin() { return list_.begin(); }
719   // DEPRECATED, use GetList()::end() instead.
end()720   iterator end() { return list_.end(); }
721 
722   // DEPRECATED, use GetList()::begin() instead.
begin()723   const_iterator begin() const { return list_.begin(); }
724   // DEPRECATED, use GetList()::end() instead.
end()725   const_iterator end() const { return list_.end(); }
726 
727   // DEPRECATED, use Value::Clone() instead.
728   // TODO(crbug.com/646113): Delete this and migrate callsites.
729   ListValue* DeepCopy() const;
730   // DEPRECATED, use Value::Clone() instead.
731   // TODO(crbug.com/646113): Delete this and migrate callsites.
732   std::unique_ptr<ListValue> CreateDeepCopy() const;
733 };
734 
735 // This interface is implemented by classes that know how to serialize
736 // Value objects.
737 class BASE_EXPORT ValueSerializer {
738  public:
739   virtual ~ValueSerializer();
740 
741   virtual bool Serialize(const Value& root) = 0;
742 };
743 
744 // This interface is implemented by classes that know how to deserialize Value
745 // objects.
746 class BASE_EXPORT ValueDeserializer {
747  public:
748   virtual ~ValueDeserializer();
749 
750   // This method deserializes the subclass-specific format into a Value object.
751   // If the return value is non-NULL, the caller takes ownership of returned
752   // Value. If the return value is NULL, and if error_code is non-NULL,
753   // error_code will be set with the underlying error.
754   // If |error_message| is non-null, it will be filled in with a formatted
755   // error message including the location of the error if appropriate.
756   virtual std::unique_ptr<Value> Deserialize(int* error_code,
757                                              std::string* error_str) = 0;
758 };
759 
760 // Stream operator so Values can be used in assertion statements.  In order that
761 // gtest uses this operator to print readable output on test failures, we must
762 // override each specific type. Otherwise, the default template implementation
763 // is preferred over an upcast.
764 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
765 
766 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
767                                             const DictionaryValue& value) {
768   return out << static_cast<const Value&>(value);
769 }
770 
771 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
772                                             const ListValue& value) {
773   return out << static_cast<const Value&>(value);
774 }
775 
776 // Stream operator so that enum class Types can be used in log statements.
777 BASE_EXPORT std::ostream& operator<<(std::ostream& out,
778                                      const Value::Type& type);
779 
780 }  // namespace base
781 
782 #endif  // BASE_VALUES_H_
783