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