Support the Service-Worker-Allowed header
[chromium-blink-merge.git] / base / values.h
blob4648283a78af85e341858655bbff4bb013b9dc67
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.
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.
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.
17 #ifndef BASE_VALUES_H_
18 #define BASE_VALUES_H_
20 #include <stddef.h>
22 #include <iosfwd>
23 #include <map>
24 #include <string>
25 #include <utility>
26 #include <vector>
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"
34 namespace base {
36 class BinaryValue;
37 class DictionaryValue;
38 class FundamentalValue;
39 class ListValue;
40 class StringValue;
41 class Value;
43 typedef std::vector<Value*> ValueVector;
44 typedef std::map<std::string, Value*> ValueMap;
46 // The Value class is the base class for Values. A Value can be instantiated
47 // via the Create*Value() factory methods, or by directly creating instances of
48 // the subclasses.
50 // See the file-level comment above for more information.
51 class BASE_EXPORT Value {
52 public:
53 enum Type {
54 TYPE_NULL = 0,
55 TYPE_BOOLEAN,
56 TYPE_INTEGER,
57 TYPE_DOUBLE,
58 TYPE_STRING,
59 TYPE_BINARY,
60 TYPE_DICTIONARY,
61 TYPE_LIST
62 // Note: Do not add more types. See the file-level comment above for why.
65 virtual ~Value();
67 static Value* CreateNullValue();
69 // Returns the type of the value stored by the current Value object.
70 // Each type will be implemented by only one subclass of Value, so it's
71 // safe to use the Type to determine whether you can cast from
72 // Value* to (Implementing Class)*. Also, a Value object never changes
73 // its type after construction.
74 Type GetType() const { return type_; }
76 // Returns true if the current object represents a given type.
77 bool IsType(Type type) const { return type == type_; }
79 // These methods allow the convenient retrieval of the contents of the Value.
80 // If the current object can be converted into the given type, the value is
81 // returned through the |out_value| parameter and true is returned;
82 // otherwise, false is returned and |out_value| is unchanged.
83 virtual bool GetAsBoolean(bool* out_value) const;
84 virtual bool GetAsInteger(int* out_value) const;
85 virtual bool GetAsDouble(double* out_value) const;
86 virtual bool GetAsString(std::string* out_value) const;
87 virtual bool GetAsString(string16* 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.
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.
99 // Subclasses return their own type directly in their overrides;
100 // this works because C++ supports covariant return types.
101 virtual Value* DeepCopy() const;
103 // Compares if two Value objects have equal contents.
104 virtual bool Equals(const Value* other) const;
106 // Compares if two Value objects have equal contents. Can handle NULLs.
107 // NULLs are considered equal but different from Value::CreateNullValue().
108 static bool Equals(const Value* a, const Value* b);
110 protected:
111 // These aren't safe for end-users, but they are useful for subclasses.
112 explicit Value(Type type);
113 Value(const Value& that);
114 Value& operator=(const Value& that);
116 private:
117 Type type_;
120 // FundamentalValue represents the simple fundamental types of values.
121 class BASE_EXPORT FundamentalValue : public Value {
122 public:
123 explicit FundamentalValue(bool in_value);
124 explicit FundamentalValue(int in_value);
125 explicit FundamentalValue(double in_value);
126 ~FundamentalValue() override;
128 // Overridden from Value:
129 bool GetAsBoolean(bool* out_value) const override;
130 bool GetAsInteger(int* out_value) const override;
131 // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
132 // doubles.
133 bool GetAsDouble(double* out_value) const override;
134 FundamentalValue* DeepCopy() const override;
135 bool Equals(const Value* other) const override;
137 private:
138 union {
139 bool boolean_value_;
140 int integer_value_;
141 double double_value_;
145 class BASE_EXPORT StringValue : public Value {
146 public:
147 // Initializes a StringValue with a UTF-8 narrow character string.
148 explicit StringValue(const std::string& in_value);
150 // Initializes a StringValue with a string16.
151 explicit StringValue(const string16& in_value);
153 ~StringValue() override;
155 // Returns |value_| as a pointer or reference.
156 std::string* GetString();
157 const std::string& GetString() const;
159 // Overridden from Value:
160 bool GetAsString(std::string* out_value) const override;
161 bool GetAsString(string16* out_value) const override;
162 bool GetAsString(const StringValue** out_value) const override;
163 StringValue* DeepCopy() const override;
164 bool Equals(const Value* other) const override;
166 private:
167 std::string value_;
170 class BASE_EXPORT BinaryValue: public Value {
171 public:
172 // Creates a BinaryValue with a null buffer and size of 0.
173 BinaryValue();
175 // Creates a BinaryValue, taking ownership of the bytes pointed to by
176 // |buffer|.
177 BinaryValue(scoped_ptr<char[]> buffer, size_t size);
179 ~BinaryValue() override;
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);
186 size_t GetSize() const { return size_; }
188 // May return NULL.
189 char* GetBuffer() { return buffer_.get(); }
190 const char* GetBuffer() const { return buffer_.get(); }
192 // Overridden from Value:
193 bool GetAsBinary(const BinaryValue** out_value) const override;
194 BinaryValue* DeepCopy() const override;
195 bool Equals(const Value* other) const override;
197 private:
198 scoped_ptr<char[]> buffer_;
199 size_t size_;
201 DISALLOW_COPY_AND_ASSIGN(BinaryValue);
204 // DictionaryValue provides a key-value dictionary with (optional) "path"
205 // parsing for recursive access; see the comment at the top of the file. Keys
206 // are |std::string|s and should be UTF-8 encoded.
207 class BASE_EXPORT DictionaryValue : public Value {
208 public:
209 DictionaryValue();
210 ~DictionaryValue() override;
212 // Overridden from Value:
213 bool GetAsDictionary(DictionaryValue** out_value) override;
214 bool GetAsDictionary(const DictionaryValue** out_value) const override;
216 // Returns true if the current dictionary has a value for the given key.
217 bool HasKey(const std::string& key) const;
219 // Returns the number of Values in this dictionary.
220 size_t size() const { return dictionary_.size(); }
222 // Returns whether the dictionary is empty.
223 bool empty() const { return dictionary_.empty(); }
225 // Clears any current contents of this dictionary.
226 void Clear();
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. |in_value| must be non-null.
235 void Set(const std::string& path, scoped_ptr<Value> in_value);
236 // Deprecated version of the above. TODO(estade): remove.
237 void Set(const std::string& path, Value* in_value);
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);
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);
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 void SetStringWithoutPathExpansion(const std::string& path,
261 const string16& in_value);
263 // Gets the Value associated with the given path starting from this object.
264 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
265 // into the next DictionaryValue down. If the path can be resolved
266 // successfully, the value for the last key in the path will be returned
267 // through the |out_value| parameter, and the function will return true.
268 // Otherwise, it will return false and |out_value| will be untouched.
269 // Note that the dictionary always owns the value that's returned.
270 // |out_value| is optional and will only be set if non-NULL.
271 bool Get(const std::string& path, const Value** out_value) const;
272 bool Get(const std::string& path, Value** out_value);
274 // These are convenience forms of Get(). The value will be retrieved
275 // and the return value will be true if the path is valid and the value at
276 // the end of the path can be returned in the form specified.
277 // |out_value| is optional and will only be set if non-NULL.
278 bool GetBoolean(const std::string& path, bool* out_value) const;
279 bool GetInteger(const std::string& path, int* out_value) const;
280 // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
281 // doubles.
282 bool GetDouble(const std::string& path, double* out_value) const;
283 bool GetString(const std::string& path, std::string* out_value) const;
284 bool GetString(const std::string& path, string16* out_value) const;
285 bool GetStringASCII(const std::string& path, std::string* out_value) const;
286 bool GetBinary(const std::string& path, const BinaryValue** out_value) const;
287 bool GetBinary(const std::string& path, BinaryValue** out_value);
288 bool GetDictionary(const std::string& path,
289 const DictionaryValue** out_value) const;
290 bool GetDictionary(const std::string& path, DictionaryValue** out_value);
291 bool GetList(const std::string& path, const ListValue** out_value) const;
292 bool GetList(const std::string& path, ListValue** out_value);
294 // Like Get(), but without special treatment of '.'. This allows e.g. URLs to
295 // be used as paths.
296 bool GetWithoutPathExpansion(const std::string& key,
297 const Value** out_value) const;
298 bool GetWithoutPathExpansion(const std::string& key, Value** out_value);
299 bool GetBooleanWithoutPathExpansion(const std::string& key,
300 bool* out_value) const;
301 bool GetIntegerWithoutPathExpansion(const std::string& key,
302 int* out_value) const;
303 bool GetDoubleWithoutPathExpansion(const std::string& key,
304 double* out_value) const;
305 bool GetStringWithoutPathExpansion(const std::string& key,
306 std::string* out_value) const;
307 bool GetStringWithoutPathExpansion(const std::string& key,
308 string16* out_value) const;
309 bool GetDictionaryWithoutPathExpansion(
310 const std::string& key,
311 const DictionaryValue** out_value) const;
312 bool GetDictionaryWithoutPathExpansion(const std::string& key,
313 DictionaryValue** out_value);
314 bool GetListWithoutPathExpansion(const std::string& key,
315 const ListValue** out_value) const;
316 bool GetListWithoutPathExpansion(const std::string& key,
317 ListValue** out_value);
319 // Removes the Value with the specified path from this dictionary (or one
320 // of its child dictionaries, if the path is more than just a local key).
321 // If |out_value| is non-NULL, the removed Value will be passed out via
322 // |out_value|. If |out_value| is NULL, the removed value will be deleted.
323 // This method returns true if |path| is a valid path; otherwise it will
324 // return false and the DictionaryValue object will be unchanged.
325 virtual bool Remove(const std::string& path, scoped_ptr<Value>* out_value);
327 // Like Remove(), but without special treatment of '.'. This allows e.g. URLs
328 // to be used as paths.
329 virtual bool RemoveWithoutPathExpansion(const std::string& key,
330 scoped_ptr<Value>* out_value);
332 // Removes a path, clearing out all dictionaries on |path| that remain empty
333 // after removing the value at |path|.
334 virtual bool RemovePath(const std::string& path,
335 scoped_ptr<Value>* out_value);
337 // Makes a copy of |this| but doesn't include empty dictionaries and lists in
338 // the copy. This never returns NULL, even if |this| itself is empty.
339 DictionaryValue* DeepCopyWithoutEmptyChildren() const;
341 // Merge |dictionary| into this dictionary. This is done recursively, i.e. any
342 // sub-dictionaries will be merged as well. In case of key collisions, the
343 // passed in dictionary takes precedence and data already present will be
344 // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
345 // be freed any time after this call.
346 void MergeDictionary(const DictionaryValue* dictionary);
348 // Swaps contents with the |other| dictionary.
349 virtual void Swap(DictionaryValue* other);
351 // This class provides an iterator over both keys and values in the
352 // dictionary. It can't be used to modify the dictionary.
353 class BASE_EXPORT Iterator {
354 public:
355 explicit Iterator(const DictionaryValue& target);
356 ~Iterator();
358 bool IsAtEnd() const { return it_ == target_.dictionary_.end(); }
359 void Advance() { ++it_; }
361 const std::string& key() const { return it_->first; }
362 const Value& value() const { return *it_->second; }
364 private:
365 const DictionaryValue& target_;
366 ValueMap::const_iterator it_;
369 // Overridden from Value:
370 DictionaryValue* DeepCopy() const override;
371 bool Equals(const Value* other) const override;
373 private:
374 ValueMap dictionary_;
376 DISALLOW_COPY_AND_ASSIGN(DictionaryValue);
379 // This type of Value represents a list of other Value values.
380 class BASE_EXPORT ListValue : public Value {
381 public:
382 typedef ValueVector::iterator iterator;
383 typedef ValueVector::const_iterator const_iterator;
385 ListValue();
386 ~ListValue() override;
388 // Clears the contents of this ListValue
389 void Clear();
391 // Returns the number of Values in this list.
392 size_t GetSize() const { return list_.size(); }
394 // Returns whether the list is empty.
395 bool empty() const { return list_.empty(); }
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);
404 // Gets the Value at the given index. Modifies |out_value| (and returns true)
405 // only if the index falls within the current list range.
406 // Note that the list always owns the Value passed out via |out_value|.
407 // |out_value| is optional and will only be set if non-NULL.
408 bool Get(size_t index, const Value** out_value) const;
409 bool Get(size_t index, Value** out_value);
411 // Convenience forms of Get(). Modifies |out_value| (and returns true)
412 // only if the index is valid and the Value at that index can be returned
413 // in the specified form.
414 // |out_value| is optional and will only be set if non-NULL.
415 bool GetBoolean(size_t index, bool* out_value) const;
416 bool GetInteger(size_t index, int* out_value) const;
417 // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
418 // doubles.
419 bool GetDouble(size_t index, double* out_value) const;
420 bool GetString(size_t index, std::string* out_value) const;
421 bool GetString(size_t index, string16* out_value) const;
422 bool GetBinary(size_t index, const BinaryValue** out_value) const;
423 bool GetBinary(size_t index, BinaryValue** out_value);
424 bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
425 bool GetDictionary(size_t index, DictionaryValue** out_value);
426 bool GetList(size_t index, const ListValue** out_value) const;
427 bool GetList(size_t index, ListValue** out_value);
429 // Removes the Value with the specified index from this list.
430 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
431 // passed out via |out_value|. If |out_value| is NULL, the removed value will
432 // be deleted. This method returns true if |index| is valid; otherwise
433 // it will return false and the ListValue object will be unchanged.
434 virtual bool Remove(size_t index, scoped_ptr<Value>* out_value);
436 // Removes the first instance of |value| found in the list, if any, and
437 // deletes it. |index| is the location where |value| was found. Returns false
438 // if not found.
439 bool Remove(const Value& value, size_t* index);
441 // Removes the element at |iter|. If |out_value| is NULL, the value will be
442 // deleted, otherwise ownership of the value is passed back to the caller.
443 // Returns an iterator pointing to the location of the element that
444 // followed the erased element.
445 iterator Erase(iterator iter, scoped_ptr<Value>* out_value);
447 // Appends a Value to the end of the list.
448 void Append(Value* in_value);
450 // Convenience forms of Append.
451 void AppendBoolean(bool in_value);
452 void AppendInteger(int in_value);
453 void AppendDouble(double in_value);
454 void AppendString(const std::string& in_value);
455 void AppendString(const string16& in_value);
456 void AppendStrings(const std::vector<std::string>& in_values);
457 void AppendStrings(const std::vector<string16>& in_values);
459 // Appends a Value if it's not already present. Takes ownership of the
460 // |in_value|. Returns true if successful, or false if the value was already
461 // present. If the value was already present the |in_value| is deleted.
462 bool AppendIfNotPresent(Value* in_value);
464 // Insert a Value at index.
465 // Returns true if successful, or false if the index was out of range.
466 bool Insert(size_t index, Value* in_value);
468 // Searches for the first instance of |value| in the list using the Equals
469 // method of the Value type.
470 // Returns a const_iterator to the found item or to end() if none exists.
471 const_iterator Find(const Value& value) const;
473 // Swaps contents with the |other| list.
474 virtual void Swap(ListValue* other);
476 // Iteration.
477 iterator begin() { return list_.begin(); }
478 iterator end() { return list_.end(); }
480 const_iterator begin() const { return list_.begin(); }
481 const_iterator end() const { return list_.end(); }
483 // Overridden from Value:
484 bool GetAsList(ListValue** out_value) override;
485 bool GetAsList(const ListValue** out_value) const override;
486 ListValue* DeepCopy() const override;
487 bool Equals(const Value* other) const override;
489 private:
490 ValueVector list_;
492 DISALLOW_COPY_AND_ASSIGN(ListValue);
495 // This interface is implemented by classes that know how to serialize and
496 // deserialize Value objects.
497 class BASE_EXPORT ValueSerializer {
498 public:
499 virtual ~ValueSerializer();
501 virtual bool Serialize(const Value& root) = 0;
503 // This method deserializes the subclass-specific format into a Value object.
504 // If the return value is non-NULL, the caller takes ownership of returned
505 // Value. If the return value is NULL, and if error_code is non-NULL,
506 // error_code will be set with the underlying error.
507 // If |error_message| is non-null, it will be filled in with a formatted
508 // error message including the location of the error if appropriate.
509 virtual Value* Deserialize(int* error_code, std::string* error_str) = 0;
512 // Stream operator so Values can be used in assertion statements. In order that
513 // gtest uses this operator to print readable output on test failures, we must
514 // override each specific type. Otherwise, the default template implementation
515 // is preferred over an upcast.
516 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
518 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
519 const FundamentalValue& value) {
520 return out << static_cast<const Value&>(value);
523 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
524 const StringValue& value) {
525 return out << static_cast<const Value&>(value);
528 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
529 const DictionaryValue& value) {
530 return out << static_cast<const Value&>(value);
533 BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
534 const ListValue& value) {
535 return out << static_cast<const Value&>(value);
538 } // namespace base
540 #endif // BASE_VALUES_H_