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// NOTE: A Value parameter that is always a Value::STRING should just be passed
18// as a std::string. Similarly for Values that are always Value::DICTIONARY
19// (should be flat_map), Value::LIST (should be std::vector), et cetera.
20
21#ifndef BASE_VALUES_H_
22#define BASE_VALUES_H_
23
24#include <stddef.h>
25#include <stdint.h>
26
27#include <iosfwd>
28#include <map>
29#include <memory>
30#include <string>
31#include <utility>
32#include <vector>
33
34#include "base/base_export.h"
35#include "base/containers/flat_map.h"
36#include "base/containers/span.h"
37#include "base/macros.h"
38#include "base/strings/string16.h"
39#include "base/strings/string_piece.h"
40#include "base/value_iterators.h"
41
42namespace base {
43
44class DictionaryValue;
45class ListValue;
46class Value;
47
48// The Value class is the base class for Values. A Value can be instantiated
49// via passing the appropriate type or backing storage to the constructor.
50//
51// See the file-level comment above for more information.
52//
53// base::Value is currently in the process of being refactored. Design doc:
54// https://docs.google.com/document/d/1uDLu5uTRlCWePxQUEHc8yNQdEoE1BDISYdpggWEABnw
55//
56// Previously (which is how most code that currently exists is written), Value
57// used derived types to implement the individual data types, and base::Value
58// was just a base class to refer to them. This required everything be heap
59// allocated.
60//
61// OLD WAY:
62//
63// std::unique_ptr<base::Value> GetFoo() {
64// std::unique_ptr<DictionaryValue> dict;
65// dict->SetString("mykey", foo);
66// return dict;
67// }
68//
69// The new design makes base::Value a variant type that holds everything in
70// a union. It is now recommended to pass by value with std::move rather than
71// use heap allocated values. The DictionaryValue and ListValue subclasses
72// exist only as a compatibility shim that we're in the process of removing.
73//
74// NEW WAY:
75//
76// base::Value GetFoo() {
77// base::Value dict(base::Value::Type::DICTIONARY);
78// dict.SetKey("mykey", base::Value(foo));
79// return dict;
80// }
81class BASE_EXPORT Value {
82 public:
83 using BlobStorage = std::vector<uint8_t>;
84 using DictStorage = flat_map<std::string, std::unique_ptr<Value>>;
85 using ListStorage = std::vector<Value>;
86 // See technical note below explaining why this is used.
87 using DoubleStorage = struct { alignas(4) char v[sizeof(double)]; };
88
89 enum class Type : unsigned char {
90 NONE = 0,
91 BOOLEAN,
92 INTEGER,
93 DOUBLE,
94 STRING,
95 BINARY,
96 DICTIONARY,
97 LIST,
98 // TODO(crbug.com/859477): Remove once root cause is found.
99 DEAD
100 // Note: Do not add more types. See the file-level comment above for why.
101 };
102
103 // For situations where you want to keep ownership of your buffer, this
104 // factory method creates a new BinaryValue by copying the contents of the
105 // buffer that's passed in.
106 // DEPRECATED, use std::make_unique<Value>(const BlobStorage&) instead.
107 // TODO(crbug.com/646113): Delete this and migrate callsites.
108 static std::unique_ptr<Value> CreateWithCopiedBuffer(const char* buffer,
109 size_t size);
110
111 // Adaptors for converting from the old way to the new way and vice versa.
112 static Value FromUniquePtrValue(std::unique_ptr<Value> val);
113 static std::unique_ptr<Value> ToUniquePtrValue(Value val);
114
115 Value(Value&& that) noexcept;
116 Value() noexcept {} // A null value
117 // Fun fact: using '= default' above instead of '{}' does not work because
118 // the compiler complains that the default constructor was deleted since
119 // the inner union contains fields with non-default constructors.
120
121 // Value's copy constructor and copy assignment operator are deleted. Use this
122 // to obtain a deep copy explicitly.
123 Value Clone() const;
124
125 explicit Value(Type type);
126 explicit Value(bool in_bool);
127 explicit Value(int in_int);
128 explicit Value(double in_double);
129
130 // Value(const char*) and Value(const char16*) are required despite
131 // Value(StringPiece) and Value(StringPiece16) because otherwise the
132 // compiler will choose the Value(bool) constructor for these arguments.
133 // Value(std::string&&) allow for efficient move construction.
134 explicit Value(const char* in_string);
135 explicit Value(StringPiece in_string);
136 explicit Value(std::string&& in_string) noexcept;
137 explicit Value(const char16* in_string16);
138 explicit Value(StringPiece16 in_string16);
139
140 explicit Value(const std::vector<char>& in_blob);
141 explicit Value(base::span<const uint8_t> in_blob);
142 explicit Value(BlobStorage&& in_blob) noexcept;
143
144 explicit Value(const DictStorage& in_dict);
145 explicit Value(DictStorage&& in_dict) noexcept;
146
147 explicit Value(const ListStorage& in_list);
148 explicit Value(ListStorage&& in_list) noexcept;
149
150 Value& operator=(Value&& that) noexcept;
151
152 ~Value();
153
154 // Returns the name for a given |type|.
155 static const char* GetTypeName(Type type);
156
157 // Returns the type of the value stored by the current Value object.
158 Type type() const { return type_; }
159
160 // Returns true if the current object represents a given type.
161 bool is_none() const { return type() == Type::NONE; }
162 bool is_bool() const { return type() == Type::BOOLEAN; }
163 bool is_int() const { return type() == Type::INTEGER; }
164 bool is_double() const { return type() == Type::DOUBLE; }
165 bool is_string() const { return type() == Type::STRING; }
166 bool is_blob() const { return type() == Type::BINARY; }
167 bool is_dict() const { return type() == Type::DICTIONARY; }
168 bool is_list() const { return type() == Type::LIST; }
169
170 // These will all CHECK if the type doesn't match.
171 bool GetBool() const;
172 int GetInt() const;
173 double GetDouble() const; // Implicitly converts from int if necessary.
174 const std::string& GetString() const;
175 const BlobStorage& GetBlob() const;
176
177 ListStorage& GetList();
178 const ListStorage& GetList() const;
179
180 // |FindKey| looks up |key| in the underlying dictionary. If found, it returns
181 // a pointer to the element. Otherwise it returns nullptr.
182 // returned. Callers are expected to perform a check against null before using
183 // the pointer.
184 // Note: This CHECKs if type() is not Type::DICTIONARY.
185 //
186 // Example:
187 // auto* found = FindKey("foo");
188 Value* FindKey(StringPiece key);
189 const Value* FindKey(StringPiece key) const;
190
191 // |FindKeyOfType| is similar to |FindKey|, but it also requires the found
192 // value to have type |type|. If no type is found, or the found value is of a
193 // different type nullptr is returned.
194 // Callers are expected to perform a check against null before using the
195 // pointer.
196 // Note: This CHECKs if type() is not Type::DICTIONARY.
197 //
198 // Example:
199 // auto* found = FindKey("foo", Type::DOUBLE);
200 Value* FindKeyOfType(StringPiece key, Type type);
201 const Value* FindKeyOfType(StringPiece key, Type type) const;
202
203 // These are convenience forms of |FindKey|. They return |base::nullopt| if
204 // the value is not found or doesn't have the type specified in the
205 // function's name.
206 base::Optional<bool> FindBoolKey(StringPiece key) const;
207 base::Optional<int> FindIntKey(StringPiece key) const;
208 // Note FindDoubleKey() will auto-convert INTEGER keys to their double
209 // value, for consistency with GetDouble().
210 base::Optional<double> FindDoubleKey(StringPiece key) const;
211
212 // |FindStringKey| returns |nullptr| if value is not found or not a string.
213 const std::string* FindStringKey(StringPiece key) const;
214
215 // Returns nullptr is value is not found or not a binary.
216 const BlobStorage* FindBlobKey(StringPiece key) const;
217
218 // Returns nullptr if value is not found or not a dictionary.
219 const Value* FindDictKey(StringPiece key) const;
220 Value* FindDictKey(StringPiece key);
221
222 // Returns nullptr if value is not found or not a list.
223 const Value* FindListKey(StringPiece key) const;
224 Value* FindListKey(StringPiece key);
225
226 // |SetKey| looks up |key| in the underlying dictionary and sets the mapped
227 // value to |value|. If |key| could not be found, a new element is inserted.
228 // A pointer to the modified item is returned.
229 // Note: This CHECKs if type() is not Type::DICTIONARY.
230 // Note: Prefer Set<Type>Key() for simple values.
231 //
232 // Example:
233 // SetKey("foo", std::move(myvalue));
234 Value* SetKey(StringPiece key, Value&& value);
235 // This overload results in a performance improvement for std::string&&.
236 Value* SetKey(std::string&& key, Value&& value);
237 // This overload is necessary to avoid ambiguity for const char* arguments.
238 Value* SetKey(const char* key, Value&& value);
239
240 // |Set<Type>Key| looks up |key| in the underlying dictionary and associates
241 // a corresponding Value() constructed from the second parameter. Compared
242 // to SetKey(), this avoids un-necessary temporary Value() creation, as well
243 // ambiguities in the value type.
244 Value* SetBoolKey(StringPiece key, bool val);
245 Value* SetIntKey(StringPiece key, int val);
246 Value* SetDoubleKey(StringPiece key, double val);
247 Value* SetStringKey(StringPiece key, StringPiece val);
248 // NOTE: These two overloads are provided as performance / code generation
249 // optimizations.
250 Value* SetStringKey(StringPiece key, const char* val);
251 Value* SetStringKey(StringPiece key, std::string&& val);
252 Value* SetStringKey(StringPiece key, StringPiece16 val);
253
254 // This attempts to remove the value associated with |key|. In case of
255 // failure, e.g. the key does not exist, false is returned and the underlying
256 // dictionary is not changed. In case of success, |key| is deleted from the
257 // dictionary and the method returns true.
258 // Note: This CHECKs if type() is not Type::DICTIONARY.
259 //
260 // Example:
261 // bool success = dict.RemoveKey("foo");
262 bool RemoveKey(StringPiece key);
263
264 // This attempts to extract the value associated with |key|. In case of
265 // failure, e.g. the key does not exist, nullopt is returned and the
266 // underlying dictionary is not changed. In case of success, |key| is deleted
267 // from the dictionary and the method returns the extracted Value.
268 // Note: This CHECKs if type() is not Type::DICTIONARY.
269 //
270 // Example:
271 // Optional<Value> maybe_value = dict.ExtractKey("foo");
272 Optional<Value> ExtractKey(StringPiece key);
273
274 // Searches a hierarchy of dictionary values for a given value. If a path
275 // of dictionaries exist, returns the item at that path. If any of the path
276 // components do not exist or if any but the last path components are not
277 // dictionaries, returns nullptr.
278 //
279 // The type of the leaf Value is not checked.
280 //
281 // Implementation note: This can't return an iterator because the iterator
282 // will actually be into another Value, so it can't be compared to iterators
283 // from this one (in particular, the DictItems().end() iterator).
284 //
285 // This version takes a StringPiece for the path, using dots as separators.
286 // Example:
287 // auto* found = FindPath("foo.bar");
288 Value* FindPath(StringPiece path);
289 const Value* FindPath(StringPiece path) const;
290
291 // There are also deprecated versions that take the path parameter
292 // as either a std::initializer_list<StringPiece> or a
293 // span<const StringPiece>. The latter is useful to use a
294 // std::vector<std::string> as a parameter but creates huge dynamic
295 // allocations and should be avoided!
296 // Note: If there is only one component in the path, use FindKey() instead.
297 //
298 // Example:
299 // std::vector<StringPiece> components = ...
300 // auto* found = FindPath(components);
301 Value* FindPath(std::initializer_list<StringPiece> path);
302 Value* FindPath(span<const StringPiece> path);
303 const Value* FindPath(std::initializer_list<StringPiece> path) const;
304 const Value* FindPath(span<const StringPiece> path) const;
305
306 // Like FindPath() but will only return the value if the leaf Value type
307 // matches the given type. Will return nullptr otherwise.
308 // Note: Prefer Find<Type>Path() for simple values.
309 //
310 // Note: If there is only one component in the path, use FindKeyOfType()
311 // instead for slightly better performance.
312 Value* FindPathOfType(StringPiece path, Type type);
313 const Value* FindPathOfType(StringPiece path, Type type) const;
314
315 // Convenience accessors used when the expected type of a value is known.
316 // Similar to Find<Type>Key() but accepts paths instead of keys.
317 base::Optional<bool> FindBoolPath(StringPiece path) const;
318 base::Optional<int> FindIntPath(StringPiece path) const;
319 base::Optional<double> FindDoublePath(StringPiece path) const;
320 const std::string* FindStringPath(StringPiece path) const;
321 const BlobStorage* FindBlobPath(StringPiece path) const;
322 Value* FindDictPath(StringPiece path);
323 const Value* FindDictPath(StringPiece path) const;
324 Value* FindListPath(StringPiece path);
325 const Value* FindListPath(StringPiece path) const;
326
327 // The following forms are deprecated too, use the ones that take the path
328 // as a single StringPiece instead.
329 Value* FindPathOfType(std::initializer_list<StringPiece> path, Type type);
330 Value* FindPathOfType(span<const StringPiece> path, Type type);
331 const Value* FindPathOfType(std::initializer_list<StringPiece> path,
332 Type type) const;
333 const Value* FindPathOfType(span<const StringPiece> path, Type type) const;
334
335 // Sets the given path, expanding and creating dictionary keys as necessary.
336 //
337 // If the current value is not a dictionary, the function returns nullptr. If
338 // path components do not exist, they will be created. If any but the last
339 // components matches a value that is not a dictionary, the function will fail
340 // (it will not overwrite the value) and return nullptr. The last path
341 // component will be unconditionally overwritten if it exists, and created if
342 // it doesn't.
343 //
344 // Example:
345 // value.SetPath("foo.bar", std::move(myvalue));
346 //
347 // Note: If there is only one component in the path, use SetKey() instead.
348 // Note: Using Set<Type>Path() might be more convenient and efficient.
349 Value* SetPath(StringPiece path, Value&& value);
350
351 // These setters are more convenient and efficient than the corresponding
352 // SetPath(...) call.
353 Value* SetBoolPath(StringPiece path, bool value);
354 Value* SetIntPath(StringPiece path, int value);
355 Value* SetDoublePath(StringPiece path, double value);
356 Value* SetStringPath(StringPiece path, StringPiece value);
357 Value* SetStringPath(StringPiece path, const char* value);
358 Value* SetStringPath(StringPiece path, std::string&& value);
359 Value* SetStringPath(StringPiece path, StringPiece16 value);
360
361 // Deprecated: use the ones that take a StringPiece path parameter instead.
362 Value* SetPath(std::initializer_list<StringPiece> path, Value&& value);
363 Value* SetPath(span<const StringPiece> path, Value&& value);
364
365 // Tries to remove a Value at the given path.
366 //
367 // If the current value is not a dictionary or any path component does not
368 // exist, this operation fails, leaves underlying Values untouched and returns
369 // |false|. In case intermediate dictionaries become empty as a result of this
370 // path removal, they will be removed as well.
371 // Note: If there is only one component in the path, use ExtractKey() instead.
372 //
373 // Example:
374 // bool success = value.RemovePath("foo.bar");
375 bool RemovePath(StringPiece path);
376
377 // Deprecated versions
378 bool RemovePath(std::initializer_list<StringPiece> path);
379 bool RemovePath(span<const StringPiece> path);
380
381 // Tries to extract a Value at the given path.
382 //
383 // If the current value is not a dictionary or any path component does not
384 // exist, this operation fails, leaves underlying Values untouched and returns
385 // nullopt. In case intermediate dictionaries become empty as a result of this
386 // path removal, they will be removed as well. Returns the extracted value on
387 // success.
388 // Note: If there is only one component in the path, use ExtractKey() instead.
389 //
390 // Example:
391 // Optional<Value> maybe_value = value.ExtractPath("foo.bar");
392 Optional<Value> ExtractPath(StringPiece path);
393
394 using dict_iterator_proxy = detail::dict_iterator_proxy;
395 using const_dict_iterator_proxy = detail::const_dict_iterator_proxy;
396
397 // |DictItems| returns a proxy object that exposes iterators to the underlying
398 // dictionary. These are intended for iteration over all items in the
399 // dictionary and are compatible with for-each loops and standard library
400 // algorithms.
401 // Note: These CHECK if type() is not Type::DICTIONARY.
402 dict_iterator_proxy DictItems();
403 const_dict_iterator_proxy DictItems() const;
404
405 // Returns the size of the dictionary, and if the dictionary is empty.
406 // Note: These CHECK if type() is not Type::DICTIONARY.
407 size_t DictSize() const;
408 bool DictEmpty() const;
409
410 // Merge |dictionary| into this value. This is done recursively, i.e. any
411 // sub-dictionaries will be merged as well. In case of key collisions, the
412 // passed in dictionary takes precedence and data already present will be
413 // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
414 // be freed any time after this call.
415 // Note: This CHECKs if type() or dictionary->type() is not Type::DICTIONARY.
416 void MergeDictionary(const Value* dictionary);
417
418 // These methods allow the convenient retrieval of the contents of the Value.
419 // If the current object can be converted into the given type, the value is
420 // returned through the |out_value| parameter and true is returned;
421 // otherwise, false is returned and |out_value| is unchanged.
422 // DEPRECATED, use GetBool() instead.
423 bool GetAsBoolean(bool* out_value) const;
424 // DEPRECATED, use GetInt() instead.
425 bool GetAsInteger(int* out_value) const;
426 // DEPRECATED, use GetDouble() instead.
427 bool GetAsDouble(double* out_value) const;
428 // DEPRECATED, use GetString() instead.
429 bool GetAsString(std::string* out_value) const;
430 bool GetAsString(string16* out_value) const;
431 bool GetAsString(const Value** out_value) const;
432 bool GetAsString(StringPiece* out_value) const;
433 // ListValue::From is the equivalent for std::unique_ptr conversions.
434 // DEPRECATED, use GetList() instead.
435 bool GetAsList(ListValue** out_value);
436 bool GetAsList(const ListValue** out_value) const;
437 // DictionaryValue::From is the equivalent for std::unique_ptr conversions.
438 bool GetAsDictionary(DictionaryValue** out_value);
439 bool GetAsDictionary(const DictionaryValue** out_value) const;
440 // Note: Do not add more types. See the file-level comment above for why.
441
442 // This creates a deep copy of the entire Value tree, and returns a pointer
443 // to the copy. The caller gets ownership of the copy, of course.
444 // Subclasses return their own type directly in their overrides;
445 // this works because C++ supports covariant return types.
446 // DEPRECATED, use Value::Clone() instead.
447 // TODO(crbug.com/646113): Delete this and migrate callsites.
448 Value* DeepCopy() const;
449 // DEPRECATED, use Value::Clone() instead.
450 // TODO(crbug.com/646113): Delete this and migrate callsites.
451 std::unique_ptr<Value> CreateDeepCopy() const;
452
453 // Comparison operators so that Values can easily be used with standard
454 // library algorithms and associative containers.
455 BASE_EXPORT friend bool operator==(const Value& lhs, const Value& rhs);
456 BASE_EXPORT friend bool operator!=(const Value& lhs, const Value& rhs);
457 BASE_EXPORT friend bool operator<(const Value& lhs, const Value& rhs);
458 BASE_EXPORT friend bool operator>(const Value& lhs, const Value& rhs);
459 BASE_EXPORT friend bool operator<=(const Value& lhs, const Value& rhs);
460 BASE_EXPORT friend bool operator>=(const Value& lhs, const Value& rhs);
461
462 // Compares if two Value objects have equal contents.
463 // DEPRECATED, use operator==(const Value& lhs, const Value& rhs) instead.
464 // TODO(crbug.com/646113): Delete this and migrate callsites.
465 bool Equals(const Value* other) const;
466
467 // Estimates dynamic memory usage.
468 // See base/trace_event/memory_usage_estimator.h for more info.
469 size_t EstimateMemoryUsage() const;
470
471 protected:
472 // Special case for doubles, which are aligned to 8 bytes on some
473 // 32-bit architectures. In this case, a simple declaration as a
474 // double member would make the whole union 8 byte-aligned, which
475 // would also force 4 bytes of wasted padding space before it in
476 // the Value layout.
477 //
478 // To override this, store the value as an array of 32-bit integers, and
479 // perform the appropriate bit casts when reading / writing to it.
480 Type type_ = Type::NONE;
481
482 union {
483 bool bool_value_;
484 int int_value_;
485 DoubleStorage double_value_;
486 std::string string_value_;
487 BlobStorage binary_value_;
488 DictStorage dict_;
489 ListStorage list_;
490 };
491
492 private:
493 friend class ValuesTest_SizeOfValue_Test;
494 double AsDoubleInternal() const;
495 void InternalMoveConstructFrom(Value&& that);
496 void InternalCleanup();
497
498 // NOTE: Using a movable reference here is done for performance (it avoids
499 // creating + moving + destroying a temporary unique ptr).
500 Value* SetKeyInternal(StringPiece key, std::unique_ptr<Value>&& val_ptr);
501 Value* SetPathInternal(StringPiece path, std::unique_ptr<Value>&& value_ptr);
502
503 DISALLOW_COPY_AND_ASSIGN(Value);
504};
505
506// DictionaryValue provides a key-value dictionary with (optional) "path"
507// parsing for recursive access; see the comment at the top of the file. Keys
508// are |std::string|s and should be UTF-8 encoded.
509class BASE_EXPORT DictionaryValue : public Value {
510 public:
511 using const_iterator = DictStorage::const_iterator;
512 using iterator = DictStorage::iterator;
513
514 // Returns |value| if it is a dictionary, nullptr otherwise.
515 static std::unique_ptr<DictionaryValue> From(std::unique_ptr<Value> value);
516
517 DictionaryValue();
518 explicit DictionaryValue(const DictStorage& in_dict);
519 explicit DictionaryValue(DictStorage&& in_dict) noexcept;
520
521 // Returns true if the current dictionary has a value for the given key.
522 // DEPRECATED, use Value::FindKey(key) instead.
523 bool HasKey(StringPiece key) const;
524
525 // Returns the number of Values in this dictionary.
526 size_t size() const { return dict_.size(); }
527
528 // Returns whether the dictionary is empty.
529 bool empty() const { return dict_.empty(); }
530
531 // Clears any current contents of this dictionary.
532 void Clear();
533
534 // Sets the Value associated with the given path starting from this object.
535 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
536 // into the next DictionaryValue down. Obviously, "." can't be used
537 // within a key, but there are no other restrictions on keys.
538 // If the key at any step of the way doesn't exist, or exists but isn't
539 // a DictionaryValue, a new DictionaryValue will be created and attached
540 // to the path in that location. |in_value| must be non-null.
541 // Returns a pointer to the inserted value.
542 // DEPRECATED, use Value::SetPath(path, value) instead.
543 Value* Set(StringPiece path, std::unique_ptr<Value> in_value);
544
545 // Convenience forms of Set(). These methods will replace any existing
546 // value at that path, even if it has a different type.
547 // DEPRECATED, use Value::SetBoolKey() or Value::SetBoolPath().
548 Value* SetBoolean(StringPiece path, bool in_value);
549 // DEPRECATED, use Value::SetIntPath().
550 Value* SetInteger(StringPiece path, int in_value);
551 // DEPRECATED, use Value::SetDoublePath().
552 Value* SetDouble(StringPiece path, double in_value);
553 // DEPRECATED, use Value::SetStringPath().
554 Value* SetString(StringPiece path, StringPiece in_value);
555 // DEPRECATED, use Value::SetStringPath().
556 Value* SetString(StringPiece path, const string16& in_value);
557 // DEPRECATED, use Value::SetPath() or Value::SetDictPath()
558 DictionaryValue* SetDictionary(StringPiece path,
559 std::unique_ptr<DictionaryValue> in_value);
560 // DEPRECATED, use Value::SetPath() or Value::SetListPath()
561 ListValue* SetList(StringPiece path, std::unique_ptr<ListValue> in_value);
562
563 // Like Set(), but without special treatment of '.'. This allows e.g. URLs to
564 // be used as paths.
565 // DEPRECATED, use Value::SetKey(key, value) instead.
566 Value* SetWithoutPathExpansion(StringPiece key,
567 std::unique_ptr<Value> in_value);
568
569 // Gets the Value associated with the given path starting from this object.
570 // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
571 // into the next DictionaryValue down. If the path can be resolved
572 // successfully, the value for the last key in the path will be returned
573 // through the |out_value| parameter, and the function will return true.
574 // Otherwise, it will return false and |out_value| will be untouched.
575 // Note that the dictionary always owns the value that's returned.
576 // |out_value| is optional and will only be set if non-NULL.
577 // DEPRECATED, use Value::FindPath(path) instead.
578 bool Get(StringPiece path, const Value** out_value) const;
579 // DEPRECATED, use Value::FindPath(path) instead.
580 bool Get(StringPiece path, Value** out_value);
581
582 // These are convenience forms of Get(). The value will be retrieved
583 // and the return value will be true if the path is valid and the value at
584 // the end of the path can be returned in the form specified.
585 // |out_value| is optional and will only be set if non-NULL.
586 // DEPRECATED, use Value::FindBoolPath(path) instead.
587 bool GetBoolean(StringPiece path, bool* out_value) const;
588 // DEPRECATED, use Value::FindIntPath(path) isntead.
589 bool GetInteger(StringPiece path, int* out_value) const;
590 // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as
591 // doubles.
592 // DEPRECATED, use Value::FindDoublePath(path).
593 bool GetDouble(StringPiece path, double* out_value) const;
594 // DEPRECATED, use Value::FindStringPath(path) instead.
595 bool GetString(StringPiece path, std::string* out_value) const;
596 // DEPRECATED, use Value::FindStringPath(path) instead.
597 bool GetString(StringPiece path, string16* out_value) const;
598 // DEPRECATED, use Value::FindString(path) and IsAsciiString() instead.
599 bool GetStringASCII(StringPiece path, std::string* out_value) const;
600 // DEPRECATED, use Value::FindBlobPath(path) instead.
601 bool GetBinary(StringPiece path, const Value** out_value) const;
602 // DEPRECATED, use Value::FindBlobPath(path) instead.
603 bool GetBinary(StringPiece path, Value** out_value);
604 // DEPRECATED, use Value::FindPath(path) and Value's Dictionary API instead.
605 bool GetDictionary(StringPiece path,
606 const DictionaryValue** out_value) const;
607 // DEPRECATED, use Value::FindPath(path) and Value's Dictionary API instead.
608 bool GetDictionary(StringPiece path, DictionaryValue** out_value);
609 // DEPRECATED, use Value::FindPath(path) and Value::GetList() instead.
610 bool GetList(StringPiece path, const ListValue** out_value) const;
611 // DEPRECATED, use Value::FindPath(path) and Value::GetList() instead.
612 bool GetList(StringPiece path, ListValue** out_value);
613
614 // Like Get(), but without special treatment of '.'. This allows e.g. URLs to
615 // be used as paths.
616 // DEPRECATED, use Value::FindKey(key) instead.
617 bool GetWithoutPathExpansion(StringPiece key, const Value** out_value) const;
618 // DEPRECATED, use Value::FindKey(key) instead.
619 bool GetWithoutPathExpansion(StringPiece key, Value** out_value);
620 // DEPRECATED, use Value::FindBoolKey(key) instead.
621 bool GetBooleanWithoutPathExpansion(StringPiece key, bool* out_value) const;
622 // DEPRECATED, use Value::FindIntKey(key) instead.
623 bool GetIntegerWithoutPathExpansion(StringPiece key, int* out_value) const;
624 // DEPRECATED, use Value::FindDoubleKey(key) instead.
625 bool GetDoubleWithoutPathExpansion(StringPiece key, double* out_value) const;
626 // DEPRECATED, use Value::FindStringKey(key) instead.
627 bool GetStringWithoutPathExpansion(StringPiece key,
628 std::string* out_value) const;
629 // DEPRECATED, use Value::FindStringKey(key) and UTF8ToUTF16() instead.
630 bool GetStringWithoutPathExpansion(StringPiece key,
631 string16* out_value) const;
632 // DEPRECATED, use Value::FindDictKey(key) instead.
633 bool GetDictionaryWithoutPathExpansion(
634 StringPiece key,
635 const DictionaryValue** out_value) const;
636 // DEPRECATED, use Value::FindDictKey(key) instead.
637 bool GetDictionaryWithoutPathExpansion(StringPiece key,
638 DictionaryValue** out_value);
639 // DEPRECATED, use Value::FindListKey(key) instead.
640 bool GetListWithoutPathExpansion(StringPiece key,
641 const ListValue** out_value) const;
642 // DEPRECATED, use Value::FindListKey(key) instead.
643 bool GetListWithoutPathExpansion(StringPiece key, ListValue** out_value);
644
645 // Removes the Value with the specified path from this dictionary (or one
646 // of its child dictionaries, if the path is more than just a local key).
647 // If |out_value| is non-NULL, the removed Value will be passed out via
648 // |out_value|. If |out_value| is NULL, the removed value will be deleted.
649 // This method returns true if |path| is a valid path; otherwise it will
650 // return false and the DictionaryValue object will be unchanged.
651 // DEPRECATED, use Value::RemovePath(path) or Value::ExtractPath(path)
652 // instead.
653 bool Remove(StringPiece path, std::unique_ptr<Value>* out_value);
654
655 // Like Remove(), but without special treatment of '.'. This allows e.g. URLs
656 // to be used as paths.
657 // DEPRECATED, use Value::RemoveKey(key) or Value::ExtractKey(key) instead.
658 bool RemoveWithoutPathExpansion(StringPiece key,
659 std::unique_ptr<Value>* out_value);
660
661 // Removes a path, clearing out all dictionaries on |path| that remain empty
662 // after removing the value at |path|.
663 // DEPRECATED, use Value::RemovePath(path) or Value::ExtractPath(path)
664 // instead.
665 bool RemovePath(StringPiece path, std::unique_ptr<Value>* out_value);
666
667 using Value::RemovePath; // DictionaryValue::RemovePath shadows otherwise.
668
669 // Makes a copy of |this| but doesn't include empty dictionaries and lists in
670 // the copy. This never returns NULL, even if |this| itself is empty.
671 std::unique_ptr<DictionaryValue> DeepCopyWithoutEmptyChildren() const;
672
673 // Swaps contents with the |other| dictionary.
674 void Swap(DictionaryValue* other);
675
676 // This class provides an iterator over both keys and values in the
677 // dictionary. It can't be used to modify the dictionary.
678 // DEPRECATED, use Value::DictItems() instead.
679 class BASE_EXPORT Iterator {
680 public:
681 explicit Iterator(const DictionaryValue& target);
682 Iterator(const Iterator& other);
683 ~Iterator();
684
685 bool IsAtEnd() const { return it_ == target_.dict_.end(); }
686 void Advance() { ++it_; }
687
688 const std::string& key() const { return it_->first; }
689 const Value& value() const { return *it_->second; }
690
691 private:
692 const DictionaryValue& target_;
693 DictStorage::const_iterator it_;
694 };
695
696 // Iteration.
697 // DEPRECATED, use Value::DictItems() instead.
698 iterator begin() { return dict_.begin(); }
699 iterator end() { return dict_.end(); }
700
701 // DEPRECATED, use Value::DictItems() instead.
702 const_iterator begin() const { return dict_.begin(); }
703 const_iterator end() const { return dict_.end(); }
704
705 // DEPRECATED, use Value::Clone() instead.
706 // TODO(crbug.com/646113): Delete this and migrate callsites.
707 DictionaryValue* DeepCopy() const;
708 // DEPRECATED, use Value::Clone() instead.
709 // TODO(crbug.com/646113): Delete this and migrate callsites.
710 std::unique_ptr<DictionaryValue> CreateDeepCopy() const;
711};
712
713// This type of Value represents a list of other Value values.
714class BASE_EXPORT ListValue : public Value {
715 public:
716 using const_iterator = ListStorage::const_iterator;
717 using iterator = ListStorage::iterator;
718
719 // Returns |value| if it is a list, nullptr otherwise.
720 static std::unique_ptr<ListValue> From(std::unique_ptr<Value> value);
721
722 ListValue();
723 explicit ListValue(const ListStorage& in_list);
724 explicit ListValue(ListStorage&& in_list) noexcept;
725
726 // Clears the contents of this ListValue
727 // DEPRECATED, use GetList()::clear() instead.
728 void Clear();
729
730 // Returns the number of Values in this list.
731 // DEPRECATED, use GetList()::size() instead.
732 size_t GetSize() const { return list_.size(); }
733
734 // Returns whether the list is empty.
735 // DEPRECATED, use GetList()::empty() instead.
736 bool empty() const { return list_.empty(); }
737
738 // Reserves storage for at least |n| values.
739 // DEPRECATED, use GetList()::reserve() instead.
740 void Reserve(size_t n);
741
742 // Sets the list item at the given index to be the Value specified by
743 // the value given. If the index beyond the current end of the list, null
744 // Values will be used to pad out the list.
745 // Returns true if successful, or false if the index was negative or
746 // the value is a null pointer.
747 // DEPRECATED, use GetList()::operator[] instead.
748 bool Set(size_t index, std::unique_ptr<Value> in_value);
749
750 // Gets the Value at the given index. Modifies |out_value| (and returns true)
751 // only if the index falls within the current list range.
752 // Note that the list always owns the Value passed out via |out_value|.
753 // |out_value| is optional and will only be set if non-NULL.
754 // DEPRECATED, use GetList()::operator[] instead.
755 bool Get(size_t index, const Value** out_value) const;
756 bool Get(size_t index, Value** out_value);
757
758 // Convenience forms of Get(). Modifies |out_value| (and returns true)
759 // only if the index is valid and the Value at that index can be returned
760 // in the specified form.
761 // |out_value| is optional and will only be set if non-NULL.
762 // DEPRECATED, use GetList()::operator[]::GetBool() instead.
763 bool GetBoolean(size_t index, bool* out_value) const;
764 // DEPRECATED, use GetList()::operator[]::GetInt() instead.
765 bool GetInteger(size_t index, int* out_value) const;
766 // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as
767 // doubles.
768 // DEPRECATED, use GetList()::operator[]::GetDouble() instead.
769 bool GetDouble(size_t index, double* out_value) const;
770 // DEPRECATED, use GetList()::operator[]::GetString() instead.
771 bool GetString(size_t index, std::string* out_value) const;
772 bool GetString(size_t index, string16* out_value) const;
773
774 bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
775 bool GetDictionary(size_t index, DictionaryValue** out_value);
776
777 using Value::GetList;
778 // DEPRECATED, use GetList()::operator[]::GetList() instead.
779 bool GetList(size_t index, const ListValue** out_value) const;
780 bool GetList(size_t index, ListValue** out_value);
781
782 // Removes the Value with the specified index from this list.
783 // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
784 // passed out via |out_value|. If |out_value| is NULL, the removed value will
785 // be deleted. This method returns true if |index| is valid; otherwise
786 // it will return false and the ListValue object will be unchanged.
787 // DEPRECATED, use GetList()::erase() instead.
788 bool Remove(size_t index, std::unique_ptr<Value>* out_value);
789
790 // Removes the first instance of |value| found in the list, if any, and
791 // deletes it. |index| is the location where |value| was found. Returns false
792 // if not found.
793 // DEPRECATED, use GetList()::erase() instead.
794 bool Remove(const Value& value, size_t* index);
795
796 // Removes the element at |iter|. If |out_value| is NULL, the value will be
797 // deleted, otherwise ownership of the value is passed back to the caller.
798 // Returns an iterator pointing to the location of the element that
799 // followed the erased element.
800 // DEPRECATED, use GetList()::erase() instead.
801 iterator Erase(iterator iter, std::unique_ptr<Value>* out_value);
802
803 // Appends a Value to the end of the list.
804 // DEPRECATED, use GetList()::push_back() instead.
805 void Append(std::unique_ptr<Value> in_value);
806
807 // Convenience forms of Append.
808 // DEPRECATED, use GetList()::emplace_back() instead.
809 void AppendBoolean(bool in_value);
810 void AppendInteger(int in_value);
811 void AppendDouble(double in_value);
812 void AppendString(StringPiece in_value);
813 void AppendString(const string16& in_value);
814 // DEPRECATED, use GetList()::emplace_back() in a loop instead.
815 void AppendStrings(const std::vector<std::string>& in_values);
816 void AppendStrings(const std::vector<string16>& in_values);
817
818 // Appends a Value if it's not already present. Returns true if successful,
819 // or false if the value was already
820 // DEPRECATED, use std::find() with GetList()::push_back() instead.
821 bool AppendIfNotPresent(std::unique_ptr<Value> in_value);
822
823 // Insert a Value at index.
824 // Returns true if successful, or false if the index was out of range.
825 // DEPRECATED, use GetList()::insert() instead.
826 bool Insert(size_t index, std::unique_ptr<Value> in_value);
827
828 // Searches for the first instance of |value| in the list using the Equals
829 // method of the Value type.
830 // Returns a const_iterator to the found item or to end() if none exists.
831 // DEPRECATED, use std::find() instead.
832 const_iterator Find(const Value& value) const;
833
834 // Swaps contents with the |other| list.
835 // DEPRECATED, use GetList()::swap() instead.
836 void Swap(ListValue* other);
837
838 // Iteration.
839 // DEPRECATED, use GetList()::begin() instead.
840 iterator begin() { return list_.begin(); }
841 // DEPRECATED, use GetList()::end() instead.
842 iterator end() { return list_.end(); }
843
844 // DEPRECATED, use GetList()::begin() instead.
845 const_iterator begin() const { return list_.begin(); }
846 // DEPRECATED, use GetList()::end() instead.
847 const_iterator end() const { return list_.end(); }
848
849 // DEPRECATED, use Value::Clone() instead.
850 // TODO(crbug.com/646113): Delete this and migrate callsites.
851 ListValue* DeepCopy() const;
852 // DEPRECATED, use Value::Clone() instead.
853 // TODO(crbug.com/646113): Delete this and migrate callsites.
854 std::unique_ptr<ListValue> CreateDeepCopy() const;
855};
856
857// This interface is implemented by classes that know how to serialize
858// Value objects.
859class BASE_EXPORT ValueSerializer {
860 public:
861 virtual ~ValueSerializer();
862
863 virtual bool Serialize(const Value& root) = 0;
864};
865
866// This interface is implemented by classes that know how to deserialize Value
867// objects.
868class BASE_EXPORT ValueDeserializer {
869 public:
870 virtual ~ValueDeserializer();
871
872 // This method deserializes the subclass-specific format into a Value object.
873 // If the return value is non-NULL, the caller takes ownership of returned
874 // Value. If the return value is NULL, and if error_code is non-NULL,
875 // error_code will be set with the underlying error.
876 // If |error_message| is non-null, it will be filled in with a formatted
877 // error message including the location of the error if appropriate.
878 virtual std::unique_ptr<Value> Deserialize(int* error_code,
879 std::string* error_str) = 0;
880};
881
882// Stream operator so Values can be used in assertion statements. In order that
883// gtest uses this operator to print readable output on test failures, we must
884// override each specific type. Otherwise, the default template implementation
885// is preferred over an upcast.
886BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
887
888BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
889 const DictionaryValue& value) {
890 return out << static_cast<const Value&>(value);
891}
892
893BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
894 const ListValue& value) {
895 return out << static_cast<const Value&>(value);
896}
897
898// Stream operator so that enum class Types can be used in log statements.
899BASE_EXPORT std::ostream& operator<<(std::ostream& out,
900 const Value::Type& type);
901
902} // namespace base
903
904#endif // BASE_VALUES_H_
905