Initialize Tizen 2.3
[external/chromium.git] / base / values.h
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // This file specifies a recursive data storage class called Value intended for
6 // storing setting and other persistable data.  It includes the ability to
7 // specify (recursive) lists and dictionaries, so it's fairly expressive.
8 // However, the API is optimized for the common case, namely storing a
9 // hierarchical tree of simple values.  Given a DictionaryValue root, you can
10 // easily do things like:
11 //
12 // root->SetString("global.pages.homepage", "http://goateleporter.com");
13 // std::string homepage = "http://google.com";  // default/fallback value
14 // root->GetString("global.pages.homepage", &homepage);
15 //
16 // where "global" and "pages" are also DictionaryValues, and "homepage" is a
17 // string setting.  If some elements of the path didn't exist yet, the
18 // SetString() method would create the missing elements and attach them to root
19 // before attaching the homepage value.
20
21 #ifndef BASE_VALUES_H_
22 #define BASE_VALUES_H_
23 #pragma once
24
25 #include <iterator>
26 #include <map>
27 #include <string>
28 #include <vector>
29
30 #include "base/base_export.h"
31 #include "base/basictypes.h"
32 #include "base/compiler_specific.h"
33 #include "base/string16.h"
34
35 // This file declares "using base::Value", etc. at the bottom, so that
36 // current code can use these classes without the base namespace. In
37 // new code, please always use base::Value, etc. or add your own
38 // "using" declaration.
39 // http://crbug.com/88666
40 namespace base {
41
42 class BinaryValue;
43 class DictionaryValue;
44 class FundamentalValue;
45 class ListValue;
46 class StringValue;
47 class Value;
48
49 typedef std::vector<Value*> ValueVector;
50 typedef std::map<std::string, Value*> ValueMap;
51
52 // The Value class is the base class for Values. A Value can be instantiated
53 // via the Create*Value() factory methods, or by directly creating instances of
54 // the subclasses.
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   };
67
68   virtual ~Value();
69
70   // Convenience methods for creating Value objects for various
71   // kinds of values without thinking about which class implements them.
72   // These can always be expected to return a valid Value*.
73   static Value* CreateNullValue();
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 settings.
91   // If the current setting object can be converted into the given type,
92   // the value is returned through the |out_value| parameter and true is
93   // returned;  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
102   // This creates a deep copy of the entire Value tree, and returns a pointer
103   // to the copy.  The caller gets ownership of the copy, of course.
104   //
105   // Subclasses return their own type directly in their overrides;
106   // this works because C++ supports covariant return types.
107   virtual Value* DeepCopy() const;
108
109   // Compares if two Value objects have equal contents.
110   virtual bool Equals(const Value* other) const;
111
112   // Compares if two Value objects have equal contents. Can handle NULLs.
113   // NULLs are considered equal but different from Value::CreateNullValue().
114   static bool Equals(const Value* a, const Value* b);
115
116  protected:
117   // This isn't safe for end-users (they should use the Create*Value()
118   // static methods above), but it's useful for subclasses.
119   explicit Value(Type type);
120
121  private:
122   Value();
123
124   Type type_;
125
126   DISALLOW_COPY_AND_ASSIGN(Value);
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   DISALLOW_COPY_AND_ASSIGN(FundamentalValue);
152 };
153
154 class BASE_EXPORT StringValue : public Value {
155  public:
156   // Initializes a StringValue with a UTF-8 narrow character string.
157   explicit StringValue(const std::string& in_value);
158
159   // Initializes a StringValue with a string16.
160   explicit StringValue(const string16& in_value);
161
162   virtual ~StringValue();
163
164   // Overridden from Value:
165   virtual bool GetAsString(std::string* out_value) const OVERRIDE;
166   virtual bool GetAsString(string16* out_value) const OVERRIDE;
167   virtual StringValue* DeepCopy() const OVERRIDE;
168   virtual bool Equals(const Value* other) const OVERRIDE;
169
170  private:
171   std::string value_;
172
173   DISALLOW_COPY_AND_ASSIGN(StringValue);
174 };
175
176 class BASE_EXPORT BinaryValue: public Value {
177  public:
178   virtual ~BinaryValue();
179
180   // Creates a Value to represent a binary buffer.  The new object takes
181   // ownership of the pointer passed in, if successful.
182   // Returns NULL if buffer is NULL.
183   static BinaryValue* Create(char* buffer, size_t size);
184
185   // For situations where you want to keep ownership of your buffer, this
186   // factory method creates a new BinaryValue by copying the contents of the
187   // buffer that's passed in.
188   // Returns NULL if buffer is NULL.
189   static BinaryValue* CreateWithCopiedBuffer(const char* buffer, size_t size);
190
191   size_t GetSize() const { return size_; }
192   char* GetBuffer() { return buffer_; }
193   const char* GetBuffer() const { return buffer_; }
194
195   // Overridden from Value:
196   virtual BinaryValue* DeepCopy() const OVERRIDE;
197   virtual bool Equals(const Value* other) const OVERRIDE;
198
199  private:
200   // Constructor is private so that only objects with valid buffer pointers
201   // and size values can be created.
202   BinaryValue(char* buffer, size_t size);
203
204   char* buffer_;
205   size_t size_;
206
207   DISALLOW_COPY_AND_ASSIGN(BinaryValue);
208 };
209
210 // DictionaryValue provides a key-value dictionary with (optional) "path"
211 // parsing for recursive access; see the comment at the top of the file. Keys
212 // are |std::string|s and should be UTF-8 encoded.
213 class BASE_EXPORT DictionaryValue : public Value {
214  public:
215   DictionaryValue();
216   virtual ~DictionaryValue();
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   // Gets the Value associated with the given path starting from this object.
254   // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
255   // into the next DictionaryValue down.  If the path can be resolved
256   // successfully, the value for the last key in the path will be returned
257   // through the |out_value| parameter, and the function will return true.
258   // Otherwise, it will return false and |out_value| will be untouched.
259   // Note that the dictionary always owns the value that's returned.
260   bool Get(const std::string& path, Value** out_value) const;
261
262   // These are convenience forms of Get().  The value will be retrieved
263   // and the return value will be true if the path is valid and the value at
264   // the end of the path can be returned in the form specified.
265   bool GetBoolean(const std::string& path, bool* out_value) const;
266   bool GetInteger(const std::string& path, int* out_value) const;
267   bool GetDouble(const std::string& path, double* out_value) const;
268   bool GetString(const std::string& path, std::string* out_value) const;
269   bool GetString(const std::string& path, string16* out_value) const;
270   bool GetStringASCII(const std::string& path, std::string* out_value) const;
271   bool GetBinary(const std::string& path, BinaryValue** out_value) const;
272   bool GetDictionary(const std::string& path,
273                      DictionaryValue** out_value) const;
274   bool GetList(const std::string& path, ListValue** out_value) const;
275
276   // Like Get(), but without special treatment of '.'.  This allows e.g. URLs to
277   // be used as paths.
278   bool GetWithoutPathExpansion(const std::string& key,
279                                Value** out_value) const;
280   bool GetIntegerWithoutPathExpansion(const std::string& key,
281                                       int* out_value) const;
282   bool GetDoubleWithoutPathExpansion(const std::string& key,
283                                    double* out_value) const;
284   bool GetStringWithoutPathExpansion(const std::string& key,
285                                      std::string* out_value) const;
286   bool GetStringWithoutPathExpansion(const std::string& key,
287                                      string16* out_value) const;
288   bool GetDictionaryWithoutPathExpansion(const std::string& key,
289                                          DictionaryValue** out_value) const;
290   bool GetListWithoutPathExpansion(const std::string& key,
291                                    ListValue** out_value) const;
292
293   // Removes the Value with the specified path from this dictionary (or one
294   // of its child dictionaries, if the path is more than just a local key).
295   // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
296   // passed out via out_value.  If |out_value| is NULL, the removed value will
297   // be deleted.  This method returns true if |path| is a valid path; otherwise
298   // it will return false and the DictionaryValue object will be unchanged.
299   bool Remove(const std::string& path, Value** out_value);
300
301   // Like Remove(), but without special treatment of '.'.  This allows e.g. URLs
302   // to be used as paths.
303   bool RemoveWithoutPathExpansion(const std::string& key, Value** out_value);
304
305   // Makes a copy of |this| but doesn't include empty dictionaries and lists in
306   // the copy.  This never returns NULL, even if |this| itself is empty.
307   DictionaryValue* DeepCopyWithoutEmptyChildren();
308
309   // Merge a given dictionary into this dictionary. This is done recursively,
310   // i.e. any subdictionaries will be merged as well. In case of key collisions,
311   // the passed in dictionary takes precedence and data already present will be
312   // replaced.
313   void MergeDictionary(const DictionaryValue* dictionary);
314
315   // Swaps contents with the |other| dictionary.
316   void Swap(DictionaryValue* other) {
317     dictionary_.swap(other->dictionary_);
318   }
319
320   // This class provides an iterator for the keys in the dictionary.
321   // It can't be used to modify the dictionary.
322   //
323   // YOU SHOULD ALWAYS USE THE XXXWithoutPathExpansion() APIs WITH THESE, NOT
324   // THE NORMAL XXX() APIs.  This makes sure things will work correctly if any
325   // keys have '.'s in them.
326   class key_iterator
327       : private std::iterator<std::input_iterator_tag, const std::string> {
328    public:
329     explicit key_iterator(ValueMap::const_iterator itr) { itr_ = itr; }
330     key_iterator operator++() {
331       ++itr_;
332       return *this;
333     }
334     const std::string& operator*() { return itr_->first; }
335     bool operator!=(const key_iterator& other) { return itr_ != other.itr_; }
336     bool operator==(const key_iterator& other) { return itr_ == other.itr_; }
337
338    private:
339     ValueMap::const_iterator itr_;
340   };
341
342   key_iterator begin_keys() const { return key_iterator(dictionary_.begin()); }
343   key_iterator end_keys() const { return key_iterator(dictionary_.end()); }
344
345   // Overridden from Value:
346   virtual DictionaryValue* DeepCopy() const OVERRIDE;
347   virtual bool Equals(const Value* other) const OVERRIDE;
348
349  private:
350   ValueMap dictionary_;
351
352   DISALLOW_COPY_AND_ASSIGN(DictionaryValue);
353 };
354
355 // This type of Value represents a list of other Value values.
356 class BASE_EXPORT ListValue : public Value {
357  public:
358   typedef ValueVector::iterator iterator;
359   typedef ValueVector::const_iterator const_iterator;
360
361   ListValue();
362   virtual ~ListValue();
363
364   // Clears the contents of this ListValue
365   void Clear();
366
367   // Returns the number of Values in this list.
368   size_t GetSize() const { return list_.size(); }
369
370   // Returns whether the list is empty.
371   bool empty() const { return list_.empty(); }
372
373   // Sets the list item at the given index to be the Value specified by
374   // the value given.  If the index beyond the current end of the list, null
375   // Values will be used to pad out the list.
376   // Returns true if successful, or false if the index was negative or
377   // the value is a null pointer.
378   bool Set(size_t index, Value* in_value);
379
380   // Gets the Value at the given index.  Modifies |out_value| (and returns true)
381   // only if the index falls within the current list range.
382   // Note that the list always owns the Value passed out via |out_value|.
383   bool Get(size_t index, Value** out_value) const;
384
385   // Convenience forms of Get().  Modifies |out_value| (and returns true)
386   // only if the index is valid and the Value at that index can be returned
387   // in the specified form.
388   bool GetBoolean(size_t index, bool* out_value) const;
389   bool GetInteger(size_t index, int* out_value) const;
390   bool GetDouble(size_t index, double* out_value) const;
391   bool GetString(size_t index, std::string* out_value) const;
392   bool GetString(size_t index, string16* out_value) const;
393   bool GetBinary(size_t index, BinaryValue** out_value) const;
394   bool GetDictionary(size_t index, DictionaryValue** out_value) const;
395   bool GetList(size_t index, ListValue** out_value) const;
396
397   // Removes the Value with the specified index from this list.
398   // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
399   // passed out via |out_value|.  If |out_value| is NULL, the removed value will
400   // be deleted.  This method returns true if |index| is valid; otherwise
401   // it will return false and the ListValue object will be unchanged.
402   bool Remove(size_t index, Value** out_value);
403
404   // Removes the first instance of |value| found in the list, if any, and
405   // deletes it. |index| is the location where |value| was found. Returns false
406   // if not found.
407   bool Remove(const Value& value, size_t* index);
408
409   // Appends a Value to the end of the list.
410   void Append(Value* in_value);
411
412   // Appends a Value if it's not already present. Takes ownership of the
413   // |in_value|. Returns true if successful, or false if the value was already
414   // present. If the value was already present the |in_value| is deleted.
415   bool AppendIfNotPresent(Value* in_value);
416
417   // Insert a Value at index.
418   // Returns true if successful, or false if the index was out of range.
419   bool Insert(size_t index, Value* in_value);
420
421   // Swaps contents with the |other| list.
422   void Swap(ListValue* other) {
423     list_.swap(other->list_);
424   }
425
426   // Iteration.
427   iterator begin() { return list_.begin(); }
428   iterator end() { return list_.end(); }
429
430   const_iterator begin() const { return list_.begin(); }
431   const_iterator end() const { return list_.end(); }
432
433   // Overridden from Value:
434   virtual bool GetAsList(ListValue** out_value) OVERRIDE;
435   virtual bool GetAsList(const ListValue** out_value) const OVERRIDE;
436   virtual ListValue* DeepCopy() const OVERRIDE;
437   virtual bool Equals(const Value* other) const OVERRIDE;
438
439  private:
440   ValueVector list_;
441
442   DISALLOW_COPY_AND_ASSIGN(ListValue);
443 };
444
445 // This interface is implemented by classes that know how to serialize and
446 // deserialize Value objects.
447 class BASE_EXPORT ValueSerializer {
448  public:
449   virtual ~ValueSerializer();
450
451   virtual bool Serialize(const Value& root) = 0;
452
453   // This method deserializes the subclass-specific format into a Value object.
454   // If the return value is non-NULL, the caller takes ownership of returned
455   // Value. If the return value is NULL, and if error_code is non-NULL,
456   // error_code will be set with the underlying error.
457   // If |error_message| is non-null, it will be filled in with a formatted
458   // error message including the location of the error if appropriate.
459   virtual Value* Deserialize(int* error_code, std::string* error_str) = 0;
460 };
461
462 }  // namespace base
463
464 // http://crbug.com/88666
465 using base::DictionaryValue;
466 using base::ListValue;
467 using base::StringValue;
468 using base::Value;
469
470 #endif  // BASE_VALUES_H_