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