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/value_iterators.h" 37 38 namespace base { 39 40 class DictionaryValue; 41 class ListValue; 42 class Value; 43 44 // The Value class is the base class for Values. A Value can be instantiated 45 // via passing the appropriate type or backing storage to the constructor. 46 // 47 // See the file-level comment above for more information. 48 // 49 // base::Value is currently in the process of being refactored. Design doc: 50 // https://docs.google.com/document/d/1uDLu5uTRlCWePxQUEHc8yNQdEoE1BDISYdpggWEABnw 51 // 52 // Previously (which is how most code that currently exists is written), Value 53 // used derived types to implement the individual data types, and base::Value 54 // was just a base class to refer to them. This required everything be heap 55 // allocated. 56 // 57 // OLD WAY: 58 // 59 // std::unique_ptr<base::Value> GetFoo() { 60 // std::unique_ptr<DictionaryValue> dict; 61 // dict->SetString("mykey", foo); 62 // return dict; 63 // } 64 // 65 // The new design makes base::Value a variant type that holds everything in 66 // a union. It is now recommended to pass by value with std::move rather than 67 // use heap allocated values. The DictionaryValue and ListValue subclasses 68 // exist only as a compatibility shim that we're in the process of removing. 69 // 70 // NEW WAY: 71 // 72 // base::Value GetFoo() { 73 // base::Value dict(base::Value::Type::DICTIONARY); 74 // dict.SetKey("mykey", base::Value(foo)); 75 // return dict; 76 // } 77 class Value { 78 public: 79 using BlobStorage = std::vector<char>; 80 using DictStorage = flat_map<std::string, std::unique_ptr<Value>>; 81 using ListStorage = std::vector<Value>; 82 83 enum class Type { 84 NONE = 0, 85 BOOLEAN, 86 INTEGER, 87 STRING, 88 BINARY, 89 DICTIONARY, 90 LIST 91 // Note: Do not add more types. See the file-level comment above for why. 92 }; 93 94 // For situations where you want to keep ownership of your buffer, this 95 // factory method creates a new BinaryValue by copying the contents of the 96 // buffer that's passed in. 97 // DEPRECATED, use std::make_unique<Value>(const BlobStorage&) instead. 98 // TODO(crbug.com/646113): Delete this and migrate callsites. 99 static std::unique_ptr<Value> CreateWithCopiedBuffer(const char* buffer, 100 size_t size); 101 102 // Adaptors for converting from the old way to the new way and vice versa. 103 static Value FromUniquePtrValue(std::unique_ptr<Value> val); 104 static std::unique_ptr<Value> ToUniquePtrValue(Value val); 105 106 Value(Value&& that) noexcept; 107 Value() noexcept; // A null value. 108 109 // Value's copy constructor and copy assignment operator are deleted. Use this 110 // to obtain a deep copy explicitly. 111 Value Clone() const; 112 113 explicit Value(Type type); 114 explicit Value(bool in_bool); 115 explicit Value(int in_int); 116 117 // Value(const char*) and Value(const char16_t*) are required despite 118 // Value(std::string_view) and Value(std::u16string_view) because otherwise 119 // the compiler will choose the Value(bool) constructor for these arguments. 120 // Value(std::string&&) allow for efficient move construction. 121 explicit Value(const char* in_string); 122 explicit Value(std::string_view in_string); 123 explicit Value(std::string&& in_string) noexcept; 124 explicit Value(const char16_t* in_string16); 125 explicit Value(std::u16string_view in_string16); 126 127 explicit Value(const BlobStorage& in_blob); 128 explicit Value(BlobStorage&& in_blob) noexcept; 129 130 explicit Value(const DictStorage& in_dict); 131 explicit Value(DictStorage&& in_dict) noexcept; 132 133 explicit Value(const ListStorage& in_list); 134 explicit Value(ListStorage&& in_list) noexcept; 135 136 Value& operator=(Value&& that) noexcept; 137 138 ~Value(); 139 140 // Returns the name for a given |type|. 141 static const char* GetTypeName(Type type); 142 143 // Returns the type of the value stored by the current Value object. type()144 Type type() const { return type_; } 145 146 // Returns true if the current object represents a given type. is_none()147 bool is_none() const { return type() == Type::NONE; } is_bool()148 bool is_bool() const { return type() == Type::BOOLEAN; } is_int()149 bool is_int() const { return type() == Type::INTEGER; } is_string()150 bool is_string() const { return type() == Type::STRING; } is_blob()151 bool is_blob() const { return type() == Type::BINARY; } is_dict()152 bool is_dict() const { return type() == Type::DICTIONARY; } is_list()153 bool is_list() const { return type() == Type::LIST; } 154 155 // These will all fatally assert if the type doesn't match. 156 bool GetBool() const; 157 int GetInt() const; 158 const std::string& GetString() const; 159 const BlobStorage& GetBlob() const; 160 161 ListStorage& GetList(); 162 const ListStorage& GetList() const; 163 164 // |FindKey| looks up |key| in the underlying dictionary. If found, it returns 165 // a pointer to the element. Otherwise it returns nullptr. 166 // returned. Callers are expected to perform a check against null before using 167 // the pointer. 168 // Note: This fatally asserts if type() is not Type::DICTIONARY. 169 // 170 // Example: 171 // auto* found = FindKey("foo"); 172 Value* FindKey(std::string_view key); 173 const Value* FindKey(std::string_view key) const; 174 175 // |FindKeyOfType| is similar to |FindKey|, but it also requires the found 176 // value to have type |type|. If no type is found, or the found value is of a 177 // different type nullptr is returned. 178 // Callers are expected to perform a check against null before using the 179 // pointer. 180 // Note: This fatally asserts if type() is not Type::DICTIONARY. 181 // 182 // Example: 183 // auto* found = FindKey("foo", Type::INTEGER); 184 Value* FindKeyOfType(std::string_view key, Type type); 185 const Value* FindKeyOfType(std::string_view key, Type type) const; 186 187 // |SetKey| looks up |key| in the underlying dictionary and sets the mapped 188 // value to |value|. If |key| could not be found, a new element is inserted. 189 // A pointer to the modified item is returned. 190 // Note: This fatally asserts if type() is not Type::DICTIONARY. 191 // 192 // Example: 193 // SetKey("foo", std::move(myvalue)); 194 Value* SetKey(std::string_view key, Value value); 195 // This overload results in a performance improvement for std::string&&. 196 Value* SetKey(std::string&& key, Value value); 197 // This overload is necessary to avoid ambiguity for const char* arguments. 198 Value* SetKey(const char* key, Value value); 199 200 // This attempts to remove the value associated with |key|. In case of 201 // failure, e.g. the key does not exist, |false| is returned and the 202 // underlying dictionary is not changed. In case of success, |key| is deleted 203 // from the dictionary and the method returns |true|. Note: This fatally 204 // asserts if type() is not Type::DICTIONARY. 205 // 206 // Example: 207 // bool success = RemoveKey("foo"); 208 bool RemoveKey(std::string_view key); 209 210 // Searches a hierarchy of dictionary values for a given value. If a path 211 // of dictionaries exist, returns the item at that path. If any of the path 212 // components do not exist or if any but the last path components are not 213 // dictionaries, returns nullptr. 214 // 215 // The type of the leaf Value is not checked. 216 // 217 // Implementation note: This can't return an iterator because the iterator 218 // will actually be into another Value, so it can't be compared to iterators 219 // from this one (in particular, the DictItems().end() iterator). 220 // 221 // Example: 222 // auto* found = FindPath({"foo", "bar"}); 223 // 224 // std::vector<std::string_view> components = ... 225 // auto* found = FindPath(components); 226 // 227 // Note: If there is only one component in the path, use FindKey() instead. 228 Value* FindPath(std::initializer_list<std::string_view> path); 229 Value* FindPath(span<const std::string_view> path); 230 const Value* FindPath(std::initializer_list<std::string_view> path) const; 231 const Value* FindPath(span<const std::string_view> path) const; 232 233 // Like FindPath() but will only return the value if the leaf Value type 234 // matches the given type. Will return nullptr otherwise. 235 // 236 // Note: If there is only one component in the path, use FindKeyOfType() 237 // instead. 238 Value* FindPathOfType(std::initializer_list<std::string_view> path, 239 Type type); 240 Value* FindPathOfType(span<const std::string_view> path, Type type); 241 const Value* FindPathOfType(std::initializer_list<std::string_view> path, 242 Type type) const; 243 const Value* FindPathOfType(span<const std::string_view> path, 244 Type type) const; 245 246 // Sets the given path, expanding and creating dictionary keys as necessary. 247 // 248 // If the current value is not a dictionary, the function returns nullptr. If 249 // path components do not exist, they will be created. If any but the last 250 // components matches a value that is not a dictionary, the function will fail 251 // (it will not overwrite the value) and return nullptr. The last path 252 // component will be unconditionally overwritten if it exists, and created if 253 // it doesn't. 254 // 255 // Example: 256 // value.SetPath({"foo", "bar"}, std::move(myvalue)); 257 // 258 // std::vector<std::string_view> components = ... 259 // value.SetPath(components, std::move(myvalue)); 260 // 261 // Note: If there is only one component in the path, use SetKey() instead. 262 Value* SetPath(std::initializer_list<std::string_view> path, Value value); 263 Value* SetPath(span<const std::string_view> path, Value value); 264 265 // Tries to remove a Value at the given path. 266 // 267 // If the current value is not a dictionary or any path components does not 268 // exist, this operation fails, leaves underlying Values untouched and returns 269 // |false|. In case intermediate dictionaries become empty as a result of this 270 // path removal, they will be removed as well. 271 // 272 // Example: 273 // bool success = value.RemovePath({"foo", "bar"}); 274 // 275 // std::vector<std::string_view> components = ... 276 // bool success = value.RemovePath(components); 277 // 278 // Note: If there is only one component in the path, use RemoveKey() instead. 279 bool RemovePath(std::initializer_list<std::string_view> path); 280 bool RemovePath(span<const std::string_view> path); 281 282 using dict_iterator_proxy = detail::dict_iterator_proxy; 283 using const_dict_iterator_proxy = detail::const_dict_iterator_proxy; 284 285 // |DictItems| returns a proxy object that exposes iterators to the underlying 286 // dictionary. These are intended for iteration over all items in the 287 // dictionary and are compatible with for-each loops and standard library 288 // algorithms. 289 // Note: This fatally asserts if type() is not Type::DICTIONARY. 290 dict_iterator_proxy DictItems(); 291 const_dict_iterator_proxy DictItems() const; 292 293 // Returns the size of the dictionary, and if the dictionary is empty. 294 // Note: This fatally asserts if type() is not Type::DICTIONARY. 295 size_t DictSize() const; 296 bool DictEmpty() const; 297 298 // These methods allow the convenient retrieval of the contents of the Value. 299 // If the current object can be converted into the given type, the value is 300 // returned through the |out_value| parameter and true is returned; 301 // otherwise, false is returned and |out_value| is unchanged. 302 // DEPRECATED, use GetBool() instead. 303 bool GetAsBoolean(bool* out_value) const; 304 // DEPRECATED, use GetInt() instead. 305 bool GetAsInteger(int* out_value) const; 306 // DEPRECATED, use GetString() instead. 307 bool GetAsString(std::string* out_value) const; 308 bool GetAsString(std::u16string* out_value) const; 309 bool GetAsString(const Value** out_value) const; 310 bool GetAsString(std::string_view* out_value) const; 311 // ListValue::From is the equivalent for std::unique_ptr conversions. 312 // DEPRECATED, use GetList() instead. 313 bool GetAsList(ListValue** out_value); 314 bool GetAsList(const ListValue** out_value) const; 315 // DictionaryValue::From is the equivalent for std::unique_ptr conversions. 316 bool GetAsDictionary(DictionaryValue** out_value); 317 bool GetAsDictionary(const DictionaryValue** out_value) const; 318 // Note: Do not add more types. See the file-level comment above for why. 319 320 // This creates a deep copy of the entire Value tree, and returns a pointer 321 // to the copy. The caller gets ownership of the copy, of course. 322 // Subclasses return their own type directly in their overrides; 323 // this works because C++ supports covariant return types. 324 // DEPRECATED, use Value::Clone() instead. 325 // TODO(crbug.com/646113): Delete this and migrate callsites. 326 Value* DeepCopy() const; 327 // DEPRECATED, use Value::Clone() instead. 328 // TODO(crbug.com/646113): Delete this and migrate callsites. 329 std::unique_ptr<Value> CreateDeepCopy() const; 330 331 // Comparison operators so that Values can easily be used with standard 332 // library algorithms and associative containers. 333 friend bool operator==(const Value& lhs, const Value& rhs); 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 340 // Compares if two Value objects have equal contents. 341 // DEPRECATED, use operator==(const Value& lhs, const Value& rhs) instead. 342 // TODO(crbug.com/646113): Delete this and migrate callsites. 343 bool Equals(const Value* other) const; 344 345 // Estimates dynamic memory usage. 346 // See base/trace_event/memory_usage_estimator.h for more info. 347 size_t EstimateMemoryUsage() const; 348 349 protected: 350 // TODO(crbug.com/646113): Make these private once DictionaryValue and 351 // ListValue are properly inlined. 352 Type type_; 353 354 union { 355 bool bool_value_; 356 int int_value_; 357 std::string string_value_; 358 BlobStorage binary_value_; 359 DictStorage dict_; 360 ListStorage list_; 361 }; 362 363 private: 364 void InternalMoveConstructFrom(Value&& that); 365 void InternalCleanup(); 366 367 Value(const Value&) = delete; 368 Value& operator=(const Value&) = delete; 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