values.h 45 KB

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