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