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