values.h 42 KB

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