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.
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_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.
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.
21 #ifndef BASE_VALUES_H_
22 #define BASE_VALUES_H_
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/macros.h"
40 #include "base/strings/string16.h"
41 #include "base/strings/string_piece.h"
42 #include "base/value_iterators.h"
46 class DictionaryValue;
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.
53 // See the file-level comment above for more information.
55 // base::Value is currently in the process of being refactored. Design doc:
56 // https://docs.google.com/document/d/1uDLu5uTRlCWePxQUEHc8yNQdEoE1BDISYdpggWEABnw
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
65 // std::unique_ptr<base::Value> GetFoo() {
66 // std::unique_ptr<DictionaryValue> dict;
67 // dict->SetString("mykey", foo);
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.
78 // base::Value GetFoo() {
79 // base::Value dict(base::Value::Type::DICTIONARY);
80 // dict.SetKey("mykey", base::Value(foo));
83 class BASE_EXPORT Value {
85 using BlobStorage = std::vector<uint8_t>;
86 using DictStorage = flat_map<std::string, std::unique_ptr<Value>>;
87 using ListStorage = std::vector<Value>;
89 using ListView = CheckedContiguousRange<ListStorage>;
90 using ConstListView = CheckedContiguousConstRange<ListStorage>;
92 // See technical note below explaining why this is used.
93 using DoubleStorage = struct { alignas(4) char v[sizeof(double)]; };
95 enum class Type : unsigned char {
104 // TODO(crbug.com/859477): Remove once root cause is found.
106 // Note: Do not add more types. See the file-level comment above for why.
109 // For situations where you want to keep ownership of your buffer, this
110 // factory method creates a new BinaryValue by copying the contents of the
111 // buffer that's passed in.
112 // DEPRECATED, use std::make_unique<Value>(const BlobStorage&) instead.
113 // TODO(crbug.com/646113): Delete this and migrate callsites.
114 static std::unique_ptr<Value> CreateWithCopiedBuffer(const char* buffer,
117 // Adaptors for converting from the old way to the new way and vice versa.
118 static Value FromUniquePtrValue(std::unique_ptr<Value> val);
119 static std::unique_ptr<Value> ToUniquePtrValue(Value val);
120 static const DictionaryValue& AsDictionaryValue(const Value& val);
121 static const ListValue& AsListValue(const Value& val);
123 Value(Value&& that) noexcept;
124 Value() noexcept {} // A null value
125 // Fun fact: using '= default' above instead of '{}' does not work because
126 // the compiler complains that the default constructor was deleted since
127 // the inner union contains fields with non-default constructors.
129 // Value's copy constructor and copy assignment operator are deleted. Use this
130 // to obtain a deep copy explicitly.
133 explicit Value(Type type);
134 explicit Value(bool in_bool);
135 explicit Value(int in_int);
136 explicit Value(double in_double);
138 // Value(const char*) and Value(const char16*) are required despite
139 // Value(StringPiece) and Value(StringPiece16) because otherwise the
140 // compiler will choose the Value(bool) constructor for these arguments.
141 // Value(std::string&&) allow for efficient move construction.
142 explicit Value(const char* in_string);
143 explicit Value(StringPiece in_string);
144 explicit Value(std::string&& in_string) noexcept;
145 explicit Value(const char16* in_string16);
146 explicit Value(StringPiece16 in_string16);
148 explicit Value(const std::vector<char>& in_blob);
149 explicit Value(base::span<const uint8_t> in_blob);
150 explicit Value(BlobStorage&& in_blob) noexcept;
152 explicit Value(const DictStorage& in_dict);
153 explicit Value(DictStorage&& in_dict) noexcept;
155 explicit Value(span<const Value> in_list);
156 explicit Value(ListStorage&& in_list) noexcept;
158 Value& operator=(Value&& that) noexcept;
162 // Returns the name for a given |type|.
163 static const char* GetTypeName(Type type);
165 // Returns the type of the value stored by the current Value object.
166 Type type() const { return type_; }
168 // Returns true if the current object represents a given type.
169 bool is_none() const { return type() == Type::NONE; }
170 bool is_bool() const { return type() == Type::BOOLEAN; }
171 bool is_int() const { return type() == Type::INTEGER; }
172 bool is_double() const { return type() == Type::DOUBLE; }
173 bool is_string() const { return type() == Type::STRING; }
174 bool is_blob() const { return type() == Type::BINARY; }
175 bool is_dict() const { return type() == Type::DICTIONARY; }
176 bool is_list() const { return type() == Type::LIST; }
178 // These will all CHECK that the type matches.
179 bool GetBool() const;
181 double GetDouble() const; // Implicitly converts from int if necessary.
182 const std::string& GetString() const;
183 std::string& GetString();
184 const BlobStorage& GetBlob() const;
186 // Returns the Values in a list as a view. The mutable overload allows for
187 // modification of the underlying values, but does not allow changing the
188 // structure of the list. If this is desired, use TakeList(), perform the
189 // operations, and return the list back to the Value via move assignment.
191 ConstListView GetList() const;
193 // Transfers ownership of the the underlying list to the caller. Subsequent
194 // calls to GetList() will return an empty list.
195 // Note: This CHECKs that type() is Type::LIST.
196 ListStorage TakeList();
198 // Appends |value| to the end of the list.
199 // Note: These CHECK that type() is Type::LIST.
200 void Append(bool value);
201 void Append(int value);
202 void Append(double value);
203 void Append(const char* value);
204 void Append(StringPiece value);
205 void Append(std::string&& value);
206 void Append(const char16* value);
207 void Append(StringPiece16 value);
208 void Append(Value&& value);
210 // Inserts |value| before |pos|.
211 // Note: This CHECK that type() is Type::LIST.
212 CheckedContiguousIterator<Value> Insert(
213 CheckedContiguousConstIterator<Value> pos,
216 // Erases the Value pointed to by |iter|. Returns false if |iter| is out of
218 // Note: This CHECKs that type() is Type::LIST.
219 bool EraseListIter(CheckedContiguousConstIterator<Value> iter);
221 // Erases all Values that compare equal to |val|. Returns the number of
223 // Note: This CHECKs that type() is Type::LIST.
224 size_t EraseListValue(const Value& val);
226 // Erases all Values for which |pred| returns true. Returns the number of
228 // Note: This CHECKs that type() is Type::LIST.
229 template <typename Predicate>
230 size_t EraseListValueIf(Predicate pred) {
232 return base::EraseIf(list_, pred);
235 // Erases all Values from the list.
236 // Note: This CHECKs that type() is Type::LIST.
239 // |FindKey| looks up |key| in the underlying dictionary. If found, it returns
240 // a pointer to the element. Otherwise it returns nullptr.
241 // returned. Callers are expected to perform a check against null before using
243 // Note: This CHECKs that type() is Type::DICTIONARY.
246 // auto* found = FindKey("foo");
247 Value* FindKey(StringPiece key);
248 const Value* FindKey(StringPiece key) const;
250 // |FindKeyOfType| is similar to |FindKey|, but it also requires the found
251 // value to have type |type|. If no type is found, or the found value is of a
252 // different type nullptr is returned.
253 // Callers are expected to perform a check against null before using the
255 // Note: This CHECKs that type() is Type::DICTIONARY.
258 // auto* found = FindKey("foo", Type::DOUBLE);
259 Value* FindKeyOfType(StringPiece key, Type type);
260 const Value* FindKeyOfType(StringPiece key, Type type) const;
262 // These are convenience forms of |FindKey|. They return |base::nullopt| if
263 // the value is not found or doesn't have the type specified in the
265 base::Optional<bool> FindBoolKey(StringPiece key) const;
266 base::Optional<int> FindIntKey(StringPiece key) const;
267 // Note FindDoubleKey() will auto-convert INTEGER keys to their double
268 // value, for consistency with GetDouble().
269 base::Optional<double> FindDoubleKey(StringPiece key) const;
271 // |FindStringKey| returns |nullptr| if value is not found or not a string.
272 const std::string* FindStringKey(StringPiece key) const;
273 std::string* FindStringKey(StringPiece key);
275 // Returns nullptr is value is not found or not a binary.
276 const BlobStorage* FindBlobKey(StringPiece key) const;
278 // Returns nullptr if value is not found or not a dictionary.
279 const Value* FindDictKey(StringPiece key) const;
280 Value* FindDictKey(StringPiece key);
282 // Returns nullptr if value is not found or not a list.
283 const Value* FindListKey(StringPiece key) const;
284 Value* FindListKey(StringPiece key);
286 // |SetKey| looks up |key| in the underlying dictionary and sets the mapped
287 // value to |value|. If |key| could not be found, a new element is inserted.
288 // A pointer to the modified item is returned.
289 // Note: This CHECKs that type() is Type::DICTIONARY.
290 // Note: Prefer Set<Type>Key() for simple values.
293 // SetKey("foo", std::move(myvalue));
294 Value* SetKey(StringPiece key, Value&& value);
295 // This overload results in a performance improvement for std::string&&.
296 Value* SetKey(std::string&& key, Value&& value);
297 // This overload is necessary to avoid ambiguity for const char* arguments.
298 Value* SetKey(const char* key, Value&& value);
300 // |Set<Type>Key| looks up |key| in the underlying dictionary and associates
301 // a corresponding Value() constructed from the second parameter. Compared
302 // to SetKey(), this avoids un-necessary temporary Value() creation, as well
303 // ambiguities in the value type.
304 Value* SetBoolKey(StringPiece key, bool val);
305 Value* SetIntKey(StringPiece key, int val);
306 Value* SetDoubleKey(StringPiece key, double val);
307 Value* SetStringKey(StringPiece key, StringPiece val);
308 Value* SetStringKey(StringPiece key, StringPiece16 val);
309 // NOTE: The following two overloads are provided as performance / code
310 // generation optimizations.
311 Value* SetStringKey(StringPiece key, const char* val);
312 Value* SetStringKey(StringPiece key, std::string&& val);
314 // This attempts to remove the value associated with |key|. In case of
315 // failure, e.g. the key does not exist, false is returned and the underlying
316 // dictionary is not changed. In case of success, |key| is deleted from the
317 // dictionary and the method returns true.
318 // Note: This CHECKs that type() is Type::DICTIONARY.
321 // bool success = dict.RemoveKey("foo");
322 bool RemoveKey(StringPiece key);
324 // This attempts to extract the value associated with |key|. In case of
325 // failure, e.g. the key does not exist, nullopt is returned and the
326 // underlying dictionary is not changed. In case of success, |key| is deleted
327 // from the dictionary and the method returns the extracted Value.
328 // Note: This CHECKs that type() is Type::DICTIONARY.
331 // Optional<Value> maybe_value = dict.ExtractKey("foo");
332 Optional<Value> ExtractKey(StringPiece key);
334 // Searches a hierarchy of dictionary values for a given value. If a path
335 // of dictionaries exist, returns the item at that path. If any of the path
336 // components do not exist or if any but the last path components are not
337 // dictionaries, returns nullptr.
339 // The type of the leaf Value is not checked.
341 // Implementation note: This can't return an iterator because the iterator
342 // will actually be into another Value, so it can't be compared to iterators
343 // from this one (in particular, the DictItems().end() iterator).
345 // This version takes a StringPiece for the path, using dots as separators.
347 // auto* found = FindPath("foo.bar");
348 Value* FindPath(StringPiece path);
349 const Value* FindPath(StringPiece path) const;
351 // There are also deprecated versions that take the path parameter
352 // as either a std::initializer_list<StringPiece> or a
353 // span<const StringPiece>. The latter is useful to use a
354 // std::vector<std::string> as a parameter but creates huge dynamic
355 // allocations and should be avoided!
356 // Note: If there is only one component in the path, use FindKey() instead.
359 // std::vector<StringPiece> components = ...
360 // auto* found = FindPath(components);
361 Value* FindPath(std::initializer_list<StringPiece> path);
362 Value* FindPath(span<const StringPiece> path);
363 const Value* FindPath(std::initializer_list<StringPiece> path) const;
364 const Value* FindPath(span<const StringPiece> path) const;
366 // Like FindPath() but will only return the value if the leaf Value type
367 // matches the given type. Will return nullptr otherwise.
368 // Note: Prefer Find<Type>Path() for simple values.
370 // Note: If there is only one component in the path, use FindKeyOfType()
371 // instead for slightly better performance.
372 Value* FindPathOfType(StringPiece path, Type type);
373 const Value* FindPathOfType(StringPiece path, Type type) const;
375 // Convenience accessors used when the expected type of a value is known.
376 // Similar to Find<Type>Key() but accepts paths instead of keys.
377 base::Optional<bool> FindBoolPath(StringPiece path) const;
378 base::Optional<int> FindIntPath(StringPiece path) const;
379 base::Optional<double> FindDoublePath(StringPiece path) const;
380 const std::string* FindStringPath(StringPiece path) const;
381 std::string* FindStringPath(StringPiece path);
382 const BlobStorage* FindBlobPath(StringPiece path) const;
383 Value* FindDictPath(StringPiece path);
384 const Value* FindDictPath(StringPiece path) const;
385 Value* FindListPath(StringPiece path);
386 const Value* FindListPath(StringPiece path) const;
388 // The following forms are deprecated too, use the ones that take the path
389 // as a single StringPiece instead.
390 Value* FindPathOfType(std::initializer_list<StringPiece> path, Type type);
391 Value* FindPathOfType(span<const StringPiece> path, Type type);
392 const Value* FindPathOfType(std::initializer_list<StringPiece> path,
394 const Value* FindPathOfType(span<const StringPiece> path, Type type) const;
396 // Sets the given path, expanding and creating dictionary keys as necessary.
398 // If the current value is not a dictionary, the function returns nullptr. If
399 // path components do not exist, they will be created. If any but the last
400 // components matches a value that is not a dictionary, the function will fail
401 // (it will not overwrite the value) and return nullptr. The last path
402 // component will be unconditionally overwritten if it exists, and created if
406 // value.SetPath("foo.bar", std::move(myvalue));
408 // Note: If there is only one component in the path, use SetKey() instead.
409 // Note: Using Set<Type>Path() might be more convenient and efficient.
410 Value* SetPath(StringPiece path, Value&& value);
412 // These setters are more convenient and efficient than the corresponding
413 // SetPath(...) call.
414 Value* SetBoolPath(StringPiece path, bool value);
415 Value* SetIntPath(StringPiece path, int value);
416 Value* SetDoublePath(StringPiece path, double value);
417 Value* SetStringPath(StringPiece path, StringPiece value);
418 Value* SetStringPath(StringPiece path, const char* value);
419 Value* SetStringPath(StringPiece path, std::string&& value);
420 Value* SetStringPath(StringPiece path, StringPiece16 value);
422 // Deprecated: use the ones that take a StringPiece path parameter instead.
423 Value* SetPath(std::initializer_list<StringPiece> path, Value&& value);
424 Value* SetPath(span<const StringPiece> path, Value&& value);
426 // Tries to remove a Value at the given path.
428 // If the current value is not a dictionary or any path component does not
429 // exist, this operation fails, leaves underlying Values untouched and returns
430 // |false|. In case intermediate dictionaries become empty as a result of this
431 // path removal, they will be removed as well.
432 // Note: If there is only one component in the path, use ExtractKey() instead.
435 // bool success = value.RemovePath("foo.bar");
436 bool RemovePath(StringPiece path);
438 // Deprecated versions
439 bool RemovePath(std::initializer_list<StringPiece> path);
440 bool RemovePath(span<const StringPiece> path);
442 // Tries to extract a Value at the given path.
444 // If the current value is not a dictionary or any path component does not
445 // exist, this operation fails, leaves underlying Values untouched and returns
446 // nullopt. In case intermediate dictionaries become empty as a result of this
447 // path removal, they will be removed as well. Returns the extracted value on
449 // Note: If there is only one component in the path, use ExtractKey() instead.
452 // Optional<Value> maybe_value = value.ExtractPath("foo.bar");
453 Optional<Value> ExtractPath(StringPiece path);
455 using dict_iterator_proxy = detail::dict_iterator_proxy;
456 using const_dict_iterator_proxy = detail::const_dict_iterator_proxy;
458 // |DictItems| returns a proxy object that exposes iterators to the underlying
459 // dictionary. These are intended for iteration over all items in the
460 // dictionary and are compatible with for-each loops and standard library
463 // Unlike with std::map, a range-for over the non-const version of DictItems()
464 // will range over items of type pair<const std::string&, Value&>, so code of
466 // for (auto kv : my_value.DictItems())
467 // Mutate(kv.second);
468 // will actually alter |my_value| in place (if it isn't const).
470 // Note: These CHECK that type() is Type::DICTIONARY.
471 dict_iterator_proxy DictItems();
472 const_dict_iterator_proxy DictItems() const;
474 // Returns the size of the dictionary, and if the dictionary is empty.
475 // Note: These CHECK that type() is Type::DICTIONARY.
476 size_t DictSize() const;
477 bool DictEmpty() const;
479 // Merge |dictionary| into this value. This is done recursively, i.e. any
480 // sub-dictionaries will be merged as well. In case of key collisions, the
481 // passed in dictionary takes precedence and data already present will be
482 // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
483 // be freed any time after this call.
484 // Note: This CHECKs that type() and dictionary->type() is Type::DICTIONARY.
485 void MergeDictionary(const Value* dictionary);
487 // These methods allow the convenient retrieval of the contents of the Value.
488 // If the current object can be converted into the given type, the value is
489 // returned through the |out_value| parameter and true is returned;
490 // otherwise, false is returned and |out_value| is unchanged.
491 // DEPRECATED, use GetBool() instead.
492 bool GetAsBoolean(bool* out_value) const;
493 // DEPRECATED, use GetInt() instead.
494 bool GetAsInteger(int* out_value) const;
495 // DEPRECATED, use GetDouble() instead.
496 bool GetAsDouble(double* out_value) const;
497 // DEPRECATED, use GetString() instead.
498 bool GetAsString(std::string* out_value) const;
499 bool GetAsString(string16* out_value) const;
500 bool GetAsString(const Value** out_value) const;
501 bool GetAsString(StringPiece* out_value) const;
502 // ListValue::From is the equivalent for std::unique_ptr conversions.
503 // DEPRECATED, use GetList() instead.
504 bool GetAsList(ListValue** out_value);
505 bool GetAsList(const ListValue** out_value) const;
506 // DictionaryValue::From is the equivalent for std::unique_ptr conversions.
507 bool GetAsDictionary(DictionaryValue** out_value);
508 bool GetAsDictionary(const DictionaryValue** out_value) const;
509 // Note: Do not add more types. See the file-level comment above for why.
511 // This creates a deep copy of the entire Value tree, and returns a pointer
512 // to the copy. The caller gets ownership of the copy, of course.
513 // Subclasses return their own type directly in their overrides;
514 // this works because C++ supports covariant return types.
515 // DEPRECATED, use Value::Clone() instead.
516 // TODO(crbug.com/646113): Delete this and migrate callsites.
517 Value* DeepCopy() const;
518 // DEPRECATED, use Value::Clone() instead.
519 // TODO(crbug.com/646113): Delete this and migrate callsites.
520 std::unique_ptr<Value> CreateDeepCopy() const;
522 // Comparison operators so that Values can easily be used with standard
523 // library algorithms and associative containers.
524 BASE_EXPORT friend bool operator==(const Value& lhs, const Value& rhs);
525 BASE_EXPORT friend bool operator!=(const Value& lhs, const Value& rhs);
526 BASE_EXPORT friend bool operator<(const Value& lhs, const Value& rhs);
527 BASE_EXPORT friend bool operator>(const Value& lhs, const Value& rhs);
528 BASE_EXPORT friend bool operator<=(const Value& lhs, const Value& rhs);
529 BASE_EXPORT friend bool operator>=(const Value& lhs, const Value& rhs);
531 // Compares if two Value objects have equal contents.
532 // DEPRECATED, use operator==(const Value& lhs, const Value& rhs) instead.
533 // TODO(crbug.com/646113): Delete this and migrate callsites.
534 bool Equals(const Value* other) const;
536 // Estimates dynamic memory usage. Requires tracing support
537 // (enable_base_tracing gn flag), otherwise always returns 0. See
538 // base/trace_event/memory_usage_estimator.h for more info.
539 size_t EstimateMemoryUsage() const;
542 // Special case for doubles, which are aligned to 8 bytes on some
543 // 32-bit architectures. In this case, a simple declaration as a
544 // double member would make the whole union 8 byte-aligned, which
545 // would also force 4 bytes of wasted padding space before it in
548 // To override this, store the value as an array of 32-bit integers, and
549 // perform the appropriate bit casts when reading / writing to it.
550 Type type_ = Type::NONE;
555 DoubleStorage double_value_;
556 std::string string_value_;
557 BlobStorage binary_value_;
563 friend class ValuesTest_SizeOfValue_Test;
564 double AsDoubleInternal() const;
565 void InternalMoveConstructFrom(Value&& that);
566 void InternalCleanup();
568 // NOTE: Using a movable reference here is done for performance (it avoids
569 // creating + moving + destroying a temporary unique ptr).
570 Value* SetKeyInternal(StringPiece key, std::unique_ptr<Value>&& val_ptr);
571 Value* SetPathInternal(StringPiece path, std::unique_ptr<Value>&& value_ptr);
573 DISALLOW_COPY_AND_ASSIGN(Value);
576 // DictionaryValue provides a key-value dictionary with (optional) "path"
577 // parsing for recursive access; see the comment at the top of the file. Keys
578 // are |std::string|s and should be UTF-8 encoded.
579 class BASE_EXPORT DictionaryValue : public Value {
581 using const_iterator = DictStorage::const_iterator;
582 using iterator = DictStorage::iterator;
584 // Returns |value| if it is a dictionary, nullptr otherwise.
585 static std::unique_ptr<DictionaryValue> From(std::unique_ptr<Value> value);
588 explicit DictionaryValue(const DictStorage& in_dict);
589 explicit DictionaryValue(DictStorage&& in_dict) noexcept;
591 // Returns true if the current dictionary has a value for the given key.
592 // DEPRECATED, use Value::FindKey(key) instead.
593 bool HasKey(StringPiece key) const;
595 // Returns the number of Values in this dictionary.
596 size_t size() const { return dict_.size(); }
598 // Returns whether the dictionary is empty.
599 bool empty() const { return dict_.empty(); }
601 // Clears any current contents of this dictionary.
604 // Sets the Value associated with the given path starting from this object.
605 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
606 // into the next DictionaryValue down. Obviously, "." can't be used
607 // within a key, but there are no other restrictions on keys.
608 // If the key at any step of the way doesn't exist, or exists but isn't
609 // a DictionaryValue, a new DictionaryValue will be created and attached
610 // to the path in that location. |in_value| must be non-null.
611 // Returns a pointer to the inserted value.
612 // DEPRECATED, use Value::SetPath(path, value) instead.
613 Value* Set(StringPiece path, std::unique_ptr<Value> in_value);
615 // Convenience forms of Set(). These methods will replace any existing
616 // value at that path, even if it has a different type.
617 // DEPRECATED, use Value::SetBoolKey() or Value::SetBoolPath().
618 Value* SetBoolean(StringPiece path, bool in_value);
619 // DEPRECATED, use Value::SetIntPath().
620 Value* SetInteger(StringPiece path, int in_value);
621 // DEPRECATED, use Value::SetDoublePath().
622 Value* SetDouble(StringPiece path, double in_value);
623 // DEPRECATED, use Value::SetStringPath().
624 Value* SetString(StringPiece path, StringPiece in_value);
625 // DEPRECATED, use Value::SetStringPath().
626 Value* SetString(StringPiece path, const string16& in_value);
627 // DEPRECATED, use Value::SetPath() or Value::SetDictPath()
628 DictionaryValue* SetDictionary(StringPiece path,
629 std::unique_ptr<DictionaryValue> in_value);
630 // DEPRECATED, use Value::SetPath() or Value::SetListPath()
631 ListValue* SetList(StringPiece path, std::unique_ptr<ListValue> in_value);
633 // Like Set(), but without special treatment of '.'. This allows e.g. URLs to
635 // DEPRECATED, use Value::SetKey(key, value) instead.
636 Value* SetWithoutPathExpansion(StringPiece key,
637 std::unique_ptr<Value> in_value);
639 // Gets the Value associated with the given path starting from this object.
640 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
641 // into the next DictionaryValue down. If the path can be resolved
642 // successfully, the value for the last key in the path will be returned
643 // through the |out_value| parameter, and the function will return true.
644 // Otherwise, it will return false and |out_value| will be untouched.
645 // Note that the dictionary always owns the value that's returned.
646 // |out_value| is optional and will only be set if non-NULL.
647 // DEPRECATED, use Value::FindPath(path) instead.
648 bool Get(StringPiece path, const Value** out_value) const;
649 // DEPRECATED, use Value::FindPath(path) instead.
650 bool Get(StringPiece path, Value** out_value);
652 // These are convenience forms of Get(). The value will be retrieved
653 // and the return value will be true if the path is valid and the value at
654 // the end of the path can be returned in the form specified.
655 // |out_value| is optional and will only be set if non-NULL.
656 // DEPRECATED, use Value::FindBoolPath(path) instead.
657 bool GetBoolean(StringPiece path, bool* out_value) const;
658 // DEPRECATED, use Value::FindIntPath(path) instead.
659 bool GetInteger(StringPiece path, int* out_value) const;
660 // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as
662 // DEPRECATED, use Value::FindDoublePath(path).
663 bool GetDouble(StringPiece path, double* out_value) const;
664 // DEPRECATED, use Value::FindStringPath(path) instead.
665 bool GetString(StringPiece path, std::string* out_value) const;
666 // DEPRECATED, use Value::FindStringPath(path) instead.
667 bool GetString(StringPiece path, string16* out_value) const;
668 // DEPRECATED, use Value::FindString(path) and IsAsciiString() instead.
669 bool GetStringASCII(StringPiece path, std::string* out_value) const;
670 // DEPRECATED, use Value::FindBlobPath(path) instead.
671 bool GetBinary(StringPiece path, const Value** out_value) const;
672 // DEPRECATED, use Value::FindBlobPath(path) instead.
673 bool GetBinary(StringPiece path, Value** out_value);
674 // DEPRECATED, use Value::FindPath(path) and Value's Dictionary API instead.
675 bool GetDictionary(StringPiece path,
676 const DictionaryValue** out_value) const;
677 // DEPRECATED, use Value::FindPath(path) and Value's Dictionary API instead.
678 bool GetDictionary(StringPiece path, DictionaryValue** out_value);
679 // DEPRECATED, use Value::FindPath(path) and Value::GetList() instead.
680 bool GetList(StringPiece path, const ListValue** out_value) const;
681 // DEPRECATED, use Value::FindPath(path) and Value::GetList() instead.
682 bool GetList(StringPiece path, ListValue** out_value);
684 // Like Get(), but without special treatment of '.'. This allows e.g. URLs to
686 // DEPRECATED, use Value::FindKey(key) instead.
687 bool GetWithoutPathExpansion(StringPiece key, const Value** out_value) const;
688 // DEPRECATED, use Value::FindKey(key) instead.
689 bool GetWithoutPathExpansion(StringPiece key, Value** out_value);
690 // DEPRECATED, use Value::FindBoolKey(key) instead.
691 bool GetBooleanWithoutPathExpansion(StringPiece key, bool* out_value) const;
692 // DEPRECATED, use Value::FindIntKey(key) instead.
693 bool GetIntegerWithoutPathExpansion(StringPiece key, int* out_value) const;
694 // DEPRECATED, use Value::FindDoubleKey(key) instead.
695 bool GetDoubleWithoutPathExpansion(StringPiece key, double* out_value) const;
696 // DEPRECATED, use Value::FindStringKey(key) instead.
697 bool GetStringWithoutPathExpansion(StringPiece key,
698 std::string* out_value) const;
699 // DEPRECATED, use Value::FindStringKey(key) and UTF8ToUTF16() instead.
700 bool GetStringWithoutPathExpansion(StringPiece key,
701 string16* out_value) const;
702 // DEPRECATED, use Value::FindDictKey(key) instead.
703 bool GetDictionaryWithoutPathExpansion(
705 const DictionaryValue** out_value) const;
706 // DEPRECATED, use Value::FindDictKey(key) instead.
707 bool GetDictionaryWithoutPathExpansion(StringPiece key,
708 DictionaryValue** out_value);
709 // DEPRECATED, use Value::FindListKey(key) instead.
710 bool GetListWithoutPathExpansion(StringPiece key,
711 const ListValue** out_value) const;
712 // DEPRECATED, use Value::FindListKey(key) instead.
713 bool GetListWithoutPathExpansion(StringPiece key, ListValue** out_value);
715 // Removes the Value with the specified path from this dictionary (or one
716 // of its child dictionaries, if the path is more than just a local key).
717 // If |out_value| is non-NULL, the removed Value will be passed out via
718 // |out_value|. If |out_value| is NULL, the removed value will be deleted.
719 // This method returns true if |path| is a valid path; otherwise it will
720 // return false and the DictionaryValue object will be unchanged.
721 // DEPRECATED, use Value::RemovePath(path) or Value::ExtractPath(path)
723 bool Remove(StringPiece path, std::unique_ptr<Value>* out_value);
725 // Like Remove(), but without special treatment of '.'. This allows e.g. URLs
726 // to be used as paths.
727 // DEPRECATED, use Value::RemoveKey(key) or Value::ExtractKey(key) instead.
728 bool RemoveWithoutPathExpansion(StringPiece key,
729 std::unique_ptr<Value>* out_value);
731 // Removes a path, clearing out all dictionaries on |path| that remain empty
732 // after removing the value at |path|.
733 // DEPRECATED, use Value::RemovePath(path) or Value::ExtractPath(path)
735 bool RemovePath(StringPiece path, std::unique_ptr<Value>* out_value);
737 using Value::RemovePath; // DictionaryValue::RemovePath shadows otherwise.
739 // Makes a copy of |this| but doesn't include empty dictionaries and lists in
740 // the copy. This never returns NULL, even if |this| itself is empty.
741 std::unique_ptr<DictionaryValue> DeepCopyWithoutEmptyChildren() const;
743 // Swaps contents with the |other| dictionary.
744 void Swap(DictionaryValue* other);
746 // This class provides an iterator over both keys and values in the
747 // dictionary. It can't be used to modify the dictionary.
748 // DEPRECATED, use Value::DictItems() instead.
749 class BASE_EXPORT Iterator {
751 explicit Iterator(const DictionaryValue& target);
752 Iterator(const Iterator& other);
755 bool IsAtEnd() const { return it_ == target_.dict_.end(); }
756 void Advance() { ++it_; }
758 const std::string& key() const { return it_->first; }
759 const Value& value() const { return *it_->second; }
762 const DictionaryValue& target_;
763 DictStorage::const_iterator it_;
767 // DEPRECATED, use Value::DictItems() instead.
768 iterator begin() { return dict_.begin(); }
769 iterator end() { return dict_.end(); }
771 // DEPRECATED, use Value::DictItems() instead.
772 const_iterator begin() const { return dict_.begin(); }
773 const_iterator end() const { return dict_.end(); }
775 // DEPRECATED, use Value::Clone() instead.
776 // TODO(crbug.com/646113): Delete this and migrate callsites.
777 DictionaryValue* DeepCopy() const;
778 // DEPRECATED, use Value::Clone() instead.
779 // TODO(crbug.com/646113): Delete this and migrate callsites.
780 std::unique_ptr<DictionaryValue> CreateDeepCopy() const;
783 // This type of Value represents a list of other Value values.
784 class BASE_EXPORT ListValue : public Value {
786 using const_iterator = ListView::const_iterator;
787 using iterator = ListView::iterator;
789 // Returns |value| if it is a list, nullptr otherwise.
790 static std::unique_ptr<ListValue> From(std::unique_ptr<Value> value);
793 explicit ListValue(span<const Value> in_list);
794 explicit ListValue(ListStorage&& in_list) noexcept;
796 // Clears the contents of this ListValue
797 // DEPRECATED, use ClearList() instead.
800 // Returns the number of Values in this list.
801 // DEPRECATED, use GetList()::size() instead.
802 size_t GetSize() const { return list_.size(); }
804 // Returns whether the list is empty.
805 // DEPRECATED, use GetList()::empty() instead.
806 bool empty() const { return list_.empty(); }
808 // Reserves storage for at least |n| values.
809 // DEPRECATED, use GetList()::reserve() instead.
810 void Reserve(size_t n);
812 // Sets the list item at the given index to be the Value specified by
813 // the value given. If the index beyond the current end of the list, null
814 // Values will be used to pad out the list.
815 // Returns true if successful, or false if the index was negative or
816 // the value is a null pointer.
817 // DEPRECATED, use GetList()::operator[] instead.
818 bool Set(size_t index, std::unique_ptr<Value> in_value);
820 // Gets the Value at the given index. Modifies |out_value| (and returns true)
821 // only if the index falls within the current list range.
822 // Note that the list always owns the Value passed out via |out_value|.
823 // |out_value| is optional and will only be set if non-NULL.
824 // DEPRECATED, use GetList()::operator[] instead.
825 bool Get(size_t index, const Value** out_value) const;
826 bool Get(size_t index, Value** out_value);
828 // Convenience forms of Get(). Modifies |out_value| (and returns true)
829 // only if the index is valid and the Value at that index can be returned
830 // in the specified form.
831 // |out_value| is optional and will only be set if non-NULL.
832 // DEPRECATED, use GetList()::operator[]::GetBool() instead.
833 bool GetBoolean(size_t index, bool* out_value) const;
834 // DEPRECATED, use GetList()::operator[]::GetInt() instead.
835 bool GetInteger(size_t index, int* out_value) const;
836 // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as
838 // DEPRECATED, use GetList()::operator[]::GetDouble() instead.
839 bool GetDouble(size_t index, double* out_value) const;
840 // DEPRECATED, use GetList()::operator[]::GetString() instead.
841 bool GetString(size_t index, std::string* out_value) const;
842 bool GetString(size_t index, string16* out_value) const;
844 bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
845 bool GetDictionary(size_t index, DictionaryValue** out_value);
847 using Value::GetList;
848 // DEPRECATED, use GetList()::operator[]::GetList() instead.
849 bool GetList(size_t index, const ListValue** out_value) const;
850 bool GetList(size_t index, ListValue** out_value);
852 // Removes the Value with the specified index from this list.
853 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
854 // passed out via |out_value|. If |out_value| is NULL, the removed value will
855 // be deleted. This method returns true if |index| is valid; otherwise
856 // it will return false and the ListValue object will be unchanged.
857 // DEPRECATED, use GetList()::erase() instead.
858 bool Remove(size_t index, std::unique_ptr<Value>* out_value);
860 // Removes the first instance of |value| found in the list, if any, and
861 // deletes it. |index| is the location where |value| was found. Returns false
863 // DEPRECATED, use GetList()::erase() instead.
864 bool Remove(const Value& value, size_t* index);
866 // Removes the element at |iter|. If |out_value| is NULL, the value will be
867 // deleted, otherwise ownership of the value is passed back to the caller.
868 // Returns an iterator pointing to the location of the element that
869 // followed the erased element.
870 // DEPRECATED, use GetList()::erase() instead.
871 iterator Erase(iterator iter, std::unique_ptr<Value>* out_value);
874 // Appends a Value to the end of the list.
875 // DEPRECATED, use Value::Append() instead.
876 void Append(std::unique_ptr<Value> in_value);
878 // Convenience forms of Append.
879 // DEPRECATED, use Value::Append() instead.
880 void AppendBoolean(bool in_value);
881 void AppendInteger(int in_value);
882 void AppendDouble(double in_value);
883 void AppendString(StringPiece in_value);
884 void AppendString(const string16& in_value);
885 // DEPRECATED, use Value::Append() in a loop instead.
886 void AppendStrings(const std::vector<std::string>& in_values);
887 void AppendStrings(const std::vector<string16>& in_values);
889 // Appends a Value if it's not already present. Returns true if successful,
890 // or false if the value was already
891 // DEPRECATED, use std::find() with Value::Append() instead.
892 bool AppendIfNotPresent(std::unique_ptr<Value> in_value);
895 // Insert a Value at index.
896 // Returns true if successful, or false if the index was out of range.
897 // DEPRECATED, use Value::Insert() instead.
898 bool Insert(size_t index, std::unique_ptr<Value> in_value);
900 // Searches for the first instance of |value| in the list using the Equals
901 // method of the Value type.
902 // Returns a const_iterator to the found item or to end() if none exists.
903 // DEPRECATED, use std::find() instead.
904 const_iterator Find(const Value& value) const;
906 // Swaps contents with the |other| list.
907 // DEPRECATED, use GetList()::swap() instead.
908 void Swap(ListValue* other);
911 // DEPRECATED, use GetList()::begin() instead.
912 iterator begin() { return GetList().begin(); }
913 // DEPRECATED, use GetList()::end() instead.
914 iterator end() { return GetList().end(); }
916 // DEPRECATED, use GetList()::begin() instead.
917 const_iterator begin() const { return GetList().begin(); }
918 // DEPRECATED, use GetList()::end() instead.
919 const_iterator end() const { return GetList().end(); }
921 // DEPRECATED, use Value::Clone() instead.
922 // TODO(crbug.com/646113): Delete this and migrate callsites.
923 ListValue* DeepCopy() const;
924 // DEPRECATED, use Value::Clone() instead.
925 // TODO(crbug.com/646113): Delete this and migrate callsites.
926 std::unique_ptr<ListValue> CreateDeepCopy() const;
929 // This interface is implemented by classes that know how to serialize
931 class BASE_EXPORT ValueSerializer {
933 virtual ~ValueSerializer();
935 virtual bool Serialize(const Value& root) = 0;
938 // This interface is implemented by classes that know how to deserialize Value
940 class BASE_EXPORT ValueDeserializer {
942 virtual ~ValueDeserializer();
944 // This method deserializes the subclass-specific format into a Value object.
945 // If the return value is non-NULL, the caller takes ownership of returned
948 // If the return value is nullptr, and if |error_code| is non-nullptr,
949 // |*error_code| will be set to an integer value representing the underlying
950 // error. See "enum ErrorCode" below for more detail about the integer value.
952 // If |error_message| is non-nullptr, it will be filled in with a formatted
953 // error message including the location of the error if appropriate.
954 virtual std::unique_ptr<Value> Deserialize(int* error_code,
955 std::string* error_message) = 0;
957 // The integer-valued error codes form four groups:
958 // - The value 0 means no error.
959 // - Values between 1 and 999 inclusive mean an error in the data (i.e.
960 // content). The bytes being deserialized are not in the right format.
961 // - Values 1000 and above mean an error in the metadata (i.e. context). The
962 // file could not be read, the network is down, etc.
963 // - Negative values are reserved.
965 kErrorCodeNoError = 0,
966 // kErrorCodeInvalidFormat is a generic error code for "the data is not in
967 // the right format". Subclasses of ValueDeserializer may return other
968 // values for more specific errors.
969 kErrorCodeInvalidFormat = 1,
970 // kErrorCodeFirstMetadataError is the minimum value (inclusive) of the
971 // range of metadata errors.
972 kErrorCodeFirstMetadataError = 1000,
975 // The |error_code| argument can be one of the ErrorCode values, but it is
976 // not restricted to only being 0, 1 or 1000. Subclasses of ValueDeserializer
977 // can define their own error code values.
978 static inline bool ErrorCodeIsDataError(int error_code) {
979 return (kErrorCodeInvalidFormat <= error_code) &&
980 (error_code < kErrorCodeFirstMetadataError);
984 // Stream operator so Values can be used in assertion statements. In order that
985 // gtest uses this operator to print readable output on test failures, we must
986 // override each specific type. Otherwise, the default template implementation
987 // is preferred over an upcast.
988 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
990 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
991 const DictionaryValue& value) {
992 return out << static_cast<const Value&>(value);
995 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
996 const ListValue& value) {
997 return out << static_cast<const Value&>(value);
1000 // Stream operator so that enum class Types can be used in log statements.
1001 BASE_EXPORT std::ostream& operator<<(std::ostream& out,
1002 const Value::Type& type);
1006 #endif // BASE_VALUES_H_