Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2009 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
      6 // intended for storing setting and other persistable data.
      7 // It includes the ability to specify (recursive) lists and dictionaries, so
      8 // it's fairly expressive.  However, the API is optimized for the common case,
      9 // namely storing a hierarchical tree of simple values.  Given a
     10 // DictionaryValue root, you can easily do things like:
     11 //
     12 // root->SetString(L"global.pages.homepage", L"http://goateleporter.com");
     13 // std::wstring homepage = L"http://google.com";  // default/fallback value
     14 // root->GetString(L"global.pages.homepage", &homepage);
     15 //
     16 // where "global" and "pages" are also DictionaryValues, and "homepage"
     17 // is a string setting.  If some elements of the path didn't exist yet,
     18 // the SetString() method would create the missing elements and attach them
     19 // to root before attaching the homepage value.
     20 
     21 #ifndef BASE_VALUES_H_
     22 #define BASE_VALUES_H_
     23 
     24 #include <iterator>
     25 #include <map>
     26 #include <string>
     27 #include <vector>
     28 
     29 #include "base/basictypes.h"
     30 #include "base/string16.h"
     31 #include "build/build_config.h"
     32 
     33 class Value;
     34 class FundamentalValue;
     35 class StringValue;
     36 class BinaryValue;
     37 class DictionaryValue;
     38 class ListValue;
     39 
     40 typedef std::vector<Value*> ValueVector;
     41 typedef std::map<std::wstring, Value*> ValueMap;
     42 
     43 // The Value class is the base class for Values.  A Value can be
     44 // instantiated via the Create*Value() factory methods, or by directly
     45 // creating instances of the subclasses.
     46 class Value {
     47  public:
     48   virtual ~Value();
     49 
     50   // Convenience methods for creating Value objects for various
     51   // kinds of values without thinking about which class implements them.
     52   // These can always be expected to return a valid Value*.
     53   static Value* CreateNullValue();
     54   static Value* CreateBooleanValue(bool in_value);
     55   static Value* CreateIntegerValue(int in_value);
     56   static Value* CreateRealValue(double in_value);
     57   static Value* CreateStringValue(const std::string& in_value);
     58   static Value* CreateStringValue(const std::wstring& in_value);
     59   static Value* CreateStringValueFromUTF16(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 "value" parameter and true is returned;
     89   // otherwise, false is returned and "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(std::wstring* out_value) const;
     95   virtual bool GetAsUTF16(string16* out_value) const;
     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  protected:
    105   // This isn't safe for end-users (they should use the Create*Value()
    106   // static methods above), but it's useful for subclasses.
    107   explicit Value(ValueType type) : type_(type) {}
    108 
    109  private:
    110   Value();
    111 
    112   ValueType type_;
    113 
    114   DISALLOW_COPY_AND_ASSIGN(Value);
    115 };
    116 
    117 // FundamentalValue represents the simple fundamental types of values.
    118 class FundamentalValue : public Value {
    119  public:
    120   explicit FundamentalValue(bool in_value)
    121     : Value(TYPE_BOOLEAN), boolean_value_(in_value) {}
    122   explicit FundamentalValue(int in_value)
    123     : Value(TYPE_INTEGER), integer_value_(in_value) {}
    124   explicit FundamentalValue(double in_value)
    125     : Value(TYPE_REAL), real_value_(in_value) {}
    126   ~FundamentalValue();
    127 
    128   // Subclassed methods
    129   virtual bool GetAsBoolean(bool* out_value) const;
    130   virtual bool GetAsInteger(int* out_value) const;
    131   virtual bool GetAsReal(double* out_value) const;
    132   virtual Value* DeepCopy() const;
    133   virtual bool Equals(const Value* other) const;
    134 
    135  private:
    136   union {
    137     bool boolean_value_;
    138     int integer_value_;
    139     double real_value_;
    140   };
    141 
    142   DISALLOW_COPY_AND_ASSIGN(FundamentalValue);
    143 };
    144 
    145 class StringValue : public Value {
    146  public:
    147   // Initializes a StringValue with a UTF-8 narrow character string.
    148   explicit StringValue(const std::string& in_value);
    149 
    150   // Initializes a StringValue with a wide character string.
    151   explicit StringValue(const std::wstring& in_value);
    152 
    153 #if !defined(WCHAR_T_IS_UTF16)
    154   // Initializes a StringValue with a string16.
    155   explicit StringValue(const string16& in_value);
    156 #endif
    157 
    158   ~StringValue();
    159 
    160   // Subclassed methods
    161   bool GetAsString(std::string* out_value) const;
    162   bool GetAsString(std::wstring* out_value) const;
    163   bool GetAsUTF16(string16* out_value) const;
    164   Value* DeepCopy() const;
    165   virtual bool Equals(const Value* other) const;
    166 
    167  private:
    168   std::string value_;
    169 
    170   DISALLOW_COPY_AND_ASSIGN(StringValue);
    171 };
    172 
    173 class BinaryValue: public Value {
    174  public:
    175   // Creates a Value to represent a binary buffer.  The new object takes
    176   // ownership of the pointer passed in, if successful.
    177   // Returns NULL if buffer is NULL.
    178   static BinaryValue* Create(char* buffer, size_t size);
    179 
    180   // For situations where you want to keep ownership of your buffer, this
    181   // factory method creates a new BinaryValue by copying the contents of the
    182   // buffer that's passed in.
    183   // Returns NULL if buffer is NULL.
    184   static BinaryValue* CreateWithCopiedBuffer(const char* buffer, size_t size);
    185 
    186   ~BinaryValue();
    187 
    188   // Subclassed methods
    189   Value* DeepCopy() const;
    190   virtual bool Equals(const Value* other) const;
    191 
    192   size_t GetSize() const { return size_; }
    193   char* GetBuffer() { return buffer_; }
    194   const char* GetBuffer() const { return buffer_; }
    195 
    196  private:
    197   // Constructor is private so that only objects with valid buffer pointers
    198   // and size values can be created.
    199   BinaryValue(char* buffer, size_t size);
    200 
    201   char* buffer_;
    202   size_t size_;
    203 
    204   DISALLOW_COPY_AND_ASSIGN(BinaryValue);
    205 };
    206 
    207 class DictionaryValue : public Value {
    208  public:
    209   DictionaryValue() : Value(TYPE_DICTIONARY) {}
    210   ~DictionaryValue();
    211 
    212   // Subclassed methods
    213   Value* DeepCopy() const;
    214   virtual bool Equals(const Value* other) const;
    215 
    216   // Returns true if the current dictionary has a value for the given key.
    217   bool HasKey(const std::wstring& key) const;
    218 
    219   // Returns the number of Values in this dictionary.
    220   size_t size() const { return dictionary_.size(); }
    221 
    222   // Returns whether the dictionary is empty.
    223   bool empty() const { return dictionary_.empty(); }
    224 
    225   // Clears any current contents of this dictionary.
    226   void Clear();
    227 
    228   // Sets the Value associated with the given path starting from this object.
    229   // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
    230   // into the next DictionaryValue down.  Obviously, "." can't be used
    231   // within a key, but there are no other restrictions on keys.
    232   // If the key at any step of the way doesn't exist, or exists but isn't
    233   // a DictionaryValue, a new DictionaryValue will be created and attached
    234   // to the path in that location.
    235   // Note that the dictionary takes ownership of the value referenced by
    236   // |in_value|, and therefore |in_value| must be non-NULL.
    237   void Set(const std::wstring& path, Value* in_value);
    238 
    239   // Convenience forms of Set().  These methods will replace any existing
    240   // value at that path, even if it has a different type.
    241   void SetBoolean(const std::wstring& path, bool in_value);
    242   void SetInteger(const std::wstring& path, int in_value);
    243   void SetReal(const std::wstring& path, double in_value);
    244   void SetString(const std::wstring& path, const std::string& in_value);
    245   void SetString(const std::wstring& path, const std::wstring& in_value);
    246   void SetStringFromUTF16(const std::wstring& path, const string16& in_value);
    247 
    248   // Like Set(), but without special treatment of '.'.  This allows e.g. URLs to
    249   // be used as paths.
    250   void SetWithoutPathExpansion(const std::wstring& key, Value* in_value);
    251 
    252   // Gets the Value associated with the given path starting from this object.
    253   // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
    254   // into the next DictionaryValue down.  If the path can be resolved
    255   // successfully, the value for the last key in the path will be returned
    256   // through the "value" parameter, and the function will return true.
    257   // Otherwise, it will return false and "value" will be untouched.
    258   // Note that the dictionary always owns the value that's returned.
    259   bool Get(const std::wstring& path, Value** out_value) const;
    260 
    261   // These are convenience forms of Get().  The value will be retrieved
    262   // and the return value will be true if the path is valid and the value at
    263   // the end of the path can be returned in the form specified.
    264   bool GetBoolean(const std::wstring& path, bool* out_value) const;
    265   bool GetInteger(const std::wstring& path, int* out_value) const;
    266   bool GetReal(const std::wstring& path, double* out_value) const;
    267   bool GetString(const std::wstring& path, std::string* out_value) const;
    268   bool GetString(const std::wstring& path, std::wstring* out_value) const;
    269   bool GetStringAsUTF16(const std::wstring& path, string16* out_value) const;
    270   bool GetBinary(const std::wstring& path, BinaryValue** out_value) const;
    271   bool GetDictionary(const std::wstring& path,
    272                      DictionaryValue** out_value) const;
    273   bool GetList(const std::wstring& path, ListValue** out_value) const;
    274 
    275   // Like Get(), but without special treatment of '.'.  This allows e.g. URLs to
    276   // be used as paths.
    277   bool GetWithoutPathExpansion(const std::wstring& key,
    278                                Value** out_value) const;
    279   bool GetIntegerWithoutPathExpansion(const std::wstring& path,
    280                                       int* out_value) const;
    281   bool GetStringWithoutPathExpansion(const std::wstring& path,
    282                                      std::string* out_value) const;
    283   bool GetStringWithoutPathExpansion(const std::wstring& path,
    284                                      std::wstring* out_value) const;
    285   bool GetStringAsUTF16WithoutPathExpansion(const std::wstring& path,
    286                                             string16* out_value) const;
    287   bool GetDictionaryWithoutPathExpansion(const std::wstring& path,
    288                                          DictionaryValue** out_value) const;
    289   bool GetListWithoutPathExpansion(const std::wstring& path,
    290                                    ListValue** out_value) const;
    291 
    292   // Removes the Value with the specified path from this dictionary (or one
    293   // of its child dictionaries, if the path is more than just a local key).
    294   // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
    295   // passed out via out_value.  If |out_value| is NULL, the removed value will
    296   // be deleted.  This method returns true if |path| is a valid path; otherwise
    297   // it will return false and the DictionaryValue object will be unchanged.
    298   bool Remove(const std::wstring& path, Value** out_value);
    299 
    300   // Like Remove(), but without special treatment of '.'.  This allows e.g. URLs
    301   // to be used as paths.
    302   bool RemoveWithoutPathExpansion(const std::wstring& key, Value** out_value);
    303 
    304   // Makes a copy of |this| but doesn't include empty dictionaries and lists in
    305   // the copy.  This never returns NULL, even if |this| itself is empty.
    306   DictionaryValue* DeepCopyWithoutEmptyChildren();
    307 
    308   // This class provides an iterator for the keys in the dictionary.
    309   // It can't be used to modify the dictionary.
    310   //
    311   // YOU SHOULD ALWAYS USE THE XXXWithoutPathExpansion() APIs WITH THESE, NOT
    312   // THE NORMAL XXX() APIs.  This makes sure things will work correctly if any
    313   // keys have '.'s in them.
    314   class key_iterator
    315     : private std::iterator<std::input_iterator_tag, const std::wstring> {
    316    public:
    317     explicit key_iterator(ValueMap::const_iterator itr) { itr_ = itr; }
    318     key_iterator operator++() {
    319       ++itr_;
    320       return *this;
    321     }
    322     const std::wstring& operator*() { return itr_->first; }
    323     bool operator!=(const key_iterator& other) { return itr_ != other.itr_; }
    324     bool operator==(const key_iterator& other) { return itr_ == other.itr_; }
    325 
    326    private:
    327     ValueMap::const_iterator itr_;
    328   };
    329 
    330   key_iterator begin_keys() const { return key_iterator(dictionary_.begin()); }
    331   key_iterator end_keys() const { return key_iterator(dictionary_.end()); }
    332 
    333  private:
    334   ValueMap dictionary_;
    335 
    336   DISALLOW_COPY_AND_ASSIGN(DictionaryValue);
    337 };
    338 
    339 // This type of Value represents a list of other Value values.
    340 class ListValue : public Value {
    341  public:
    342   ListValue() : Value(TYPE_LIST) {}
    343   ~ListValue();
    344 
    345   // Subclassed methods
    346   Value* DeepCopy() const;
    347   virtual bool Equals(const Value* other) const;
    348 
    349   // Clears the contents of this ListValue
    350   void Clear();
    351 
    352   // Returns the number of Values in this list.
    353   size_t GetSize() const { return list_.size(); }
    354 
    355   // Returns whether the list is empty.
    356   bool empty() const { return list_.empty(); }
    357 
    358   // Sets the list item at the given index to be the Value specified by
    359   // the value given.  If the index beyond the current end of the list, null
    360   // Values will be used to pad out the list.
    361   // Returns true if successful, or false if the index was negative or
    362   // the value is a null pointer.
    363   bool Set(size_t index, Value* in_value);
    364 
    365   // Gets the Value at the given index.  Modifies value (and returns true)
    366   // only if the index falls within the current list range.
    367   // Note that the list always owns the Value passed out via out_value.
    368   bool Get(size_t index, Value** out_value) const;
    369 
    370   // Convenience forms of Get().  Modifies value (and returns true) only if
    371   // the index is valid and the Value at that index can be returned in
    372   // the specified form.
    373   bool GetBoolean(size_t index, bool* out_value) const;
    374   bool GetInteger(size_t index, int* out_value) const;
    375   bool GetReal(size_t index, double* out_value) const;
    376   bool GetString(size_t index, std::string* out_value) const;
    377   bool GetString(size_t index, std::wstring* out_value) const;
    378   bool GetStringAsUTF16(size_t index, string16* out_value) const;
    379   bool GetBinary(size_t index, BinaryValue** out_value) const;
    380   bool GetDictionary(size_t index, DictionaryValue** out_value) const;
    381   bool GetList(size_t index, ListValue** out_value) const;
    382 
    383   // Removes the Value with the specified index from this list.
    384   // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
    385   // passed out via |out_value|.  If |out_value| is NULL, the removed value will
    386   // be deleted.  This method returns true if |index| is valid; otherwise
    387   // it will return false and the ListValue object will be unchanged.
    388   bool Remove(size_t index, Value** out_value);
    389 
    390   // Removes the first instance of |value| found in the list, if any, and
    391   // deletes it.  Returns the index that it was located at (-1 for not present).
    392   int Remove(const Value& value);
    393 
    394   // Appends a Value to the end of the list.
    395   void Append(Value* in_value);
    396 
    397   // Insert a Value at index.
    398   // Returns true if successful, or false if the index was out of range.
    399   bool Insert(size_t index, Value* in_value);
    400 
    401   // Iteration
    402   typedef ValueVector::iterator iterator;
    403   typedef ValueVector::const_iterator const_iterator;
    404 
    405   ListValue::iterator begin() { return list_.begin(); }
    406   ListValue::iterator end() { return list_.end(); }
    407 
    408   ListValue::const_iterator begin() const { return list_.begin(); }
    409   ListValue::const_iterator end() const { return list_.end(); }
    410 
    411  private:
    412   ValueVector list_;
    413 
    414   DISALLOW_COPY_AND_ASSIGN(ListValue);
    415 };
    416 
    417 // This interface is implemented by classes that know how to serialize and
    418 // deserialize Value objects.
    419 class ValueSerializer {
    420  public:
    421   virtual ~ValueSerializer() {}
    422 
    423   virtual bool Serialize(const Value& root) = 0;
    424 
    425   // This method deserializes the subclass-specific format into a Value object.
    426   // If the return value is non-NULL, the caller takes ownership of returned
    427   // Value. If the return value is NULL, and if error_message is non-NULL,
    428   // error_message should be filled with a message describing the error.
    429   virtual Value* Deserialize(std::string* error_message) = 0;
    430 };
    431 
    432 #endif  // BASE_VALUES_H_
    433