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