1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 // This file specifies a recursive data storage class called Value intended for 6 // storing settings and other persistable data. 7 // 8 // A Value represents something that can be stored in JSON or passed to/from 9 // JavaScript. As such, it is NOT a generalized variant type, since only the 10 // types supported by JavaScript/JSON are supported. 11 // 12 // IN PARTICULAR this means that there is no support for int64_t or unsigned 13 // numbers. Writing JSON with such types would violate the spec. If you need 14 // something like this, either use a double or make a string value containing 15 // the number you want. 16 17 #ifndef BASE_VALUES_H_ 18 #define BASE_VALUES_H_ 19 20 #include <stddef.h> 21 #include <stdint.h> 22 23 #include <iosfwd> 24 #include <map> 25 #include <memory> 26 #include <string> 27 #include <utility> 28 #include <vector> 29 30 #include "base/base_export.h" 31 #include "base/compiler_specific.h" 32 #include "base/macros.h" 33 #include "base/memory/manual_constructor.h" 34 #include "base/strings/string16.h" 35 #include "base/strings/string_piece.h" 36 37 namespace base { 38 39 class DictionaryValue; 40 class ListValue; 41 class Value; 42 using BinaryValue = Value; 43 44 // The Value class is the base class for Values. A Value can be instantiated 45 // via the Create*Value() factory methods, or by directly creating instances of 46 // the subclasses. 47 // 48 // See the file-level comment above for more information. 49 class BASE_EXPORT Value { 50 public: 51 using DictStorage = std::map<std::string, std::unique_ptr<Value>>; 52 using ListStorage = std::vector<std::unique_ptr<Value>>; 53 54 enum class Type { 55 NONE = 0, 56 BOOLEAN, 57 INTEGER, 58 DOUBLE, 59 STRING, 60 BINARY, 61 DICTIONARY, 62 LIST 63 // Note: Do not add more types. See the file-level comment above for why. 64 }; 65 66 static std::unique_ptr<Value> CreateNullValue(); 67 68 // For situations where you want to keep ownership of your buffer, this 69 // factory method creates a new BinaryValue by copying the contents of the 70 // buffer that's passed in. 71 // DEPRECATED, use MakeUnique<Value>(const std::vector<char>&) instead. 72 // TODO(crbug.com/646113): Delete this and migrate callsites. 73 static std::unique_ptr<BinaryValue> CreateWithCopiedBuffer(const char* buffer, 74 size_t size); 75 76 Value(const Value& that); 77 Value(Value&& that) noexcept; 78 Value() noexcept; // A null value. 79 explicit Value(Type type); 80 explicit Value(bool in_bool); 81 explicit Value(int in_int); 82 explicit Value(double in_double); 83 84 // Value(const char*) and Value(const char16*) are required despite 85 // Value(const std::string&) and Value(const string16&) because otherwise the 86 // compiler will choose the Value(bool) constructor for these arguments. 87 // Value(std::string&&) allow for efficient move construction. 88 // Value(StringPiece) exists due to many callsites passing StringPieces as 89 // arguments. 90 explicit Value(const char* in_string); 91 explicit Value(const std::string& in_string); 92 explicit Value(std::string&& in_string) noexcept; 93 explicit Value(const char16* in_string); 94 explicit Value(const string16& in_string); 95 explicit Value(StringPiece in_string); 96 97 explicit Value(const std::vector<char>& in_blob); 98 explicit Value(std::vector<char>&& in_blob) noexcept; 99 100 Value& operator=(const Value& that); 101 Value& operator=(Value&& that) noexcept; 102 103 ~Value(); 104 105 // Returns the name for a given |type|. 106 static const char* GetTypeName(Type type); 107 108 // Returns the type of the value stored by the current Value object. 109 // Each type will be implemented by only one subclass of Value, so it's 110 // safe to use the Type to determine whether you can cast from 111 // Value* to (Implementing Class)*. Also, a Value object never changes 112 // its type after construction. 113 Type GetType() const { return type_; } // DEPRECATED, use type(). 114 Type type() const { return type_; } 115 116 // Returns true if the current object represents a given type. 117 bool IsType(Type type) const { return type == type_; } 118 bool is_bool() const { return type() == Type::BOOLEAN; } 119 bool is_int() const { return type() == Type::INTEGER; } 120 bool is_double() const { return type() == Type::DOUBLE; } 121 bool is_string() const { return type() == Type::STRING; } 122 bool is_blob() const { return type() == Type::BINARY; } 123 bool is_dict() const { return type() == Type::DICTIONARY; } 124 bool is_list() const { return type() == Type::LIST; } 125 126 // These will all fatally assert if the type doesn't match. 127 bool GetBool() const; 128 int GetInt() const; 129 double GetDouble() const; // Implicitly converts from int if necessary. 130 const std::string& GetString() const; 131 const std::vector<char>& GetBlob() const; 132 133 size_t GetSize() const; // DEPRECATED, use GetBlob().size() instead. 134 const char* GetBuffer() const; // DEPRECATED, use GetBlob().data() instead. 135 136 // These methods allow the convenient retrieval of the contents of the Value. 137 // If the current object can be converted into the given type, the value is 138 // returned through the |out_value| parameter and true is returned; 139 // otherwise, false is returned and |out_value| is unchanged. 140 bool GetAsBoolean(bool* out_value) const; 141 bool GetAsInteger(int* out_value) const; 142 bool GetAsDouble(double* out_value) const; 143 bool GetAsString(std::string* out_value) const; 144 bool GetAsString(string16* out_value) const; 145 bool GetAsString(const Value** out_value) const; 146 bool GetAsString(StringPiece* out_value) const; 147 bool GetAsBinary(const BinaryValue** out_value) const; 148 // ListValue::From is the equivalent for std::unique_ptr conversions. 149 bool GetAsList(ListValue** out_value); 150 bool GetAsList(const ListValue** out_value) const; 151 // DictionaryValue::From is the equivalent for std::unique_ptr conversions. 152 bool GetAsDictionary(DictionaryValue** out_value); 153 bool GetAsDictionary(const DictionaryValue** out_value) const; 154 // Note: Do not add more types. See the file-level comment above for why. 155 156 // This creates a deep copy of the entire Value tree, and returns a pointer 157 // to the copy. The caller gets ownership of the copy, of course. 158 // Subclasses return their own type directly in their overrides; 159 // this works because C++ supports covariant return types. 160 // DEPRECATED, use Value's copy constructor instead. 161 // TODO(crbug.com/646113): Delete this and migrate callsites. 162 Value* DeepCopy() const; 163 // Preferred version of DeepCopy. TODO(estade): remove the above. 164 std::unique_ptr<Value> CreateDeepCopy() const; 165 166 // Comparison operators so that Values can easily be used with standard 167 // library algorithms and associative containers. 168 BASE_EXPORT friend bool operator==(const Value& lhs, const Value& rhs); 169 BASE_EXPORT friend bool operator!=(const Value& lhs, const Value& rhs); 170 BASE_EXPORT friend bool operator<(const Value& lhs, const Value& rhs); 171 BASE_EXPORT friend bool operator>(const Value& lhs, const Value& rhs); 172 BASE_EXPORT friend bool operator<=(const Value& lhs, const Value& rhs); 173 BASE_EXPORT friend bool operator>=(const Value& lhs, const Value& rhs); 174 175 // Compares if two Value objects have equal contents. 176 // DEPRECATED, use operator==(const Value& lhs, const Value& rhs) instead. 177 // TODO(crbug.com/646113): Delete this and migrate callsites. 178 bool Equals(const Value* other) const; 179 180 // Compares if two Value objects have equal contents. Can handle NULLs. 181 // NULLs are considered equal but different from Value::CreateNullValue(). 182 // DEPRECATED, use operator==(const Value& lhs, const Value& rhs) instead. 183 // TODO(crbug.com/646113): Delete this and migrate callsites. 184 static bool Equals(const Value* a, const Value* b); 185 186 protected: 187 // TODO(crbug.com/646113): Make these private once DictionaryValue and 188 // ListValue are properly inlined. 189 Type type_; 190 191 union { 192 bool bool_value_; 193 int int_value_; 194 double double_value_; 195 ManualConstructor<std::string> string_value_; 196 ManualConstructor<std::vector<char>> binary_value_; 197 // For current gcc and clang sizeof(DictStorage) = 48, which would result 198 // in sizeof(Value) = 56 if DictStorage was stack allocated. Allocating it 199 // on the heap results in sizeof(Value) = 40 for all of gcc, clang and MSVC. 200 ManualConstructor<std::unique_ptr<DictStorage>> dict_ptr_; 201 ManualConstructor<ListStorage> list_; 202 }; 203 204 private: 205 void InternalCopyFundamentalValue(const Value& that); 206 void InternalCopyConstructFrom(const Value& that); 207 void InternalMoveConstructFrom(Value&& that); 208 void InternalCopyAssignFromSameType(const Value& that); 209 void InternalCleanup(); 210 }; 211 212 // DictionaryValue provides a key-value dictionary with (optional) "path" 213 // parsing for recursive access; see the comment at the top of the file. Keys 214 // are |std::string|s and should be UTF-8 encoded. 215 class BASE_EXPORT DictionaryValue : public Value { 216 public: 217 // Returns |value| if it is a dictionary, nullptr otherwise. 218 static std::unique_ptr<DictionaryValue> From(std::unique_ptr<Value> value); 219 220 DictionaryValue(); 221 222 // Returns true if the current dictionary has a value for the given key. 223 bool HasKey(StringPiece key) const; 224 225 // Returns the number of Values in this dictionary. 226 size_t size() const { return (*dict_ptr_)->size(); } 227 228 // Returns whether the dictionary is empty. 229 bool empty() const { return (*dict_ptr_)->empty(); } 230 231 // Clears any current contents of this dictionary. 232 void Clear(); 233 234 // Sets the Value associated with the given path starting from this object. 235 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes 236 // into the next DictionaryValue down. Obviously, "." can't be used 237 // within a key, but there are no other restrictions on keys. 238 // If the key at any step of the way doesn't exist, or exists but isn't 239 // a DictionaryValue, a new DictionaryValue will be created and attached 240 // to the path in that location. |in_value| must be non-null. 241 void Set(StringPiece path, std::unique_ptr<Value> in_value); 242 // Deprecated version of the above. TODO(estade): remove. 243 void Set(StringPiece path, Value* in_value); 244 245 // Convenience forms of Set(). These methods will replace any existing 246 // value at that path, even if it has a different type. 247 void SetBoolean(StringPiece path, bool in_value); 248 void SetInteger(StringPiece path, int in_value); 249 void SetDouble(StringPiece path, double in_value); 250 void SetString(StringPiece path, StringPiece in_value); 251 void SetString(StringPiece path, const string16& in_value); 252 253 // Like Set(), but without special treatment of '.'. This allows e.g. URLs to 254 // be used as paths. 255 void SetWithoutPathExpansion(StringPiece key, 256 std::unique_ptr<Value> in_value); 257 // Deprecated version of the above. TODO(estade): remove. 258 void SetWithoutPathExpansion(StringPiece key, Value* in_value); 259 260 // Convenience forms of SetWithoutPathExpansion(). 261 void SetBooleanWithoutPathExpansion(StringPiece path, bool in_value); 262 void SetIntegerWithoutPathExpansion(StringPiece path, int in_value); 263 void SetDoubleWithoutPathExpansion(StringPiece path, double in_value); 264 void SetStringWithoutPathExpansion(StringPiece path, StringPiece in_value); 265 void SetStringWithoutPathExpansion(StringPiece path, 266 const string16& in_value); 267 268 // Gets the Value associated with the given path starting from this object. 269 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes 270 // into the next DictionaryValue down. If the path can be resolved 271 // successfully, the value for the last key in the path will be returned 272 // through the |out_value| parameter, and the function will return true. 273 // Otherwise, it will return false and |out_value| will be untouched. 274 // Note that the dictionary always owns the value that's returned. 275 // |out_value| is optional and will only be set if non-NULL. 276 bool Get(StringPiece path, const Value** out_value) const; 277 bool Get(StringPiece path, Value** out_value); 278 279 // These are convenience forms of Get(). The value will be retrieved 280 // and the return value will be true if the path is valid and the value at 281 // the end of the path can be returned in the form specified. 282 // |out_value| is optional and will only be set if non-NULL. 283 bool GetBoolean(StringPiece path, bool* out_value) const; 284 bool GetInteger(StringPiece path, int* out_value) const; 285 // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as 286 // doubles. 287 bool GetDouble(StringPiece path, double* out_value) const; 288 bool GetString(StringPiece path, std::string* out_value) const; 289 bool GetString(StringPiece path, string16* out_value) const; 290 bool GetStringASCII(StringPiece path, std::string* out_value) const; 291 bool GetBinary(StringPiece path, const BinaryValue** out_value) const; 292 bool GetBinary(StringPiece path, BinaryValue** out_value); 293 bool GetDictionary(StringPiece path, 294 const DictionaryValue** out_value) const; 295 bool GetDictionary(StringPiece path, DictionaryValue** out_value); 296 bool GetList(StringPiece path, const ListValue** out_value) const; 297 bool GetList(StringPiece path, ListValue** out_value); 298 299 // Like Get(), but without special treatment of '.'. This allows e.g. URLs to 300 // be used as paths. 301 bool GetWithoutPathExpansion(StringPiece key, const Value** out_value) const; 302 bool GetWithoutPathExpansion(StringPiece key, Value** out_value); 303 bool GetBooleanWithoutPathExpansion(StringPiece key, bool* out_value) const; 304 bool GetIntegerWithoutPathExpansion(StringPiece key, int* out_value) const; 305 bool GetDoubleWithoutPathExpansion(StringPiece key, double* out_value) const; 306 bool GetStringWithoutPathExpansion(StringPiece key, 307 std::string* out_value) const; 308 bool GetStringWithoutPathExpansion(StringPiece key, 309 string16* out_value) const; 310 bool GetDictionaryWithoutPathExpansion( 311 StringPiece key, 312 const DictionaryValue** out_value) const; 313 bool GetDictionaryWithoutPathExpansion(StringPiece key, 314 DictionaryValue** out_value); 315 bool GetListWithoutPathExpansion(StringPiece key, 316 const ListValue** out_value) const; 317 bool GetListWithoutPathExpansion(StringPiece key, ListValue** out_value); 318 319 // Removes the Value with the specified path from this dictionary (or one 320 // of its child dictionaries, if the path is more than just a local key). 321 // If |out_value| is non-NULL, the removed Value will be passed out via 322 // |out_value|. If |out_value| is NULL, the removed value will be deleted. 323 // This method returns true if |path| is a valid path; otherwise it will 324 // return false and the DictionaryValue object will be unchanged. 325 bool Remove(StringPiece path, std::unique_ptr<Value>* out_value); 326 327 // Like Remove(), but without special treatment of '.'. This allows e.g. URLs 328 // to be used as paths. 329 bool RemoveWithoutPathExpansion(StringPiece key, 330 std::unique_ptr<Value>* out_value); 331 332 // Removes a path, clearing out all dictionaries on |path| that remain empty 333 // after removing the value at |path|. 334 bool RemovePath(StringPiece path, std::unique_ptr<Value>* out_value); 335 336 // Makes a copy of |this| but doesn't include empty dictionaries and lists in 337 // the copy. This never returns NULL, even if |this| itself is empty. 338 std::unique_ptr<DictionaryValue> DeepCopyWithoutEmptyChildren() const; 339 340 // Merge |dictionary| into this dictionary. This is done recursively, i.e. any 341 // sub-dictionaries will be merged as well. In case of key collisions, the 342 // passed in dictionary takes precedence and data already present will be 343 // replaced. Values within |dictionary| are deep-copied, so |dictionary| may 344 // be freed any time after this call. 345 void MergeDictionary(const DictionaryValue* dictionary); 346 347 // Swaps contents with the |other| dictionary. 348 void Swap(DictionaryValue* other); 349 350 // This class provides an iterator over both keys and values in the 351 // dictionary. It can't be used to modify the dictionary. 352 class BASE_EXPORT Iterator { 353 public: 354 explicit Iterator(const DictionaryValue& target); 355 Iterator(const Iterator& other); 356 ~Iterator(); 357 358 bool IsAtEnd() const { return it_ == (*target_.dict_ptr_)->end(); } 359 void Advance() { ++it_; } 360 361 const std::string& key() const { return it_->first; } 362 const Value& value() const { return *it_->second; } 363 364 private: 365 const DictionaryValue& target_; 366 DictStorage::const_iterator it_; 367 }; 368 369 // DEPRECATED, use DictionaryValue's copy constructor instead. 370 // TODO(crbug.com/646113): Delete this and migrate callsites. 371 DictionaryValue* DeepCopy() const; 372 // Preferred version of DeepCopy. TODO(estade): remove the above. 373 std::unique_ptr<DictionaryValue> CreateDeepCopy() const; 374 }; 375 376 // This type of Value represents a list of other Value values. 377 class BASE_EXPORT ListValue : public Value { 378 public: 379 using const_iterator = ListStorage::const_iterator; 380 using iterator = ListStorage::iterator; 381 382 // Returns |value| if it is a list, nullptr otherwise. 383 static std::unique_ptr<ListValue> From(std::unique_ptr<Value> value); 384 385 ListValue(); 386 387 // Clears the contents of this ListValue 388 void Clear(); 389 390 // Returns the number of Values in this list. 391 size_t GetSize() const { return list_->size(); } 392 393 // Returns whether the list is empty. 394 bool empty() const { return list_->empty(); } 395 396 // Sets the list item at the given index to be the Value specified by 397 // the value given. If the index beyond the current end of the list, null 398 // Values will be used to pad out the list. 399 // Returns true if successful, or false if the index was negative or 400 // the value is a null pointer. 401 bool Set(size_t index, Value* in_value); 402 // Preferred version of the above. TODO(estade): remove the above. 403 bool Set(size_t index, std::unique_ptr<Value> in_value); 404 405 // Gets the Value at the given index. Modifies |out_value| (and returns true) 406 // only if the index falls within the current list range. 407 // Note that the list always owns the Value passed out via |out_value|. 408 // |out_value| is optional and will only be set if non-NULL. 409 bool Get(size_t index, const Value** out_value) const; 410 bool Get(size_t index, Value** out_value); 411 412 // Convenience forms of Get(). Modifies |out_value| (and returns true) 413 // only if the index is valid and the Value at that index can be returned 414 // in the specified form. 415 // |out_value| is optional and will only be set if non-NULL. 416 bool GetBoolean(size_t index, bool* out_value) const; 417 bool GetInteger(size_t index, int* out_value) const; 418 // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as 419 // doubles. 420 bool GetDouble(size_t index, double* out_value) const; 421 bool GetString(size_t index, std::string* out_value) const; 422 bool GetString(size_t index, string16* out_value) const; 423 bool GetBinary(size_t index, const BinaryValue** out_value) const; 424 bool GetBinary(size_t index, BinaryValue** out_value); 425 bool GetDictionary(size_t index, const DictionaryValue** out_value) const; 426 bool GetDictionary(size_t index, DictionaryValue** out_value); 427 bool GetList(size_t index, const ListValue** out_value) const; 428 bool GetList(size_t index, ListValue** out_value); 429 430 // Removes the Value with the specified index from this list. 431 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be 432 // passed out via |out_value|. If |out_value| is NULL, the removed value will 433 // be deleted. This method returns true if |index| is valid; otherwise 434 // it will return false and the ListValue object will be unchanged. 435 bool Remove(size_t index, std::unique_ptr<Value>* out_value); 436 437 // Removes the first instance of |value| found in the list, if any, and 438 // deletes it. |index| is the location where |value| was found. Returns false 439 // if not found. 440 bool Remove(const Value& value, size_t* index); 441 442 // Removes the element at |iter|. If |out_value| is NULL, the value will be 443 // deleted, otherwise ownership of the value is passed back to the caller. 444 // Returns an iterator pointing to the location of the element that 445 // followed the erased element. 446 iterator Erase(iterator iter, std::unique_ptr<Value>* out_value); 447 448 // Appends a Value to the end of the list. 449 void Append(std::unique_ptr<Value> in_value); 450 #if !defined(OS_LINUX) 451 // Deprecated version of the above. TODO(estade): remove. 452 void Append(Value* in_value); 453 #endif 454 455 // Convenience forms of Append. 456 void AppendBoolean(bool in_value); 457 void AppendInteger(int in_value); 458 void AppendDouble(double in_value); 459 void AppendString(StringPiece in_value); 460 void AppendString(const string16& in_value); 461 void AppendStrings(const std::vector<std::string>& in_values); 462 void AppendStrings(const std::vector<string16>& in_values); 463 464 // Appends a Value if it's not already present. Returns true if successful, 465 // or false if the value was already 466 bool AppendIfNotPresent(std::unique_ptr<Value> in_value); 467 468 // Insert a Value at index. 469 // Returns true if successful, or false if the index was out of range. 470 bool Insert(size_t index, std::unique_ptr<Value> in_value); 471 472 // Searches for the first instance of |value| in the list using the Equals 473 // method of the Value type. 474 // Returns a const_iterator to the found item or to end() if none exists. 475 const_iterator Find(const Value& value) const; 476 477 // Swaps contents with the |other| list. 478 void Swap(ListValue* other); 479 480 // Iteration. 481 iterator begin() { return list_->begin(); } 482 iterator end() { return list_->end(); } 483 484 const_iterator begin() const { return list_->begin(); } 485 const_iterator end() const { return list_->end(); } 486 487 // DEPRECATED, use ListValue's copy constructor instead. 488 // TODO(crbug.com/646113): Delete this and migrate callsites. 489 ListValue* DeepCopy() const; 490 // Preferred version of DeepCopy. TODO(estade): remove DeepCopy. 491 std::unique_ptr<ListValue> CreateDeepCopy() const; 492 }; 493 494 // This interface is implemented by classes that know how to serialize 495 // Value objects. 496 class BASE_EXPORT ValueSerializer { 497 public: 498 virtual ~ValueSerializer(); 499 500 virtual bool Serialize(const Value& root) = 0; 501 }; 502 503 // This interface is implemented by classes that know how to deserialize Value 504 // objects. 505 class BASE_EXPORT ValueDeserializer { 506 public: 507 virtual ~ValueDeserializer(); 508 509 // This method deserializes the subclass-specific format into a Value object. 510 // If the return value is non-NULL, the caller takes ownership of returned 511 // Value. If the return value is NULL, and if error_code is non-NULL, 512 // error_code will be set with the underlying error. 513 // If |error_message| is non-null, it will be filled in with a formatted 514 // error message including the location of the error if appropriate. 515 virtual std::unique_ptr<Value> Deserialize(int* error_code, 516 std::string* error_str) = 0; 517 }; 518 519 // Stream operator so Values can be used in assertion statements. In order that 520 // gtest uses this operator to print readable output on test failures, we must 521 // override each specific type. Otherwise, the default template implementation 522 // is preferred over an upcast. 523 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value); 524 525 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out, 526 const DictionaryValue& value) { 527 return out << static_cast<const Value&>(value); 528 } 529 530 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out, 531 const ListValue& value) { 532 return out << static_cast<const Value&>(value); 533 } 534 535 // Stream operator so that enum class Types can be used in log statements. 536 BASE_EXPORT std::ostream& operator<<(std::ostream& out, 537 const Value::Type& type); 538 539 } // namespace base 540 541 #endif // BASE_VALUES_H_ 542