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