values.h revision 21d179b334e59e9a3bfcaed4c4430bef1bc5759d
1// Copyright (c) 2010 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 setting and other persistable data. It includes the ability to 7// specify (recursive) lists and dictionaries, so it's fairly expressive. 8// However, the API is optimized for the common case, namely storing a 9// hierarchical tree of simple values. Given a DictionaryValue root, you can 10// easily do things like: 11// 12// root->SetString("global.pages.homepage", "http://goateleporter.com"); 13// std::string homepage = "http://google.com"; // default/fallback value 14// root->GetString("global.pages.homepage", &homepage); 15// 16// where "global" and "pages" are also DictionaryValues, and "homepage" is a 17// string setting. If some elements of the path didn't exist yet, the 18// SetString() method would create the missing elements and attach them to root 19// before attaching the homepage value. 20 21#ifndef BASE_VALUES_H_ 22#define BASE_VALUES_H_ 23#pragma once 24 25#include <iterator> 26#include <map> 27#include <string> 28#include <vector> 29 30#include "base/basictypes.h" 31#include "base/string16.h" 32#include "build/build_config.h" 33 34class Value; 35class FundamentalValue; 36class StringValue; 37class BinaryValue; 38class DictionaryValue; 39class ListValue; 40 41typedef std::vector<Value*> ValueVector; 42typedef std::map<std::string, Value*> ValueMap; 43 44// The Value class is the base class for Values. A Value can be 45// instantiated via the Create*Value() factory methods, or by directly 46// creating instances of the subclasses. 47class Value { 48 public: 49 virtual ~Value(); 50 51 // Convenience methods for creating Value objects for various 52 // kinds of values without thinking about which class implements them. 53 // These can always be expected to return a valid Value*. 54 static Value* CreateNullValue(); 55 static Value* CreateBooleanValue(bool in_value); 56 static Value* CreateIntegerValue(int in_value); 57 static Value* CreateRealValue(double in_value); 58 static Value* CreateStringValue(const std::string& in_value); 59 static Value* CreateStringValue(const string16& in_value); 60 61 // This one can return NULL if the input isn't valid. If the return value 62 // is non-null, the new object has taken ownership of the buffer pointer. 63 static BinaryValue* CreateBinaryValue(char* buffer, size_t size); 64 65 typedef enum { 66 TYPE_NULL = 0, 67 TYPE_BOOLEAN, 68 TYPE_INTEGER, 69 TYPE_REAL, 70 TYPE_STRING, 71 TYPE_BINARY, 72 TYPE_DICTIONARY, 73 TYPE_LIST 74 } ValueType; 75 76 // Returns the type of the value stored by the current Value object. 77 // Each type will be implemented by only one subclass of Value, so it's 78 // safe to use the ValueType to determine whether you can cast from 79 // Value* to (Implementing Class)*. Also, a Value object never changes 80 // its type after construction. 81 ValueType GetType() const { return type_; } 82 83 // Returns true if the current object represents a given type. 84 bool IsType(ValueType type) const { return type == type_; } 85 86 // These methods allow the convenient retrieval of settings. 87 // If the current setting object can be converted into the given type, 88 // the value is returned through the |out_value| parameter and true is 89 // returned; otherwise, false is returned and |out_value| is unchanged. 90 virtual bool GetAsBoolean(bool* out_value) const; 91 virtual bool GetAsInteger(int* out_value) const; 92 virtual bool GetAsReal(double* out_value) const; 93 virtual bool GetAsString(std::string* out_value) const; 94 virtual bool GetAsString(string16* out_value) const; 95 virtual bool GetAsList(ListValue** out_value); 96 97 // This creates a deep copy of the entire Value tree, and returns a pointer 98 // to the copy. The caller gets ownership of the copy, of course. 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 // This isn't safe for end-users (they should use the Create*Value() 110 // static methods above), but it's useful for subclasses. 111 explicit Value(ValueType type); 112 113 private: 114 Value(); 115 116 ValueType type_; 117 118 DISALLOW_COPY_AND_ASSIGN(Value); 119}; 120 121// FundamentalValue represents the simple fundamental types of values. 122class FundamentalValue : public Value { 123 public: 124 explicit FundamentalValue(bool in_value); 125 explicit FundamentalValue(int in_value); 126 explicit FundamentalValue(double in_value); 127 virtual ~FundamentalValue(); 128 129 // Subclassed methods 130 virtual bool GetAsBoolean(bool* out_value) const; 131 virtual bool GetAsInteger(int* out_value) const; 132 virtual bool GetAsReal(double* out_value) const; 133 virtual Value* DeepCopy() const; 134 virtual bool Equals(const Value* other) const; 135 136 private: 137 union { 138 bool boolean_value_; 139 int integer_value_; 140 double real_value_; 141 }; 142 143 DISALLOW_COPY_AND_ASSIGN(FundamentalValue); 144}; 145 146class StringValue : public Value { 147 public: 148 // Initializes a StringValue with a UTF-8 narrow character string. 149 explicit StringValue(const std::string& in_value); 150 151 // Initializes a StringValue with a string16. 152 explicit StringValue(const string16& in_value); 153 154 virtual ~StringValue(); 155 156 // Subclassed methods 157 virtual bool GetAsString(std::string* out_value) const; 158 virtual bool GetAsString(string16* out_value) const; 159 virtual Value* DeepCopy() const; 160 virtual bool Equals(const Value* other) const; 161 162 private: 163 std::string value_; 164 165 DISALLOW_COPY_AND_ASSIGN(StringValue); 166}; 167 168class BinaryValue: public Value { 169 public: 170 // Creates a Value to represent a binary buffer. The new object takes 171 // ownership of the pointer passed in, if successful. 172 // Returns NULL if buffer is NULL. 173 static BinaryValue* Create(char* buffer, size_t size); 174 175 // For situations where you want to keep ownership of your buffer, this 176 // factory method creates a new BinaryValue by copying the contents of the 177 // buffer that's passed in. 178 // Returns NULL if buffer is NULL. 179 static BinaryValue* CreateWithCopiedBuffer(const char* buffer, size_t size); 180 181 virtual ~BinaryValue(); 182 183 // Subclassed methods 184 virtual Value* DeepCopy() const; 185 virtual bool Equals(const Value* other) const; 186 187 size_t GetSize() const { return size_; } 188 char* GetBuffer() { return buffer_; } 189 const char* GetBuffer() const { return buffer_; } 190 191 private: 192 // Constructor is private so that only objects with valid buffer pointers 193 // and size values can be created. 194 BinaryValue(char* buffer, size_t size); 195 196 char* buffer_; 197 size_t size_; 198 199 DISALLOW_COPY_AND_ASSIGN(BinaryValue); 200}; 201 202// DictionaryValue provides a key-value dictionary with (optional) "path" 203// parsing for recursive access; see the comment at the top of the file. Keys 204// are |std::string|s and should be UTF-8 encoded. 205class DictionaryValue : public Value { 206 public: 207 DictionaryValue(); 208 virtual ~DictionaryValue(); 209 210 // Subclassed methods 211 virtual Value* DeepCopy() const; 212 virtual bool Equals(const Value* other) const; 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. 218 size_t size() const { return dictionary_.size(); } 219 220 // Returns whether the dictionary is 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 SetReal(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 // Gets the Value associated with the given path starting from this object. 250 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes 251 // into the next DictionaryValue down. If the path can be resolved 252 // successfully, the value for the last key in the path will be returned 253 // through the |out_value| parameter, and the function will return true. 254 // Otherwise, it will return false and |out_value| will be untouched. 255 // Note that the dictionary always owns the value that's returned. 256 bool Get(const std::string& path, Value** out_value) const; 257 258 // These are convenience forms of Get(). The value will be retrieved 259 // and the return value will be true if the path is valid and the value at 260 // the end of the path can be returned in the form specified. 261 bool GetBoolean(const std::string& path, bool* out_value) const; 262 bool GetInteger(const std::string& path, int* out_value) const; 263 bool GetReal(const std::string& path, double* out_value) const; 264 bool GetString(const std::string& path, std::string* out_value) const; 265 bool GetString(const std::string& path, string16* out_value) const; 266 bool GetStringASCII(const std::string& path, std::string* out_value) const; 267 bool GetBinary(const std::string& path, BinaryValue** out_value) const; 268 bool GetDictionary(const std::string& path, 269 DictionaryValue** out_value) const; 270 bool GetList(const std::string& path, ListValue** out_value) const; 271 272 // Like Get(), but without special treatment of '.'. This allows e.g. URLs to 273 // be used as paths. 274 bool GetWithoutPathExpansion(const std::string& key, 275 Value** out_value) const; 276 bool GetIntegerWithoutPathExpansion(const std::string& key, 277 int* out_value) const; 278 bool GetRealWithoutPathExpansion(const std::string& key, 279 double* out_value) const; 280 bool GetStringWithoutPathExpansion(const std::string& key, 281 std::string* out_value) const; 282 bool GetStringWithoutPathExpansion(const std::string& key, 283 string16* out_value) const; 284 bool GetDictionaryWithoutPathExpansion(const std::string& key, 285 DictionaryValue** out_value) const; 286 bool GetListWithoutPathExpansion(const std::string& key, 287 ListValue** out_value) const; 288 289 // Removes the Value with the specified path from this dictionary (or one 290 // of its child dictionaries, if the path is more than just a local key). 291 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be 292 // passed out via out_value. If |out_value| is NULL, the removed value will 293 // be deleted. This method returns true if |path| is a valid path; otherwise 294 // it will return false and the DictionaryValue object will be unchanged. 295 bool Remove(const std::string& path, Value** out_value); 296 297 // Like Remove(), but without special treatment of '.'. This allows e.g. URLs 298 // to be used as paths. 299 bool RemoveWithoutPathExpansion(const std::string& key, Value** out_value); 300 301 // Makes a copy of |this| but doesn't include empty dictionaries and lists in 302 // the copy. This never returns NULL, even if |this| itself is empty. 303 DictionaryValue* DeepCopyWithoutEmptyChildren(); 304 305 // Merge a given dictionary into this dictionary. This is done recursively, 306 // i.e. any subdictionaries will be merged as well. In case of key collisions, 307 // the passed in dictionary takes precedence and data already present will be 308 // replaced. 309 void MergeDictionary(const DictionaryValue* dictionary); 310 311 // This class provides an iterator for the keys in the dictionary. 312 // It can't be used to modify the dictionary. 313 // 314 // YOU SHOULD ALWAYS USE THE XXXWithoutPathExpansion() APIs WITH THESE, NOT 315 // THE NORMAL XXX() APIs. This makes sure things will work correctly if any 316 // keys have '.'s in them. 317 class key_iterator 318 : private std::iterator<std::input_iterator_tag, const std::string> { 319 public: 320 explicit key_iterator(ValueMap::const_iterator itr) { itr_ = itr; } 321 key_iterator operator++() { 322 ++itr_; 323 return *this; 324 } 325 const std::string& operator*() { return itr_->first; } 326 bool operator!=(const key_iterator& other) { return itr_ != other.itr_; } 327 bool operator==(const key_iterator& other) { return itr_ == other.itr_; } 328 329 private: 330 ValueMap::const_iterator itr_; 331 }; 332 333 key_iterator begin_keys() const { return key_iterator(dictionary_.begin()); } 334 key_iterator end_keys() const { return key_iterator(dictionary_.end()); } 335 336 private: 337 ValueMap dictionary_; 338 339 DISALLOW_COPY_AND_ASSIGN(DictionaryValue); 340}; 341 342// This type of Value represents a list of other Value values. 343class ListValue : public Value { 344 public: 345 ListValue(); 346 ~ListValue(); 347 348 // Subclassed methods 349 virtual bool GetAsList(ListValue** out_value); 350 virtual Value* DeepCopy() const; 351 virtual bool Equals(const Value* other) const; 352 353 // Clears the contents of this ListValue 354 void Clear(); 355 356 // Returns the number of Values in this list. 357 size_t GetSize() const { return list_.size(); } 358 359 // Returns whether the list is empty. 360 bool empty() const { return list_.empty(); } 361 362 // Sets the list item at the given index to be the Value specified by 363 // the value given. If the index beyond the current end of the list, null 364 // Values will be used to pad out the list. 365 // Returns true if successful, or false if the index was negative or 366 // the value is a null pointer. 367 bool Set(size_t index, Value* in_value); 368 369 // Gets the Value at the given index. Modifies |out_value| (and returns true) 370 // only if the index falls within the current list range. 371 // Note that the list always owns the Value passed out via |out_value|. 372 bool Get(size_t index, Value** out_value) const; 373 374 // Convenience forms of Get(). Modifies |out_value| (and returns true) 375 // only if the index is valid and the Value at that index can be returned 376 // in the specified form. 377 bool GetBoolean(size_t index, bool* out_value) const; 378 bool GetInteger(size_t index, int* out_value) const; 379 bool GetReal(size_t index, double* out_value) const; 380 bool GetString(size_t index, std::string* out_value) const; 381 bool GetString(size_t index, string16* out_value) const; 382 bool GetBinary(size_t index, BinaryValue** out_value) const; 383 bool GetDictionary(size_t index, DictionaryValue** out_value) const; 384 bool GetList(size_t index, ListValue** out_value) const; 385 386 // Removes the Value with the specified index from this list. 387 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be 388 // passed out via |out_value|. If |out_value| is NULL, the removed value will 389 // be deleted. This method returns true if |index| is valid; otherwise 390 // it will return false and the ListValue object will be unchanged. 391 bool Remove(size_t index, Value** out_value); 392 393 // Removes the first instance of |value| found in the list, if any, and 394 // deletes it. Returns the index that it was located at (-1 for not present). 395 int Remove(const Value& value); 396 397 // Appends a Value to the end of the list. 398 void Append(Value* in_value); 399 400 // Appends a Value if it's not already present. 401 // Returns true if successful, or false if the value was already present. 402 bool AppendIfNotPresent(Value* in_value); 403 404 // Insert a Value at index. 405 // Returns true if successful, or false if the index was out of range. 406 bool Insert(size_t index, Value* in_value); 407 408 // Swaps contents with the |other| list. 409 void Swap(ListValue* other) { 410 list_.swap(other->list_); 411 } 412 413 // Iteration 414 typedef ValueVector::iterator iterator; 415 typedef ValueVector::const_iterator const_iterator; 416 417 ListValue::iterator begin() { return list_.begin(); } 418 ListValue::iterator end() { return list_.end(); } 419 420 ListValue::const_iterator begin() const { return list_.begin(); } 421 ListValue::const_iterator end() const { return list_.end(); } 422 423 private: 424 ValueVector list_; 425 426 DISALLOW_COPY_AND_ASSIGN(ListValue); 427}; 428 429// This interface is implemented by classes that know how to serialize and 430// deserialize Value objects. 431class ValueSerializer { 432 public: 433 virtual ~ValueSerializer(); 434 435 virtual bool Serialize(const Value& root) = 0; 436 437 // This method deserializes the subclass-specific format into a Value object. 438 // If the return value is non-NULL, the caller takes ownership of returned 439 // Value. If the return value is NULL, and if error_code is non-NULL, 440 // error_code will be set with the underlying error. 441 // If |error_message| is non-null, it will be filled in with a formatted 442 // error message including the location of the error if appropriate. 443 virtual Value* Deserialize(int* error_code, std::string* error_str) = 0; 444}; 445 446#endif // BASE_VALUES_H_ 447