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