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 <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
     39 namespace base {
     40 
     41 class DictionaryValue;
     42 class FundamentalValue;
     43 class ListValue;
     44 class StringValue;
     45 class Value;
     46 
     47 typedef std::vector<Value*> ValueVector;
     48 typedef 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.
     55 class 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.
    130 class 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 
    152 class 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 
    172 class 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.
    208 class 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     ~Iterator();
    352 
    353     bool IsAtEnd() const { return it_ == target_.dictionary_.end(); }
    354     void Advance() { ++it_; }
    355 
    356     const std::string& key() const { return it_->first; }
    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.
    387   size_t GetSize() const { return list_.size(); }
    388 
    389   // Returns whether the list is 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   bool Get(size_t index, const Value** out_value) const;
    403   bool Get(size_t index, Value** out_value);
    404 
    405   // Convenience forms of Get().  Modifies |out_value| (and returns true)
    406   // only if the index is valid and the Value at that index can be returned
    407   // in the specified form.
    408   bool GetBoolean(size_t index, bool* out_value) const;
    409   bool GetInteger(size_t index, int* out_value) const;
    410   bool GetDouble(size_t index, double* out_value) const;
    411   bool GetString(size_t index, std::string* out_value) const;
    412   bool GetString(size_t index, string16* out_value) const;
    413   bool GetBinary(size_t index, const BinaryValue** out_value) const;
    414   bool GetBinary(size_t index, BinaryValue** out_value);
    415   bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
    416   bool GetDictionary(size_t index, DictionaryValue** out_value);
    417   bool GetList(size_t index, const ListValue** out_value) const;
    418   bool GetList(size_t index, ListValue** out_value);
    419 
    420   // Removes the Value with the specified index from this list.
    421   // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
    422   // passed out via |out_value|.  If |out_value| is NULL, the removed value will
    423   // be deleted.  This method returns true if |index| is valid; otherwise
    424   // it will return false and the ListValue object will be unchanged.
    425   virtual bool Remove(size_t index, scoped_ptr<Value>* out_value);
    426 
    427   // Removes the first instance of |value| found in the list, if any, and
    428   // deletes it. |index| is the location where |value| was found. Returns false
    429   // if not found.
    430   bool Remove(const Value& value, size_t* index);
    431 
    432   // Removes the element at |iter|. If |out_value| is NULL, the value will be
    433   // deleted, otherwise ownership of the value is passed back to the caller.
    434   // Returns an iterator pointing to the location of the element that
    435   // followed the erased element.
    436   iterator Erase(iterator iter, scoped_ptr<Value>* out_value);
    437 
    438   // Appends a Value to the end of the list.
    439   void Append(Value* in_value);
    440 
    441   // Convenience forms of Append.
    442   void AppendBoolean(bool in_value);
    443   void AppendInteger(int in_value);
    444   void AppendDouble(double in_value);
    445   void AppendString(const std::string& in_value);
    446   void AppendString(const string16& in_value);
    447   void AppendStrings(const std::vector<std::string>& in_values);
    448   void AppendStrings(const std::vector<string16>& in_values);
    449 
    450   // Appends a Value if it's not already present. Takes ownership of the
    451   // |in_value|. Returns true if successful, or false if the value was already
    452   // present. If the value was already present the |in_value| is deleted.
    453   bool AppendIfNotPresent(Value* in_value);
    454 
    455   // Insert a Value at index.
    456   // Returns true if successful, or false if the index was out of range.
    457   bool Insert(size_t index, Value* in_value);
    458 
    459   // Searches for the first instance of |value| in the list using the Equals
    460   // method of the Value type.
    461   // Returns a const_iterator to the found item or to end() if none exists.
    462   const_iterator Find(const Value& value) const;
    463 
    464   // Swaps contents with the |other| list.
    465   virtual void Swap(ListValue* other);
    466 
    467   // Iteration.
    468   iterator begin() { return list_.begin(); }
    469   iterator end() { return list_.end(); }
    470 
    471   const_iterator begin() const { return list_.begin(); }
    472   const_iterator end() const { return list_.end(); }
    473 
    474   // Overridden from Value:
    475   virtual bool GetAsList(ListValue** out_value) OVERRIDE;
    476   virtual bool GetAsList(const ListValue** out_value) const OVERRIDE;
    477   virtual ListValue* DeepCopy() const OVERRIDE;
    478   virtual bool Equals(const Value* other) const OVERRIDE;
    479 
    480  private:
    481   ValueVector list_;
    482 
    483   DISALLOW_COPY_AND_ASSIGN(ListValue);
    484 };
    485 
    486 // This interface is implemented by classes that know how to serialize and
    487 // deserialize Value objects.
    488 class BASE_EXPORT ValueSerializer {
    489  public:
    490   virtual ~ValueSerializer();
    491 
    492   virtual bool Serialize(const Value& root) = 0;
    493 
    494   // This method deserializes the subclass-specific format into a Value object.
    495   // If the return value is non-NULL, the caller takes ownership of returned
    496   // Value. If the return value is NULL, and if error_code is non-NULL,
    497   // error_code will be set with the underlying error.
    498   // If |error_message| is non-null, it will be filled in with a formatted
    499   // error message including the location of the error if appropriate.
    500   virtual Value* Deserialize(int* error_code, std::string* error_str) = 0;
    501 };
    502 
    503 // Stream operator so Values can be used in assertion statements.  In order that
    504 // gtest uses this operator to print readable output on test failures, we must
    505 // override each specific type. Otherwise, the default template implementation
    506 // is preferred over an upcast.
    507 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
    508 
    509 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
    510                                             const FundamentalValue& value) {
    511   return out << static_cast<const Value&>(value);
    512 }
    513 
    514 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
    515                                             const StringValue& value) {
    516   return out << static_cast<const Value&>(value);
    517 }
    518 
    519 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
    520                                             const DictionaryValue& value) {
    521   return out << static_cast<const Value&>(value);
    522 }
    523 
    524 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
    525                                             const ListValue& value) {
    526   return out << static_cast<const Value&>(value);
    527 }
    528 
    529 }  // namespace base
    530 
    531 // http://crbug.com/88666
    532 using base::DictionaryValue;
    533 using base::ListValue;
    534 using base::StringValue;
    535 using base::Value;
    536 
    537 #endif  // BASE_VALUES_H_
    538