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/checked_iterators.h"
36 #include "base/containers/checked_range.h"
37 #include "base/containers/flat_map.h"
38 #include "base/containers/span.h"
39 #include "base/strings/string16.h"
40 #include "base/strings/string_piece.h"
41 #include "base/value_iterators.h"
42 #include "third_party/abseil-cpp/absl/types/variant.h"
43 
44 namespace base {
45 
46 class DictionaryValue;
47 class ListValue;
48 class Value;
49 
50 // The Value class is the base class for Values. A Value can be instantiated
51 // via passing the appropriate type or backing storage to the constructor.
52 //
53 // See the file-level comment above for more information.
54 //
55 // base::Value is currently in the process of being refactored. Design doc:
56 // https://docs.google.com/document/d/1uDLu5uTRlCWePxQUEHc8yNQdEoE1BDISYdpggWEABnw
57 //
58 // Previously (which is how most code that currently exists is written), Value
59 // used derived types to implement the individual data types, and base::Value
60 // was just a base class to refer to them. This required everything be heap
61 // allocated.
62 //
63 // OLD WAY:
64 //
65 //   std::unique_ptr<base::Value> GetFoo() {
66 //     std::unique_ptr<DictionaryValue> dict;
67 //     dict->SetString("mykey", foo);
68 //     return dict;
69 //   }
70 //
71 // The new design makes base::Value a variant type that holds everything in
72 // a union. It is now recommended to pass by value with std::move rather than
73 // use heap allocated values. The DictionaryValue and ListValue subclasses
74 // exist only as a compatibility shim that we're in the process of removing.
75 //
76 // NEW WAY:
77 //
78 //   base::Value GetFoo() {
79 //     base::Value dict(base::Value::Type::DICTIONARY);
80 //     dict.SetKey("mykey", base::Value(foo));
81 //     return dict;
82 //   }
83 //
84 // The new design tries to avoid losing type information. Thus when migrating
85 // off deprecated types, existing usages of base::ListValue should be replaced
86 // by std::vector<base::Value>, and existing usages of base::DictionaryValue
87 // should be replaced with base::flat_map<std::string, base::Value>.
88 //
89 // OLD WAY:
90 //
91 //   void AlwaysTakesList(std::unique_ptr<base::ListValue> list);
92 //   void AlwaysTakesDict(std::unique_ptr<base::DictionaryValue> dict);
93 //
94 // NEW WAY:
95 //
96 //   void AlwaysTakesList(std::vector<base::Value> list);
97 //   void AlwaysTakesDict(base::flat_map<std::string, base::Value> dict);
98 //
99 // Migrating code will require conversions on API boundaries. This can be done
100 // cheaply by making use of overloaded base::Value constructors and the
101 // Value::TakeList() and Value::TakeDict() APIs.
102 class BASE_EXPORT Value {
103  public:
104   using BlobStorage = std::vector<uint8_t>;
105   using ListStorage = std::vector<Value>;
106   using DictStorage = flat_map<std::string, Value>;
107 
108   // Like `DictStorage`, but with std::unique_ptr in the mapped type. This is
109   // due to legacy reasons, and should be removed once no caller relies on
110   // stability of pointers anymore.
111   using LegacyDictStorage = flat_map<std::string, std::unique_ptr<Value>>;
112 
113   using ListView = CheckedContiguousRange<ListStorage>;
114   using ConstListView = CheckedContiguousConstRange<ListStorage>;
115 
116   enum class Type : unsigned char {
117     NONE = 0,
118     BOOLEAN,
119     INTEGER,
120     DOUBLE,
121     STRING,
122     BINARY,
123     DICTIONARY,
124     LIST,
125     // TODO(crbug.com/859477): Remove once root cause is found.
126     DEAD
127     // Note: Do not add more types. See the file-level comment above for why.
128   };
129 
130   // Adaptors for converting from the old way to the new way and vice versa.
131   static Value FromUniquePtrValue(std::unique_ptr<Value> val);
132   static std::unique_ptr<Value> ToUniquePtrValue(Value val);
133   static const DictionaryValue& AsDictionaryValue(const Value& val);
134   static const ListValue& AsListValue(const Value& val);
135 
136   Value() noexcept;
137   Value(Value&& that) noexcept;
138 
139   // Value's copy constructor and copy assignment operator are deleted. Use this
140   // to obtain a deep copy explicitly.
141   Value Clone() const;
142 
143   explicit Value(Type type);
144   explicit Value(bool in_bool);
145   explicit Value(int in_int);
146   explicit Value(double in_double);
147 
148   // Value(const char*) and Value(const char16*) are required despite
149   // Value(StringPiece) and Value(StringPiece16) because otherwise the
150   // compiler will choose the Value(bool) constructor for these arguments.
151   // Value(std::string&&) allow for efficient move construction.
152   explicit Value(const char* in_string);
153   explicit Value(StringPiece in_string);
154   explicit Value(std::string&& in_string) noexcept;
155   explicit Value(const char16* in_string16);
156   explicit Value(StringPiece16 in_string16);
157 
158   explicit Value(const std::vector<char>& in_blob);
159   explicit Value(base::span<const uint8_t> in_blob);
160   explicit Value(BlobStorage&& in_blob) noexcept;
161 
162   explicit Value(const DictStorage& in_dict);
163   explicit Value(DictStorage&& in_dict) noexcept;
164 
165   explicit Value(span<const Value> in_list);
166   explicit Value(ListStorage&& in_list) noexcept;
167 
168   Value& operator=(Value&& that) noexcept;
169   Value(const Value&) = delete;
170   Value& operator=(const Value&) = delete;
171 
172   ~Value();
173 
174   // Returns the name for a given |type|.
175   static const char* GetTypeName(Type type);
176 
177   // Returns the type of the value stored by the current Value object.
type()178   Type type() const { return static_cast<Type>(data_.index()); }
179 
180   // Returns true if the current object represents a given type.
is_none()181   bool is_none() const { return type() == Type::NONE; }
is_bool()182   bool is_bool() const { return type() == Type::BOOLEAN; }
is_int()183   bool is_int() const { return type() == Type::INTEGER; }
is_double()184   bool is_double() const { return type() == Type::DOUBLE; }
is_string()185   bool is_string() const { return type() == Type::STRING; }
is_blob()186   bool is_blob() const { return type() == Type::BINARY; }
is_dict()187   bool is_dict() const { return type() == Type::DICTIONARY; }
is_list()188   bool is_list() const { return type() == Type::LIST; }
189 
190   // These will all CHECK that the type matches.
191   bool GetBool() const;
192   int GetInt() const;
193   double GetDouble() const;  // Implicitly converts from int if necessary.
194   const std::string& GetString() const;
195   std::string& GetString();
196   const BlobStorage& GetBlob() const;
197 
198   // Returns the Values in a list as a view. The mutable overload allows for
199   // modification of the underlying values, but does not allow changing the
200   // structure of the list. If this is desired, use TakeList(), perform the
201   // operations, and return the list back to the Value via move assignment.
202   ListView GetList();
203   ConstListView GetList() const;
204 
205   // Transfers ownership of the underlying list to the caller. Subsequent
206   // calls to GetList() will return an empty list.
207   // Note: This requires that type() is Type::LIST.
208   ListStorage TakeList();
209 
210   // Appends |value| to the end of the list.
211   // Note: These CHECK that type() is Type::LIST.
212   void Append(bool value);
213   void Append(int value);
214   void Append(double value);
215   void Append(const char* value);
216   void Append(StringPiece value);
217   void Append(std::string&& value);
218   void Append(const char16* value);
219   void Append(StringPiece16 value);
220   void Append(Value&& value);
221 
222   // Inserts |value| before |pos|.
223   // Note: This CHECK that type() is Type::LIST.
224   CheckedContiguousIterator<Value> Insert(
225       CheckedContiguousConstIterator<Value> pos,
226       Value&& value);
227 
228   // Erases the Value pointed to by |iter|. Returns false if |iter| is out of
229   // bounds.
230   // Note: This requires that type() is Type::LIST.
231   bool EraseListIter(CheckedContiguousConstIterator<Value> iter);
232 
233   // Erases all Values that compare equal to |val|. Returns the number of
234   // deleted Values.
235   // Note: This requires that type() is Type::LIST.
236   size_t EraseListValue(const Value& val);
237 
238   // Erases all Values for which |pred| returns true. Returns the number of
239   // deleted Values.
240   // Note: This requires that type() is Type::LIST.
241   template <typename Predicate>
EraseListValueIf(Predicate pred)242   size_t EraseListValueIf(Predicate pred) {
243     return base::EraseIf(list(), pred);
244   }
245 
246   // Erases all Values from the list.
247   // Note: This requires that type() is Type::LIST.
248   void ClearList();
249 
250   // |FindKey| looks up |key| in the underlying dictionary. If found, it returns
251   // a pointer to the element. Otherwise it returns nullptr.
252   // returned. Callers are expected to perform a check against null before using
253   // the pointer.
254   // Note: This requires that type() is Type::DICTIONARY.
255   //
256   // Example:
257   //   auto* found = FindKey("foo");
258   Value* FindKey(StringPiece key);
259   const Value* FindKey(StringPiece key) const;
260 
261   // |FindKeyOfType| is similar to |FindKey|, but it also requires the found
262   // value to have type |type|. If no type is found, or the found value is of a
263   // different type nullptr is returned.
264   // Callers are expected to perform a check against null before using the
265   // pointer.
266   // Note: This requires that type() is Type::DICTIONARY.
267   //
268   // Example:
269   //   auto* found = FindKey("foo", Type::DOUBLE);
270   Value* FindKeyOfType(StringPiece key, Type type);
271   const Value* FindKeyOfType(StringPiece key, Type type) const;
272 
273   // These are convenience forms of |FindKey|. They return |base::nullopt| if
274   // the value is not found or doesn't have the type specified in the
275   // function's name.
276   base::Optional<bool> FindBoolKey(StringPiece key) const;
277   base::Optional<int> FindIntKey(StringPiece key) const;
278   // Note FindDoubleKey() will auto-convert INTEGER keys to their double
279   // value, for consistency with GetDouble().
280   base::Optional<double> FindDoubleKey(StringPiece key) const;
281 
282   // |FindStringKey| returns |nullptr| if value is not found or not a string.
283   const std::string* FindStringKey(StringPiece key) const;
284   std::string* FindStringKey(StringPiece key);
285 
286   // Returns nullptr is value is not found or not a binary.
287   const BlobStorage* FindBlobKey(StringPiece key) const;
288 
289   // Returns nullptr if value is not found or not a dictionary.
290   const Value* FindDictKey(StringPiece key) const;
291   Value* FindDictKey(StringPiece key);
292 
293   // Returns nullptr if value is not found or not a list.
294   const Value* FindListKey(StringPiece key) const;
295   Value* FindListKey(StringPiece key);
296 
297   // |SetKey| looks up |key| in the underlying dictionary and sets the mapped
298   // value to |value|. If |key| could not be found, a new element is inserted.
299   // A pointer to the modified item is returned.
300   // Note: This requires that type() is Type::DICTIONARY.
301   // Note: Prefer Set<Type>Key() for simple values.
302   //
303   // Example:
304   //   SetKey("foo", std::move(myvalue));
305   Value* SetKey(StringPiece key, Value&& value);
306   // This overload results in a performance improvement for std::string&&.
307   Value* SetKey(std::string&& key, Value&& value);
308   // This overload is necessary to avoid ambiguity for const char* arguments.
309   Value* SetKey(const char* key, Value&& value);
310 
311   // |Set<Type>Key| looks up |key| in the underlying dictionary and associates
312   // a corresponding Value() constructed from the second parameter. Compared
313   // to SetKey(), this avoids un-necessary temporary Value() creation, as well
314   // ambiguities in the value type.
315   Value* SetBoolKey(StringPiece key, bool val);
316   Value* SetIntKey(StringPiece key, int val);
317   Value* SetDoubleKey(StringPiece key, double val);
318   Value* SetStringKey(StringPiece key, StringPiece val);
319   Value* SetStringKey(StringPiece key, StringPiece16 val);
320   // NOTE: The following two overloads are provided as performance / code
321   // generation optimizations.
322   Value* SetStringKey(StringPiece key, const char* val);
323   Value* SetStringKey(StringPiece key, std::string&& val);
324 
325   // This attempts to remove the value associated with |key|. In case of
326   // failure, e.g. the key does not exist, false is returned and the underlying
327   // dictionary is not changed. In case of success, |key| is deleted from the
328   // dictionary and the method returns true.
329   // Note: This requires that type() is Type::DICTIONARY.
330   //
331   // Example:
332   //   bool success = dict.RemoveKey("foo");
333   bool RemoveKey(StringPiece key);
334 
335   // This attempts to extract the value associated with |key|. In case of
336   // failure, e.g. the key does not exist, nullopt is returned and the
337   // underlying dictionary is not changed. In case of success, |key| is deleted
338   // from the dictionary and the method returns the extracted Value.
339   // Note: This requires that type() is Type::DICTIONARY.
340   //
341   // Example:
342   //   Optional<Value> maybe_value = dict.ExtractKey("foo");
343   Optional<Value> ExtractKey(StringPiece key);
344 
345   // Searches a hierarchy of dictionary values for a given value. If a path
346   // of dictionaries exist, returns the item at that path. If any of the path
347   // components do not exist or if any but the last path components are not
348   // dictionaries, returns nullptr.
349   //
350   // The type of the leaf Value is not checked.
351   //
352   // Implementation note: This can't return an iterator because the iterator
353   // will actually be into another Value, so it can't be compared to iterators
354   // from this one (in particular, the DictItems().end() iterator).
355   //
356   // This version takes a StringPiece for the path, using dots as separators.
357   // Example:
358   //    auto* found = FindPath("foo.bar");
359   Value* FindPath(StringPiece path);
360   const Value* FindPath(StringPiece path) const;
361 
362   // There are also deprecated versions that take the path parameter
363   // as either a std::initializer_list<StringPiece> or a
364   // span<const StringPiece>. The latter is useful to use a
365   // std::vector<std::string> as a parameter but creates huge dynamic
366   // allocations and should be avoided!
367   // Note: If there is only one component in the path, use FindKey() instead.
368   //
369   // Example:
370   //   std::vector<StringPiece> components = ...
371   //   auto* found = FindPath(components);
372   Value* FindPath(std::initializer_list<StringPiece> path);
373   Value* FindPath(span<const StringPiece> path);
374   const Value* FindPath(std::initializer_list<StringPiece> path) const;
375   const Value* FindPath(span<const StringPiece> path) const;
376 
377   // Like FindPath() but will only return the value if the leaf Value type
378   // matches the given type. Will return nullptr otherwise.
379   // Note: Prefer Find<Type>Path() for simple values.
380   //
381   // Note: If there is only one component in the path, use FindKeyOfType()
382   // instead for slightly better performance.
383   Value* FindPathOfType(StringPiece path, Type type);
384   const Value* FindPathOfType(StringPiece path, Type type) const;
385 
386   // Convenience accessors used when the expected type of a value is known.
387   // Similar to Find<Type>Key() but accepts paths instead of keys.
388   base::Optional<bool> FindBoolPath(StringPiece path) const;
389   base::Optional<int> FindIntPath(StringPiece path) const;
390   base::Optional<double> FindDoublePath(StringPiece path) const;
391   const std::string* FindStringPath(StringPiece path) const;
392   std::string* FindStringPath(StringPiece path);
393   const BlobStorage* FindBlobPath(StringPiece path) const;
394   Value* FindDictPath(StringPiece path);
395   const Value* FindDictPath(StringPiece path) const;
396   Value* FindListPath(StringPiece path);
397   const Value* FindListPath(StringPiece path) const;
398 
399   // The following forms are deprecated too, use the ones that take the path
400   // as a single StringPiece instead.
401   Value* FindPathOfType(std::initializer_list<StringPiece> path, Type type);
402   Value* FindPathOfType(span<const StringPiece> path, Type type);
403   const Value* FindPathOfType(std::initializer_list<StringPiece> path,
404                               Type type) const;
405   const Value* FindPathOfType(span<const StringPiece> path, Type type) const;
406 
407   // Sets the given path, expanding and creating dictionary keys as necessary.
408   //
409   // If the current value is not a dictionary, the function returns nullptr. If
410   // path components do not exist, they will be created. If any but the last
411   // components matches a value that is not a dictionary, the function will fail
412   // (it will not overwrite the value) and return nullptr. The last path
413   // component will be unconditionally overwritten if it exists, and created if
414   // it doesn't.
415   //
416   // Example:
417   //   value.SetPath("foo.bar", std::move(myvalue));
418   //
419   // Note: If there is only one component in the path, use SetKey() instead.
420   // Note: Using Set<Type>Path() might be more convenient and efficient.
421   Value* SetPath(StringPiece path, Value&& value);
422 
423   // These setters are more convenient and efficient than the corresponding
424   // SetPath(...) call.
425   Value* SetBoolPath(StringPiece path, bool value);
426   Value* SetIntPath(StringPiece path, int value);
427   Value* SetDoublePath(StringPiece path, double value);
428   Value* SetStringPath(StringPiece path, StringPiece value);
429   Value* SetStringPath(StringPiece path, const char* value);
430   Value* SetStringPath(StringPiece path, std::string&& value);
431   Value* SetStringPath(StringPiece path, StringPiece16 value);
432 
433   // Deprecated: use the ones that take a StringPiece path parameter instead.
434   Value* SetPath(std::initializer_list<StringPiece> path, Value&& value);
435   Value* SetPath(span<const StringPiece> path, Value&& value);
436 
437   // Tries to remove a Value at the given path.
438   //
439   // If the current value is not a dictionary or any path component does not
440   // exist, this operation fails, leaves underlying Values untouched and returns
441   // |false|. In case intermediate dictionaries become empty as a result of this
442   // path removal, they will be removed as well.
443   // Note: If there is only one component in the path, use ExtractKey() instead.
444   //
445   // Example:
446   //   bool success = value.RemovePath("foo.bar");
447   bool RemovePath(StringPiece path);
448 
449   // Tries to extract a Value at the given path.
450   //
451   // If the current value is not a dictionary or any path component does not
452   // exist, this operation fails, leaves underlying Values untouched and returns
453   // nullopt. In case intermediate dictionaries become empty as a result of this
454   // path removal, they will be removed as well. Returns the extracted value on
455   // success.
456   // Note: If there is only one component in the path, use ExtractKey() instead.
457   //
458   // Example:
459   //   Optional<Value> maybe_value = value.ExtractPath("foo.bar");
460   Optional<Value> ExtractPath(StringPiece path);
461 
462   using dict_iterator_proxy = detail::dict_iterator_proxy;
463   using const_dict_iterator_proxy = detail::const_dict_iterator_proxy;
464 
465   // |DictItems| returns a proxy object that exposes iterators to the underlying
466   // dictionary. These are intended for iteration over all items in the
467   // dictionary and are compatible with for-each loops and standard library
468   // algorithms.
469   //
470   // Unlike with std::map, a range-for over the non-const version of DictItems()
471   // will range over items of type pair<const std::string&, Value&>, so code of
472   // the form
473   //   for (auto kv : my_value.DictItems())
474   //     Mutate(kv.second);
475   // will actually alter |my_value| in place (if it isn't const).
476   //
477   // Note: These CHECK that type() is Type::DICTIONARY.
478   dict_iterator_proxy DictItems();
479   const_dict_iterator_proxy DictItems() const;
480 
481   // Transfers ownership of the underlying dict to the caller. Subsequent
482   // calls to DictItems() will return an empty dict.
483   // Note: This requires that type() is Type::DICTIONARY.
484   DictStorage TakeDict();
485 
486   // Returns the size of the dictionary, if the dictionary is empty, and clears
487   // the dictionary. Note: These CHECK that type() is Type::DICTIONARY.
488   size_t DictSize() const;
489   bool DictEmpty() const;
490   void DictClear();
491 
492   // Merge |dictionary| into this value. This is done recursively, i.e. any
493   // sub-dictionaries will be merged as well. In case of key collisions, the
494   // passed in dictionary takes precedence and data already present will be
495   // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
496   // be freed any time after this call.
497   // Note: This requires that type() and dictionary->type() is Type::DICTIONARY.
498   void MergeDictionary(const Value* dictionary);
499 
500   // These methods allow the convenient retrieval of the contents of the Value.
501   // If the current object can be converted into the given type, the value is
502   // returned through the |out_value| parameter and true is returned;
503   // otherwise, false is returned and |out_value| is unchanged.
504   // DEPRECATED, use GetBool() instead.
505   bool GetAsBoolean(bool* out_value) const;
506   // DEPRECATED, use GetInt() instead.
507   bool GetAsInteger(int* out_value) const;
508   // DEPRECATED, use GetDouble() instead.
509   bool GetAsDouble(double* out_value) const;
510   // DEPRECATED, use GetString() instead.
511   bool GetAsString(std::string* out_value) const;
512   bool GetAsString(string16* out_value) const;
513   bool GetAsString(const Value** out_value) const;
514   bool GetAsString(StringPiece* out_value) const;
515   // ListValue::From is the equivalent for std::unique_ptr conversions.
516   // DEPRECATED, use GetList() instead.
517   bool GetAsList(ListValue** out_value);
518   bool GetAsList(const ListValue** out_value) const;
519   // DictionaryValue::From is the equivalent for std::unique_ptr conversions.
520   bool GetAsDictionary(DictionaryValue** out_value);
521   bool GetAsDictionary(const DictionaryValue** out_value) const;
522   // Note: Do not add more types. See the file-level comment above for why.
523 
524   // This creates a deep copy of the entire Value tree, and returns a pointer
525   // to the copy. The caller gets ownership of the copy, of course.
526   // Subclasses return their own type directly in their overrides;
527   // this works because C++ supports covariant return types.
528   // DEPRECATED, use Value::Clone() instead.
529   // TODO(crbug.com/646113): Delete this and migrate callsites.
530   Value* DeepCopy() const;
531   // DEPRECATED, use Value::Clone() instead.
532   // TODO(crbug.com/646113): Delete this and migrate callsites.
533   std::unique_ptr<Value> CreateDeepCopy() const;
534 
535   // Comparison operators so that Values can easily be used with standard
536   // library algorithms and associative containers.
537   BASE_EXPORT friend bool operator==(const Value& lhs, const Value& rhs);
538   BASE_EXPORT friend bool operator!=(const Value& lhs, const Value& rhs);
539   BASE_EXPORT friend bool operator<(const Value& lhs, const Value& rhs);
540   BASE_EXPORT friend bool operator>(const Value& lhs, const Value& rhs);
541   BASE_EXPORT friend bool operator<=(const Value& lhs, const Value& rhs);
542   BASE_EXPORT friend bool operator>=(const Value& lhs, const Value& rhs);
543 
544   // Compares if two Value objects have equal contents.
545   // DEPRECATED, use operator==(const Value& lhs, const Value& rhs) instead.
546   // TODO(crbug.com/646113): Delete this and migrate callsites.
547   bool Equals(const Value* other) const;
548 
549   // Estimates dynamic memory usage. Requires tracing support
550   // (enable_base_tracing gn flag), otherwise always returns 0. See
551   // base/trace_event/memory_usage_estimator.h for more info.
552   size_t EstimateMemoryUsage() const;
553 
554  protected:
555   // Checked convenience accessors for dict and list.
dict()556   const LegacyDictStorage& dict() const {
557     return absl::get<LegacyDictStorage>(data_);
558   }
dict()559   LegacyDictStorage& dict() { return absl::get<LegacyDictStorage>(data_); }
list()560   const ListStorage& list() const { return absl::get<ListStorage>(data_); }
list()561   ListStorage& list() { return absl::get<ListStorage>(data_); }
562 
563   // Internal constructors, allowing the simplify the implementation of Clone().
564   explicit Value(const LegacyDictStorage& storage);
565   explicit Value(LegacyDictStorage&& storage) noexcept;
566 
567  private:
568   // Special case for doubles, which are aligned to 8 bytes on some
569   // 32-bit architectures. In this case, a simple declaration as a
570   // double member would make the whole union 8 byte-aligned, which
571   // would also force 4 bytes of wasted padding space before it in
572   // the Value layout.
573   //
574   // To override this, store the value as an array of 32-bit integers, and
575   // perform the appropriate bit casts when reading / writing to it.
576   using DoubleStorage = struct { alignas(4) char v[sizeof(double)]; };
577 
578   // Internal constructors, allowing the simplify the implementation of Clone().
579   explicit Value(absl::monostate);
580   explicit Value(DoubleStorage storage);
581 
582   friend class ValuesTest_SizeOfValue_Test;
583   double AsDoubleInternal() const;
584 
585   // NOTE: Using a movable reference here is done for performance (it avoids
586   // creating + moving + destroying a temporary unique ptr).
587   Value* SetKeyInternal(StringPiece key, std::unique_ptr<Value>&& val_ptr);
588   Value* SetPathInternal(StringPiece path, std::unique_ptr<Value>&& value_ptr);
589 
590   absl::variant<absl::monostate,
591                 bool,
592                 int,
593                 DoubleStorage,
594                 std::string,
595                 BlobStorage,
596                 LegacyDictStorage,
597                 ListStorage>
598       data_;
599 };
600 
601 // DictionaryValue provides a key-value dictionary with (optional) "path"
602 // parsing for recursive access; see the comment at the top of the file. Keys
603 // are |std::string|s and should be UTF-8 encoded.
604 class BASE_EXPORT DictionaryValue : public Value {
605  public:
606   using const_iterator = LegacyDictStorage::const_iterator;
607   using iterator = LegacyDictStorage::iterator;
608 
609   // Returns |value| if it is a dictionary, nullptr otherwise.
610   static std::unique_ptr<DictionaryValue> From(std::unique_ptr<Value> value);
611 
612   DictionaryValue();
613   explicit DictionaryValue(const LegacyDictStorage& in_dict);
614   explicit DictionaryValue(LegacyDictStorage&& in_dict) noexcept;
615 
616   // Returns true if the current dictionary has a value for the given key.
617   // DEPRECATED, use Value::FindKey(key) instead.
618   bool HasKey(StringPiece key) const;
619 
620   // Returns the number of Values in this dictionary.
size()621   size_t size() const { return dict().size(); }
622 
623   // Returns whether the dictionary is empty.
empty()624   bool empty() const { return dict().empty(); }
625 
626   // Clears any current contents of this dictionary.
627   // DEPRECATED, use Value::DictClear() instead.
628   void Clear();
629 
630   // Sets the Value associated with the given path starting from this object.
631   // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
632   // into the next DictionaryValue down.  Obviously, "." can't be used
633   // within a key, but there are no other restrictions on keys.
634   // If the key at any step of the way doesn't exist, or exists but isn't
635   // a DictionaryValue, a new DictionaryValue will be created and attached
636   // to the path in that location. |in_value| must be non-null.
637   // Returns a pointer to the inserted value.
638   // DEPRECATED, use Value::SetPath(path, value) instead.
639   Value* Set(StringPiece path, std::unique_ptr<Value> in_value);
640 
641   // Convenience forms of Set().  These methods will replace any existing
642   // value at that path, even if it has a different type.
643   // DEPRECATED, use Value::SetBoolKey() or Value::SetBoolPath().
644   Value* SetBoolean(StringPiece path, bool in_value);
645   // DEPRECATED, use Value::SetIntPath().
646   Value* SetInteger(StringPiece path, int in_value);
647   // DEPRECATED, use Value::SetDoublePath().
648   Value* SetDouble(StringPiece path, double in_value);
649   // DEPRECATED, use Value::SetStringPath().
650   Value* SetString(StringPiece path, StringPiece in_value);
651   // DEPRECATED, use Value::SetStringPath().
652   Value* SetString(StringPiece path, const string16& in_value);
653   // DEPRECATED, use Value::SetPath().
654   DictionaryValue* SetDictionary(StringPiece path,
655                                  std::unique_ptr<DictionaryValue> in_value);
656   // DEPRECATED, use Value::SetPath().
657   ListValue* SetList(StringPiece path, std::unique_ptr<ListValue> in_value);
658 
659   // Like Set(), but without special treatment of '.'.  This allows e.g. URLs to
660   // be used as paths.
661   // DEPRECATED, use Value::SetKey(key, value) instead.
662   Value* SetWithoutPathExpansion(StringPiece key,
663                                  std::unique_ptr<Value> in_value);
664 
665   // Gets the Value associated with the given path starting from this object.
666   // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
667   // into the next DictionaryValue down.  If the path can be resolved
668   // successfully, the value for the last key in the path will be returned
669   // through the |out_value| parameter, and the function will return true.
670   // Otherwise, it will return false and |out_value| will be untouched.
671   // Note that the dictionary always owns the value that's returned.
672   // |out_value| is optional and will only be set if non-NULL.
673   // DEPRECATED, use Value::FindPath(path) instead.
674   bool Get(StringPiece path, const Value** out_value) const;
675   // DEPRECATED, use Value::FindPath(path) instead.
676   bool Get(StringPiece path, Value** out_value);
677 
678   // These are convenience forms of Get().  The value will be retrieved
679   // and the return value will be true if the path is valid and the value at
680   // the end of the path can be returned in the form specified.
681   // |out_value| is optional and will only be set if non-NULL.
682   // DEPRECATED, use Value::FindBoolPath(path) instead.
683   bool GetBoolean(StringPiece path, bool* out_value) const;
684   // DEPRECATED, use Value::FindIntPath(path) instead.
685   bool GetInteger(StringPiece path, int* out_value) const;
686   // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as
687   // doubles.
688   // DEPRECATED, use Value::FindDoublePath(path).
689   bool GetDouble(StringPiece path, double* out_value) const;
690   // DEPRECATED, use Value::FindStringPath(path) instead.
691   bool GetString(StringPiece path, std::string* out_value) const;
692   // DEPRECATED, use Value::FindStringPath(path) instead.
693   bool GetString(StringPiece path, string16* out_value) const;
694   // DEPRECATED, use Value::FindString(path) and IsAsciiString() instead.
695   bool GetStringASCII(StringPiece path, std::string* out_value) const;
696   // DEPRECATED, use Value::FindBlobPath(path) instead.
697   bool GetBinary(StringPiece path, const Value** out_value) const;
698   // DEPRECATED, use Value::FindBlobPath(path) instead.
699   bool GetBinary(StringPiece path, Value** out_value);
700   // DEPRECATED, use Value::FindPath(path) and Value's Dictionary API instead.
701   bool GetDictionary(StringPiece path, const DictionaryValue** out_value) const;
702   // DEPRECATED, use Value::FindPath(path) and Value's Dictionary API instead.
703   bool GetDictionary(StringPiece path, DictionaryValue** out_value);
704   // DEPRECATED, use Value::FindPath(path) and Value::GetList() instead.
705   bool GetList(StringPiece path, const ListValue** out_value) const;
706   // DEPRECATED, use Value::FindPath(path) and Value::GetList() instead.
707   bool GetList(StringPiece path, ListValue** out_value);
708 
709   // Like Get(), but without special treatment of '.'.  This allows e.g. URLs to
710   // be used as paths.
711   // DEPRECATED, use Value::FindKey(key) instead.
712   bool GetWithoutPathExpansion(StringPiece key, const Value** out_value) const;
713   // DEPRECATED, use Value::FindKey(key) instead.
714   bool GetWithoutPathExpansion(StringPiece key, Value** out_value);
715   // DEPRECATED, use Value::FindBoolKey(key) instead.
716   bool GetBooleanWithoutPathExpansion(StringPiece key, bool* out_value) const;
717   // DEPRECATED, use Value::FindIntKey(key) instead.
718   bool GetIntegerWithoutPathExpansion(StringPiece key, int* out_value) const;
719   // DEPRECATED, use Value::FindDoubleKey(key) instead.
720   bool GetDoubleWithoutPathExpansion(StringPiece key, double* out_value) const;
721   // DEPRECATED, use Value::FindStringKey(key) instead.
722   bool GetStringWithoutPathExpansion(StringPiece key,
723                                      std::string* out_value) const;
724   // DEPRECATED, use Value::FindStringKey(key) and UTF8ToUTF16() instead.
725   bool GetStringWithoutPathExpansion(StringPiece key,
726                                      string16* out_value) const;
727   // DEPRECATED, use Value::FindDictKey(key) instead.
728   bool GetDictionaryWithoutPathExpansion(
729       StringPiece key,
730       const DictionaryValue** out_value) const;
731   // DEPRECATED, use Value::FindDictKey(key) instead.
732   bool GetDictionaryWithoutPathExpansion(StringPiece key,
733                                          DictionaryValue** out_value);
734   // DEPRECATED, use Value::FindListKey(key) instead.
735   bool GetListWithoutPathExpansion(StringPiece key,
736                                    const ListValue** out_value) const;
737   // DEPRECATED, use Value::FindListKey(key) instead.
738   bool GetListWithoutPathExpansion(StringPiece key, ListValue** out_value);
739 
740   // Removes the Value with the specified path from this dictionary (or one
741   // of its child dictionaries, if the path is more than just a local key).
742   // If |out_value| is non-NULL, the removed Value will be passed out via
743   // |out_value|.  If |out_value| is NULL, the removed value will be deleted.
744   // This method returns true if |path| is a valid path; otherwise it will
745   // return false and the DictionaryValue object will be unchanged.
746   // DEPRECATED, use Value::RemovePath(path) or Value::ExtractPath(path)
747   // instead.
748   bool Remove(StringPiece path, std::unique_ptr<Value>* out_value);
749 
750   // Like Remove(), but without special treatment of '.'.  This allows e.g. URLs
751   // to be used as paths.
752   // DEPRECATED, use Value::RemoveKey(key) or Value::ExtractKey(key) instead.
753   bool RemoveWithoutPathExpansion(StringPiece key,
754                                   std::unique_ptr<Value>* out_value);
755 
756   // Removes a path, clearing out all dictionaries on |path| that remain empty
757   // after removing the value at |path|.
758   // DEPRECATED, use Value::RemovePath(path) or Value::ExtractPath(path)
759   // instead.
760   bool RemovePath(StringPiece path, std::unique_ptr<Value>* out_value);
761 
762   using Value::RemovePath;  // DictionaryValue::RemovePath shadows otherwise.
763 
764   // Makes a copy of |this| but doesn't include empty dictionaries and lists in
765   // the copy.  This never returns NULL, even if |this| itself is empty.
766   std::unique_ptr<DictionaryValue> DeepCopyWithoutEmptyChildren() const;
767 
768   // Swaps contents with the |other| dictionary.
769   void Swap(DictionaryValue* other);
770 
771   // This class provides an iterator over both keys and values in the
772   // dictionary.  It can't be used to modify the dictionary.
773   // DEPRECATED, use Value::DictItems() instead.
774   class BASE_EXPORT Iterator {
775    public:
776     explicit Iterator(const DictionaryValue& target);
777     Iterator(const Iterator& other);
778     ~Iterator();
779 
IsAtEnd()780     bool IsAtEnd() const { return it_ == target_.end(); }
Advance()781     void Advance() { ++it_; }
782 
key()783     const std::string& key() const { return it_->first; }
value()784     const Value& value() const { return *it_->second; }
785 
786    private:
787     const DictionaryValue& target_;
788     LegacyDictStorage::const_iterator it_;
789   };
790 
791   // Iteration.
792   // DEPRECATED, use Value::DictItems() instead.
begin()793   iterator begin() { return dict().begin(); }
end()794   iterator end() { return dict().end(); }
795 
796   // DEPRECATED, use Value::DictItems() instead.
begin()797   const_iterator begin() const { return dict().begin(); }
end()798   const_iterator end() const { return dict().end(); }
799 
800   // DEPRECATED, use Value::Clone() instead.
801   // TODO(crbug.com/646113): Delete this and migrate callsites.
802   DictionaryValue* DeepCopy() const;
803   // DEPRECATED, use Value::Clone() instead.
804   // TODO(crbug.com/646113): Delete this and migrate callsites.
805   std::unique_ptr<DictionaryValue> CreateDeepCopy() const;
806 };
807 
808 // This type of Value represents a list of other Value values.
809 // DEPRECATED: Use std::vector<base::Value> instead.
810 class BASE_EXPORT ListValue : public Value {
811  public:
812   using const_iterator = ListView::const_iterator;
813   using iterator = ListView::iterator;
814 
815   // Returns |value| if it is a list, nullptr otherwise.
816   static std::unique_ptr<ListValue> From(std::unique_ptr<Value> value);
817 
818   ListValue();
819   explicit ListValue(span<const Value> in_list);
820   explicit ListValue(ListStorage&& in_list) noexcept;
821 
822   // Clears the contents of this ListValue
823   // DEPRECATED, use ClearList() instead.
824   void Clear();
825 
826   // Returns the number of Values in this list.
827   // DEPRECATED, use GetList()::size() instead.
GetSize()828   size_t GetSize() const { return list().size(); }
829 
830   // Returns whether the list is empty.
831   // DEPRECATED, use GetList()::empty() instead.
empty()832   bool empty() const { return list().empty(); }
833 
834   // Sets the list item at the given index to be the Value specified by
835   // the value given.  If the index beyond the current end of the list, null
836   // Values will be used to pad out the list.
837   // Returns true if successful, or false if the index was negative or
838   // the value is a null pointer.
839   // DEPRECATED, use GetList()::operator[] instead.
840   bool Set(size_t index, std::unique_ptr<Value> in_value);
841 
842   // Gets the Value at the given index.  Modifies |out_value| (and returns true)
843   // only if the index falls within the current list range.
844   // Note that the list always owns the Value passed out via |out_value|.
845   // |out_value| is optional and will only be set if non-NULL.
846   // DEPRECATED, use GetList()::operator[] instead.
847   bool Get(size_t index, const Value** out_value) const;
848   bool Get(size_t index, Value** out_value);
849 
850   // Convenience forms of Get().  Modifies |out_value| (and returns true)
851   // only if the index is valid and the Value at that index can be returned
852   // in the specified form.
853   // |out_value| is optional and will only be set if non-NULL.
854   // DEPRECATED, use GetList()::operator[]::GetBool() instead.
855   bool GetBoolean(size_t index, bool* out_value) const;
856   // DEPRECATED, use GetList()::operator[]::GetInt() instead.
857   bool GetInteger(size_t index, int* out_value) const;
858   // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as
859   // doubles.
860   // DEPRECATED, use GetList()::operator[]::GetDouble() instead.
861   bool GetDouble(size_t index, double* out_value) const;
862   // DEPRECATED, use GetList()::operator[]::GetString() instead.
863   bool GetString(size_t index, std::string* out_value) const;
864   bool GetString(size_t index, string16* out_value) const;
865 
866   bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
867   bool GetDictionary(size_t index, DictionaryValue** out_value);
868 
869   using Value::GetList;
870   // DEPRECATED, use GetList()::operator[]::GetList() instead.
871   bool GetList(size_t index, const ListValue** out_value) const;
872   bool GetList(size_t index, ListValue** out_value);
873 
874   // Removes the Value with the specified index from this list.
875   // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
876   // passed out via |out_value|.  If |out_value| is NULL, the removed value will
877   // be deleted.  This method returns true if |index| is valid; otherwise
878   // it will return false and the ListValue object will be unchanged.
879   // DEPRECATED, use GetList()::erase() instead.
880   bool Remove(size_t index, std::unique_ptr<Value>* out_value);
881 
882   // Removes the first instance of |value| found in the list, if any, and
883   // deletes it. |index| is the location where |value| was found. Returns false
884   // if not found.
885   // DEPRECATED, use GetList()::erase() instead.
886   bool Remove(const Value& value, size_t* index);
887 
888   // Removes the element at |iter|. If |out_value| is NULL, the value will be
889   // deleted, otherwise ownership of the value is passed back to the caller.
890   // Returns an iterator pointing to the location of the element that
891   // followed the erased element.
892   // DEPRECATED, use GetList()::erase() instead.
893   iterator Erase(iterator iter, std::unique_ptr<Value>* out_value);
894 
895   using Value::Append;
896   // Appends a Value to the end of the list.
897   // DEPRECATED, use Value::Append() instead.
898   void Append(std::unique_ptr<Value> in_value);
899 
900   // Convenience forms of Append.
901   // DEPRECATED, use Value::Append() instead.
902   void AppendBoolean(bool in_value);
903   void AppendInteger(int in_value);
904   void AppendDouble(double in_value);
905   void AppendString(StringPiece in_value);
906   void AppendString(const string16& in_value);
907   // DEPRECATED, use Value::Append() in a loop instead.
908   void AppendStrings(const std::vector<std::string>& in_values);
909 
910   // Appends a Value if it's not already present. Returns true if successful,
911   // or false if the value was already
912   // DEPRECATED, use std::find() with Value::Append() instead.
913   bool AppendIfNotPresent(std::unique_ptr<Value> in_value);
914 
915   using Value::Insert;
916   // Insert a Value at index.
917   // Returns true if successful, or false if the index was out of range.
918   // DEPRECATED, use Value::Insert() instead.
919   bool Insert(size_t index, std::unique_ptr<Value> in_value);
920 
921   // Searches for the first instance of |value| in the list using the Equals
922   // method of the Value type.
923   // Returns a const_iterator to the found item or to end() if none exists.
924   // DEPRECATED, use std::find() instead.
925   const_iterator Find(const Value& value) const;
926 
927   // Swaps contents with the |other| list.
928   // DEPRECATED, use GetList()::swap() instead.
929   void Swap(ListValue* other);
930 
931   // Iteration.
932   // DEPRECATED, use GetList()::begin() instead.
begin()933   iterator begin() { return GetList().begin(); }
934   // DEPRECATED, use GetList()::end() instead.
end()935   iterator end() { return GetList().end(); }
936 
937   // DEPRECATED, use GetList()::begin() instead.
begin()938   const_iterator begin() const { return GetList().begin(); }
939   // DEPRECATED, use GetList()::end() instead.
end()940   const_iterator end() const { return GetList().end(); }
941 
942   // DEPRECATED, use Value::Clone() instead.
943   // TODO(crbug.com/646113): Delete this and migrate callsites.
944   ListValue* DeepCopy() const;
945   // DEPRECATED, use Value::Clone() instead.
946   // TODO(crbug.com/646113): Delete this and migrate callsites.
947   std::unique_ptr<ListValue> CreateDeepCopy() const;
948 };
949 
950 // This interface is implemented by classes that know how to serialize
951 // Value objects.
952 class BASE_EXPORT ValueSerializer {
953  public:
954   virtual ~ValueSerializer();
955 
956   virtual bool Serialize(const Value& root) = 0;
957 };
958 
959 // This interface is implemented by classes that know how to deserialize Value
960 // objects.
961 class BASE_EXPORT ValueDeserializer {
962  public:
963   virtual ~ValueDeserializer();
964 
965   // This method deserializes the subclass-specific format into a Value object.
966   // If the return value is non-NULL, the caller takes ownership of returned
967   // Value.
968   //
969   // If the return value is nullptr, and if |error_code| is non-nullptr,
970   // |*error_code| will be set to an integer value representing the underlying
971   // error. See "enum ErrorCode" below for more detail about the integer value.
972   //
973   // If |error_message| is non-nullptr, it will be filled in with a formatted
974   // error message including the location of the error if appropriate.
975   virtual std::unique_ptr<Value> Deserialize(int* error_code,
976                                              std::string* error_message) = 0;
977 
978   // The integer-valued error codes form four groups:
979   //  - The value 0 means no error.
980   //  - Values between 1 and 999 inclusive mean an error in the data (i.e.
981   //    content). The bytes being deserialized are not in the right format.
982   //  - Values 1000 and above mean an error in the metadata (i.e. context). The
983   //    file could not be read, the network is down, etc.
984   //  - Negative values are reserved.
985   enum ErrorCode {
986     kErrorCodeNoError = 0,
987     // kErrorCodeInvalidFormat is a generic error code for "the data is not in
988     // the right format". Subclasses of ValueDeserializer may return other
989     // values for more specific errors.
990     kErrorCodeInvalidFormat = 1,
991     // kErrorCodeFirstMetadataError is the minimum value (inclusive) of the
992     // range of metadata errors.
993     kErrorCodeFirstMetadataError = 1000,
994   };
995 
996   // The |error_code| argument can be one of the ErrorCode values, but it is
997   // not restricted to only being 0, 1 or 1000. Subclasses of ValueDeserializer
998   // can define their own error code values.
ErrorCodeIsDataError(int error_code)999   static inline bool ErrorCodeIsDataError(int error_code) {
1000     return (kErrorCodeInvalidFormat <= error_code) &&
1001            (error_code < kErrorCodeFirstMetadataError);
1002   }
1003 };
1004 
1005 // Stream operator so Values can be used in assertion statements.  In order that
1006 // gtest uses this operator to print readable output on test failures, we must
1007 // override each specific type. Otherwise, the default template implementation
1008 // is preferred over an upcast.
1009 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
1010 
1011 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
1012                                             const DictionaryValue& value) {
1013   return out << static_cast<const Value&>(value);
1014 }
1015 
1016 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
1017                                             const ListValue& value) {
1018   return out << static_cast<const Value&>(value);
1019 }
1020 
1021 // Stream operator so that enum class Types can be used in log statements.
1022 BASE_EXPORT std::ostream& operator<<(std::ostream& out,
1023                                      const Value::Type& type);
1024 
1025 }  // namespace base
1026 
1027 #endif  // BASE_VALUES_H_
1028