values.h 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  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. #ifndef BASE_VALUES_H_
  5. #define BASE_VALUES_H_
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <array>
  9. #include <initializer_list>
  10. #include <iosfwd>
  11. #include <iterator>
  12. #include <memory>
  13. #include <string>
  14. #include <utility>
  15. #include <vector>
  16. #include "base/base_export.h"
  17. #include "base/bit_cast.h"
  18. #include "base/compiler_specific.h"
  19. #include "base/containers/checked_iterators.h"
  20. #include "base/containers/checked_range.h"
  21. #include "base/containers/cxx20_erase_vector.h"
  22. #include "base/containers/flat_map.h"
  23. #include "base/containers/span.h"
  24. #include "base/strings/string_piece.h"
  25. #include "base/trace_event/base_tracing_forward.h"
  26. #include "base/value_iterators.h"
  27. #include "third_party/abseil-cpp/absl/types/optional.h"
  28. #include "third_party/abseil-cpp/absl/types/variant.h"
  29. namespace base {
  30. class DictionaryValue;
  31. class ListValue;
  32. // The `Value` class is a variant type can hold one of the following types:
  33. // - null
  34. // - bool
  35. // - int
  36. // - double
  37. // - string (internally UTF8-encoded)
  38. // - binary data (i.e. a blob)
  39. // - dictionary of string keys to `Value`s
  40. // - list of `Value`s
  41. //
  42. // With the exception of binary blobs, `Value` is intended to be the C++ version
  43. // of data types that can be represented in JSON.
  44. //
  45. // Warning: blob support may be removed in the future.
  46. //
  47. // ## Usage
  48. //
  49. // Do not use `Value` if a more specific type would be more appropriate. For
  50. // example, a function that only accepts dictionary values should have a
  51. // `base::Value::Dict` parameter, not a `base::Value` parameter.
  52. //
  53. // Construction:
  54. //
  55. // `Value` is directly constructible from `bool`, `int`, `double`, binary blobs
  56. // (`std::vector<uint8_t>`), `base::StringPiece`, `base::StringPiece16`,
  57. // `Value::Dict`, and `Value::List`.
  58. //
  59. // Copying:
  60. //
  61. // `Value` does not support C++ copy semantics to make it harder to accidentally
  62. // copy large values. Instead, use `Clone()` to manually create a deep copy.
  63. //
  64. // Reading:
  65. //
  66. // `GetBool()`, GetInt()`, et cetera `CHECK()` that the `Value` has the correct
  67. // subtype before returning the contained value. `bool`, `int`, `double` are
  68. // returned by value. Binary blobs, `std::string`, `Value::Dict`, `Value::List`
  69. // are returned by reference.
  70. //
  71. // `GetIfBool()`, `GetIfInt()`, et cetera return `absl::nullopt`/`nullptr` if
  72. // the `Value` does not have the correct subtype; otherwise, returns the value
  73. // wrapped in an `absl::optional` (for `bool`, `int`, `double`) or by pointer
  74. // (for binary blobs, `std::string`, `Value::Dict`, `Value::List`).
  75. //
  76. // Note: both `GetDouble()` and `GetIfDouble()` still return a non-null result
  77. // when the subtype is `Value::Type::INT`. In that case, the stored value is
  78. // coerced to a double before being returned.
  79. //
  80. // Assignment:
  81. //
  82. // It is not possible to directly assign `bool`, `int`, et cetera to a `Value`.
  83. // Instead, wrap the underlying type in `Value` before assigning.
  84. //
  85. // ## Dictionaries and Lists
  86. //
  87. // `Value` provides the `Value::Dict` and `Value::List` container types for
  88. // working with dictionaries and lists of values respectively, rather than
  89. // exposing the underlying container types directly. This allows the types to
  90. // provide convenient helpers for dictionaries and lists, as well as giving
  91. // greater flexibility for changing implementation details in the future.
  92. //
  93. // Both container types support enough STL-isms to be usable in range-based for
  94. // loops and generic operations such as those from <algorithm>.
  95. //
  96. // Dictionaries support:
  97. // - `empty()`, `size()`, `begin()`, `end()`, `cbegin()`, `cend()`,
  98. // `contains()`, `clear()`, `erase()`: Identical to the STL container
  99. // equivalents, with additional safety checks, e.g. iterators will
  100. // `CHECK()` if `end()` is dereferenced.
  101. //
  102. // - `Clone()`: Create a deep copy.
  103. // - `Merge()`: Merge another dictionary into this dictionary.
  104. // - `Find()`: Find a value by `StringPiece` key, returning nullptr if the key
  105. // is not present.
  106. // - `FindBool()`, `FindInt()`, ...: Similar to `Find()`, but ensures that the
  107. // `Value` also has the correct subtype. Same return semantics as
  108. // `GetIfBool()`, `GetIfInt()`, et cetera, returning `absl::nullopt` or
  109. // `nullptr` if the key is not present or the value has the wrong subtype.
  110. // - `Set()`: Associate a value with a `StringPiece` key. Accepts `Value` or any
  111. // of the subtypes that `Value` can hold.
  112. // - `Remove()`: Remove the key from this dictionary, if present.
  113. // - `Extract()`: If the key is present in the dictionary, removes the key from
  114. // the dictionary and transfers ownership of `Value` to the caller.
  115. // Otherwise, returns `absl::nullopt`.
  116. //
  117. // Dictionaries also support an additional set of helper methods that operate on
  118. // "paths": `FindByDottedPath()`, `SetByDottedPath()`, `RemoveByDottedPath()`,
  119. // and `ExtractByDottedPath()`. Dotted paths are a convenience method of naming
  120. // intermediate nested dictionaries, separating the components of the path using
  121. // '.' characters. For example, finding a string path on a `Value::Dict` using
  122. // the dotted path:
  123. //
  124. // "aaa.bbb.ccc"
  125. //
  126. // Will first look for a `Value::Type::DICT` associated with the key "aaa", then
  127. // another `Value::Type::DICT` under the "aaa" dict associated with the
  128. // key "bbb", and then a `Value::Type::STRING` under the "bbb" dict associated
  129. // with the key "ccc".
  130. //
  131. // If a path only has one component (i.e. has no dots), please use the regular,
  132. // non-path APIs.
  133. //
  134. // Lists support:
  135. // - `empty()`, `size()`, `begin()`, `end()`, `cbegin()`, `cend()`,
  136. // `front()`, `back()`, `reserve()`, `operator[]`, `clear()`, `erase()`:
  137. // Identical to the STL container equivalents, with additional safety
  138. // checks, e.g. `operator[]` will `CHECK()` if the index is out of range.
  139. // - `Clone()`: Create a deep copy.
  140. // - `Append()`: Append a value to the end of the list. Accepts `Value` or any
  141. // of the subtypes that `Value` can hold.
  142. // - `Insert()`: Insert a `Value` at a specified point in the list.
  143. // - `EraseValue()`: Erases all matching `Value`s from the list.
  144. // - `EraseIf()`: Erase all `Value`s matching an arbitrary predicate from the
  145. // list.
  146. //
  147. // ## Refactoring Notes
  148. //
  149. // `Value` was originally implemented as a class hierarchy, with a `Value` base
  150. // class, and a leaf class for each of the different types of `Value` subtypes.
  151. // https://docs.google.com/document/d/1uDLu5uTRlCWePxQUEHc8yNQdEoE1BDISYdpggWEABnw
  152. // proposed an overhaul of the `Value` API that has now largely been
  153. // implemented, though there remains a significant amount of legacy code that is
  154. // still being migrated as part of the code health migration.
  155. //
  156. // OLD WAY:
  157. //
  158. // std::unique_ptr<base::Value> GetFoo() {
  159. // std::unique_ptr<DictionaryValue> dict;
  160. // dict->SetString("mykey", "foo");
  161. // return dict;
  162. // }
  163. //
  164. // NEW WAY:
  165. //
  166. // base::Value GetFoo() {
  167. // base::Value::Dict dict;
  168. // dict.Set("mykey", "abc");
  169. // return base::Value(std::move(dict));
  170. // }
  171. //
  172. // To avoid losing type information with the new variant-based design, migration
  173. // off the deprecated types should use more specific subtypes where possible:
  174. //
  175. // OLD WAY:
  176. //
  177. // void AlwaysTakesList(std::unique_ptr<base::ListValue> list);
  178. // void AlwaysTakesDict(std::unique_ptr<base::DictionaryValue> dict);
  179. //
  180. // DEPRECATED (PREVIOUS) WAY:
  181. //
  182. // void AlwaysTakesList(std::vector<base::Value> list);
  183. // void AlwaysTakesListAlternative1(base::Value::ConstListView list);
  184. // void AlwaysTakesListAlternative2(base::Value::ListView& list);
  185. // void AlwaysTakesListAlterantive3(base::Value::ListStorage);
  186. // void AlwaysTakesDict(base::flat_map<std::string, base::Value> dict);
  187. // void AlwaysTakesDictAlternative(base::Value::DictStorage);
  188. //
  189. // NEW WAY:
  190. //
  191. // void AlwaysTakesList(base::Value::List list);
  192. // void AlwaysTakesDict(base::Value::Dict dict);
  193. //
  194. // Migrating code may require conversions on API boundaries. If something seems
  195. // awkward/inefficient, please reach out to #code-health-rotation on Slack for
  196. // consultation: it is entirely possible that certain classes of APIs may be
  197. // missing due to an unrealized need.
  198. class BASE_EXPORT GSL_OWNER Value {
  199. public:
  200. using BlobStorage = std::vector<uint8_t>;
  201. using DeprecatedListStorage = std::vector<Value>;
  202. // Like `DictStorage`, but with std::unique_ptr in the mapped type. This is
  203. // due to legacy reasons, and should be replaced with
  204. // flat_map<std::string, Value> once no caller relies on stability of pointers
  205. // anymore.
  206. using LegacyDictStorage = flat_map<std::string, std::unique_ptr<Value>>;
  207. using DeprecatedListView = CheckedContiguousRange<DeprecatedListStorage>;
  208. using DeprecatedConstListView =
  209. CheckedContiguousConstRange<DeprecatedListStorage>;
  210. // TODO(https://crbug.com/1291666): Make these private.
  211. using ListView = DeprecatedListView;
  212. using ConstListView = DeprecatedConstListView;
  213. class Dict;
  214. class List;
  215. enum class Type : unsigned char {
  216. NONE = 0,
  217. BOOLEAN,
  218. INTEGER,
  219. DOUBLE,
  220. STRING,
  221. BINARY,
  222. DICT,
  223. // TODO(https://crbug.com/1291670): Deprecated and will be removed.
  224. DICTIONARY = DICT,
  225. LIST,
  226. // Note: Do not add more types. See the file-level comment above for why.
  227. };
  228. // Adaptors for converting from the old way to the new way and vice versa.
  229. static Value FromUniquePtrValue(std::unique_ptr<Value> val);
  230. static std::unique_ptr<Value> ToUniquePtrValue(Value val);
  231. static const DictionaryValue& AsDictionaryValue(const Value& val);
  232. static const ListValue& AsListValue(const Value& val);
  233. Value() noexcept;
  234. Value(Value&&) noexcept;
  235. Value& operator=(Value&&) noexcept;
  236. // Deleted to prevent accidental copying.
  237. Value(const Value&) = delete;
  238. Value& operator=(const Value&) = delete;
  239. // Creates a deep copy of this value.
  240. Value Clone() const;
  241. // Creates a `Value` of `type`. The data of the corresponding type will be
  242. // default constructed.
  243. explicit Value(Type type);
  244. // Constructor for `Value::Type::BOOLEAN`.
  245. explicit Value(bool value);
  246. // Prevent pointers from implicitly converting to bool. Another way to write
  247. // this would be to template the bool constructor and use SFINAE to only allow
  248. // use if `std::is_same_v<T, bool>` is true, but this has surprising behavior
  249. // with range-based for loops over a `std::vector<bool>` (which will
  250. // unintuitively match the int overload instead).
  251. //
  252. // The `const` is load-bearing; otherwise, a `char*` argument would prefer the
  253. // deleted overload due to requiring a qualification conversion.
  254. template <typename T>
  255. explicit Value(const T*) = delete;
  256. // Constructor for `Value::Type::INT`.
  257. explicit Value(int value);
  258. // Constructor for `Value::Type::DOUBLE`.
  259. explicit Value(double value);
  260. // Constructors for `Value::Type::STRING`.
  261. explicit Value(StringPiece value);
  262. explicit Value(StringPiece16 value);
  263. // `char*` and `char16_t*` are needed to provide a more specific overload than
  264. // the deleted `const T*` overload above.
  265. explicit Value(const char* value);
  266. explicit Value(const char16_t* value);
  267. // `std::string&&` allows for efficient move construction.
  268. explicit Value(std::string&& value) noexcept;
  269. // Constructors for `Value::Type::BINARY`.
  270. explicit Value(const std::vector<char>& value);
  271. explicit Value(base::span<const uint8_t> value);
  272. explicit Value(BlobStorage&& value) noexcept;
  273. // Constructor for `Value::Type::DICT`.
  274. explicit Value(Dict&& value) noexcept;
  275. // Constructor for `Value::Type::LIST`.
  276. explicit Value(List&& value) noexcept;
  277. ~Value();
  278. // Returns the name for a given `type`.
  279. static const char* GetTypeName(Type type);
  280. // Returns the type of the value stored by the current Value object.
  281. Type type() const { return static_cast<Type>(data_.index()); }
  282. // Returns true if the current object represents a given type.
  283. bool is_none() const { return type() == Type::NONE; }
  284. bool is_bool() const { return type() == Type::BOOLEAN; }
  285. bool is_int() const { return type() == Type::INTEGER; }
  286. bool is_double() const { return type() == Type::DOUBLE; }
  287. bool is_string() const { return type() == Type::STRING; }
  288. bool is_blob() const { return type() == Type::BINARY; }
  289. bool is_dict() const { return type() == Type::DICT; }
  290. bool is_list() const { return type() == Type::LIST; }
  291. // Returns the stored data if the type matches, or `absl::nullopt`/`nullptr`
  292. // otherwise. `bool`, `int`, and `double` are returned in a wrapped
  293. // `absl::optional`; blobs, `Value::Dict`, and `Value::List` are returned by
  294. // pointer.
  295. absl::optional<bool> GetIfBool() const;
  296. absl::optional<int> GetIfInt() const;
  297. // Returns a non-null value for both `Value::Type::DOUBLE` and
  298. // `Value::Type::INT`, converting the latter to a double.
  299. absl::optional<double> GetIfDouble() const;
  300. const std::string* GetIfString() const;
  301. std::string* GetIfString();
  302. const BlobStorage* GetIfBlob() const;
  303. const Dict* GetIfDict() const;
  304. Dict* GetIfDict();
  305. const List* GetIfList() const;
  306. List* GetIfList();
  307. // Similar to the `GetIf...()` variants above, but fails with a `CHECK()` on a
  308. // type mismatch. `bool`, `int`, and `double` are returned by value; blobs,
  309. // `Value::Dict`, and `Value::List` are returned by reference.
  310. bool GetBool() const;
  311. int GetInt() const;
  312. // Returns a value for both `Value::Type::DOUBLE` and `Value::Type::INT`,
  313. // converting the latter to a double.
  314. double GetDouble() const;
  315. // Callers that want to transfer ownership can use std::move() in conjunction
  316. // with one of the mutable variants below, e.g.:
  317. // std::string taken_string = std::move(value.GetString());
  318. // base::Value::Dict taken_dict = std::move(value.GetDict());
  319. // base::Value::List taken_list = std::move(value.GetList());
  320. const std::string& GetString() const;
  321. std::string& GetString();
  322. const BlobStorage& GetBlob() const;
  323. const Dict& GetDict() const;
  324. Dict& GetDict();
  325. const List& GetList() const;
  326. List& GetList();
  327. // Represents a dictionary of string keys to Values.
  328. class BASE_EXPORT GSL_OWNER Dict {
  329. public:
  330. using iterator = detail::dict_iterator;
  331. using const_iterator = detail::const_dict_iterator;
  332. Dict();
  333. Dict(Dict&&) noexcept;
  334. Dict& operator=(Dict&&) noexcept;
  335. // Deleted to prevent accidental copying.
  336. Dict(const Dict&) = delete;
  337. Dict& operator=(const Dict&) = delete;
  338. // Takes move_iterators iterators that return std::pair<std::string, Value>,
  339. // and moves their values into a new Dict. Adding all entries at once
  340. // results in a faster initial sort operation. Takes move iterators to avoid
  341. // having to clone the input.
  342. template <class IteratorType>
  343. explicit Dict(std::move_iterator<IteratorType> first,
  344. std::move_iterator<IteratorType> last) {
  345. // Need to move into a vector first, since `storage_` currently uses
  346. // unique_ptrs.
  347. std::vector<std::pair<std::string, std::unique_ptr<Value>>> values;
  348. for (auto current = first; current != last; ++current) {
  349. // With move iterators, no need to call Clone(), but do need to move
  350. // to a temporary first, as accessing either field individually will
  351. // directly from the iterator will delete the other field.
  352. auto value = *current;
  353. values.emplace_back(std::move(value.first),
  354. std::make_unique<Value>(std::move(value.second)));
  355. }
  356. storage_ =
  357. flat_map<std::string, std::unique_ptr<Value>>(std::move(values));
  358. }
  359. ~Dict();
  360. // TODO(dcheng): Probably need to allow construction from a pair of
  361. // iterators for now due to the prevalence of DictStorage.
  362. // Returns true if there are no entries in this dictionary and false
  363. // otherwise.
  364. bool empty() const;
  365. // Returns the number of entries in this dictionary.
  366. size_t size() const;
  367. // Returns an iterator to the first entry in this dictionary.
  368. iterator begin();
  369. const_iterator begin() const;
  370. const_iterator cbegin() const;
  371. // Returns an iterator following the last entry in this dictionary. May not
  372. // be dereferenced.
  373. iterator end();
  374. const_iterator end() const;
  375. const_iterator cend() const;
  376. // Returns true if `key` is an entry in this dictionary.
  377. bool contains(base::StringPiece key) const;
  378. // Removes all entries from this dictionary.
  379. void clear();
  380. // Removes the entry referenced by `pos` in this dictionary and returns an
  381. // iterator to the entry following the removed entry.
  382. iterator erase(iterator pos);
  383. iterator erase(const_iterator pos);
  384. // Creates a deep copy of this dictionary.
  385. Dict Clone() const;
  386. // Merges the entries from `dict` into this dictionary. If an entry with the
  387. // same key exists in this dictionary and `dict`:
  388. // - if both entries are dictionaries, they will be recursively merged
  389. // - otherwise, the already-existing entry in this dictionary will be
  390. // overwritten with the entry from `dict`.
  391. void Merge(Dict dict);
  392. // Finds the entry corresponding to `key` in this dictionary. Returns
  393. // nullptr if there is no such entry.
  394. const Value* Find(StringPiece key) const;
  395. Value* Find(StringPiece key);
  396. // Similar to `Find()` above, but returns `absl::nullopt`/`nullptr` if the
  397. // type of the entry does not match. `bool`, `int`, and `double` are
  398. // returned in a wrapped `absl::optional`; blobs, `Value::Dict`, and
  399. // `Value::List` are returned by pointer.
  400. absl::optional<bool> FindBool(StringPiece key) const;
  401. absl::optional<int> FindInt(StringPiece key) const;
  402. // Returns a non-null value for both `Value::Type::DOUBLE` and
  403. // `Value::Type::INT`, converting the latter to a double.
  404. absl::optional<double> FindDouble(StringPiece key) const;
  405. const std::string* FindString(StringPiece key) const;
  406. std::string* FindString(StringPiece key);
  407. const BlobStorage* FindBlob(StringPiece key) const;
  408. const Dict* FindDict(StringPiece key) const;
  409. Dict* FindDict(StringPiece key);
  410. const List* FindList(StringPiece key) const;
  411. List* FindList(StringPiece key);
  412. // If there's a value of the specified type at `key` in this dictionary,
  413. // returns it. Otherwise, creates an empty container of the specified type,
  414. // inserts it at `key`, and returns it. If there's a value of some other
  415. // type at `key`, will overwrite that entry.
  416. Dict* EnsureDict(StringPiece key);
  417. List* EnsureList(StringPiece key);
  418. // Sets an entry with `key` and `value` in this dictionary, overwriting any
  419. // existing entry with the same `key`. Returns a pointer to the set `value`.
  420. Value* Set(StringPiece key, Value&& value);
  421. Value* Set(StringPiece key, bool value);
  422. template <typename T>
  423. Value* Set(StringPiece, const T*) = delete;
  424. Value* Set(StringPiece key, int value);
  425. Value* Set(StringPiece key, double value);
  426. Value* Set(StringPiece key, StringPiece value);
  427. Value* Set(StringPiece key, StringPiece16 value);
  428. Value* Set(StringPiece key, const char* value);
  429. Value* Set(StringPiece key, const char16_t* value);
  430. Value* Set(StringPiece key, std::string&& value);
  431. Value* Set(StringPiece key, BlobStorage&& value);
  432. Value* Set(StringPiece key, Dict&& value);
  433. Value* Set(StringPiece key, List&& value);
  434. // Removes the entry corresponding to `key` from this dictionary. Returns
  435. // true if an entry was removed or false otherwise.
  436. bool Remove(StringPiece key);
  437. // Similar to `Remove()`, but returns the value corresponding to the removed
  438. // entry or `absl::nullopt` otherwise.
  439. absl::optional<Value> Extract(StringPiece key);
  440. // Equivalent to the above methods but operating on paths instead of keys.
  441. // A path is shorthand syntax for referring to a key nested inside
  442. // intermediate dictionaries, with components delimited by ".". Paths may
  443. // not be empty.
  444. //
  445. // Prefer the non-path methods above when possible. Paths that have only one
  446. // component (i.e. no dots in the path) should never use the path-based
  447. // methods.
  448. //
  449. // Originally, the path-based APIs were the only way of specifying a key, so
  450. // there are likely to be many legacy (and unnecessary) uses of the path
  451. // APIs that do not actually require traversing nested dictionaries.
  452. const Value* FindByDottedPath(StringPiece path) const;
  453. Value* FindByDottedPath(StringPiece path);
  454. absl::optional<bool> FindBoolByDottedPath(StringPiece path) const;
  455. absl::optional<int> FindIntByDottedPath(StringPiece path) const;
  456. // Returns a non-null value for both `Value::Type::DOUBLE` and
  457. // `Value::Type::INT`, converting the latter to a double.
  458. absl::optional<double> FindDoubleByDottedPath(StringPiece path) const;
  459. const std::string* FindStringByDottedPath(StringPiece path) const;
  460. std::string* FindStringByDottedPath(StringPiece path);
  461. const BlobStorage* FindBlobByDottedPath(StringPiece path) const;
  462. const Dict* FindDictByDottedPath(StringPiece path) const;
  463. Dict* FindDictByDottedPath(StringPiece path);
  464. const List* FindListByDottedPath(StringPiece path) const;
  465. List* FindListByDottedPath(StringPiece path);
  466. // Creates a new entry with a dictionary for any non-last component that is
  467. // missing an entry while performing the path traversal. Will fail if any
  468. // non-last component of the path refers to an already-existing entry that
  469. // is not a dictionary. Returns `nullptr` on failure.
  470. Value* SetByDottedPath(StringPiece path, Value&& value);
  471. Value* SetByDottedPath(StringPiece path, bool value);
  472. template <typename T>
  473. Value* SetByDottedPath(StringPiece, const T*) = delete;
  474. Value* SetByDottedPath(StringPiece path, int value);
  475. Value* SetByDottedPath(StringPiece path, double value);
  476. Value* SetByDottedPath(StringPiece path, StringPiece value);
  477. Value* SetByDottedPath(StringPiece path, StringPiece16 value);
  478. Value* SetByDottedPath(StringPiece path, const char* value);
  479. Value* SetByDottedPath(StringPiece path, const char16_t* value);
  480. Value* SetByDottedPath(StringPiece path, std::string&& value);
  481. Value* SetByDottedPath(StringPiece path, BlobStorage&& value);
  482. Value* SetByDottedPath(StringPiece path, Dict&& value);
  483. Value* SetByDottedPath(StringPiece path, List&& value);
  484. bool RemoveByDottedPath(StringPiece path);
  485. absl::optional<Value> ExtractByDottedPath(StringPiece path);
  486. // Serializes to a string for logging and debug purposes.
  487. std::string DebugString() const;
  488. #if BUILDFLAG(ENABLE_BASE_TRACING)
  489. // Write this object into a trace.
  490. void WriteIntoTrace(perfetto::TracedValue) const;
  491. #endif // BUILDFLAG(ENABLE_BASE_TRACING)
  492. private:
  493. BASE_EXPORT friend bool operator==(const Dict& lhs, const Dict& rhs);
  494. BASE_EXPORT friend bool operator!=(const Dict& lhs, const Dict& rhs);
  495. BASE_EXPORT friend bool operator<(const Dict& lhs, const Dict& rhs);
  496. BASE_EXPORT friend bool operator>(const Dict& lhs, const Dict& rhs);
  497. BASE_EXPORT friend bool operator<=(const Dict& lhs, const Dict& rhs);
  498. BASE_EXPORT friend bool operator>=(const Dict& lhs, const Dict& rhs);
  499. // For legacy access to the internal storage type.
  500. friend Value;
  501. explicit Dict(const flat_map<std::string, std::unique_ptr<Value>>& storage);
  502. flat_map<std::string, std::unique_ptr<Value>> storage_;
  503. };
  504. // Represents a list of Values.
  505. class BASE_EXPORT GSL_OWNER List {
  506. public:
  507. using iterator = CheckedContiguousIterator<Value>;
  508. using const_iterator = CheckedContiguousConstIterator<Value>;
  509. using value_type = Value;
  510. List();
  511. List(List&&) noexcept;
  512. List& operator=(List&&) noexcept;
  513. // Deleted to prevent accidental copying.
  514. List(const List&) = delete;
  515. List& operator=(const List&) = delete;
  516. ~List();
  517. // TODO(dcheng): Probably need to allow construction from a pair of
  518. // iterators for now due to the prevalence of ListStorage now.
  519. // Returns true if there are no values in this list and false otherwise.
  520. bool empty() const;
  521. // Returns the number of values in this list.
  522. size_t size() const;
  523. // Returns an iterator to the first value in this list.
  524. iterator begin();
  525. const_iterator begin() const;
  526. const_iterator cbegin() const;
  527. // Returns an iterator following the last value in this list. May not be
  528. // dereferenced.
  529. iterator end();
  530. const_iterator end() const;
  531. const_iterator cend() const;
  532. // Returns a reference to the first value in the container. Fails with
  533. // `CHECK()` if the list is empty.
  534. const Value& front() const;
  535. Value& front();
  536. // Returns a reference to the last value in the container. Fails with
  537. // `CHECK()` if the list is empty.
  538. const Value& back() const;
  539. Value& back();
  540. // Increase the capacity of the backing container, but does not change
  541. // the size. Assume all existing iterators will be invalidated.
  542. void reserve(size_t capacity);
  543. // Returns a reference to the value at `index` in this list. Fails with a
  544. // `CHECK()` if `index >= size()`.
  545. const Value& operator[](size_t index) const;
  546. Value& operator[](size_t index);
  547. // Removes all value from this list.
  548. void clear();
  549. // Removes the value referenced by `pos` in this list and returns an
  550. // iterator to the value following the removed value.
  551. iterator erase(iterator pos);
  552. const_iterator erase(const_iterator pos);
  553. // Remove the values in the range [`first`, `last`). Returns iterator to the
  554. // first value following the removed range, which is `last`. If `first` ==
  555. // `last`, removes nothing and returns `last`.
  556. iterator erase(iterator first, iterator last);
  557. const_iterator erase(const_iterator first, const_iterator last);
  558. // Creates a deep copy of this dictionary.
  559. List Clone() const;
  560. // Appends `value` to the end of this list.
  561. void Append(Value&& value);
  562. void Append(bool value);
  563. template <typename T>
  564. void Append(const T*) = delete;
  565. void Append(int value);
  566. void Append(double value);
  567. void Append(StringPiece value);
  568. void Append(StringPiece16 value);
  569. void Append(const char* value);
  570. void Append(const char16_t* value);
  571. void Append(std::string&& value);
  572. void Append(BlobStorage&& value);
  573. void Append(Dict&& value);
  574. void Append(List&& value);
  575. // Inserts `value` before `pos` in this list. Returns an iterator to the
  576. // inserted value.
  577. // TODO(dcheng): Should this provide the same set of overloads that Append()
  578. // does?
  579. iterator Insert(const_iterator pos, Value&& value);
  580. // Erases all values equal to `value` from this list.
  581. size_t EraseValue(const Value& value);
  582. // Erases all values for which `predicate` evaluates to true from this list.
  583. template <typename Predicate>
  584. size_t EraseIf(Predicate predicate) {
  585. return base::EraseIf(storage_, predicate);
  586. }
  587. // Serializes to a string for logging and debug purposes.
  588. std::string DebugString() const;
  589. #if BUILDFLAG(ENABLE_BASE_TRACING)
  590. // Write this object into a trace.
  591. void WriteIntoTrace(perfetto::TracedValue) const;
  592. #endif // BUILDFLAG(ENABLE_BASE_TRACING)
  593. private:
  594. BASE_EXPORT friend bool operator==(const List& lhs, const List& rhs);
  595. BASE_EXPORT friend bool operator!=(const List& lhs, const List& rhs);
  596. BASE_EXPORT friend bool operator<(const List& lhs, const List& rhs);
  597. BASE_EXPORT friend bool operator>(const List& lhs, const List& rhs);
  598. BASE_EXPORT friend bool operator<=(const List& lhs, const List& rhs);
  599. BASE_EXPORT friend bool operator>=(const List& lhs, const List& rhs);
  600. // For legacy access to the internal storage type.
  601. friend Value;
  602. explicit List(const std::vector<Value>& storage);
  603. std::vector<Value> storage_;
  604. };
  605. // ===== DEPRECATED methods that require `type() == Type::LIST` =====
  606. // Returns the Values in a list as a view. The mutable overload allows for
  607. // modification of the underlying values, but does not allow changing the
  608. // structure of the list.
  609. //
  610. // DEPRECATED: prefer direct use `base::Value::List` where possible, or
  611. // `GetList()` otherwise.
  612. DeprecatedListView GetListDeprecated();
  613. DeprecatedConstListView GetListDeprecated() const;
  614. // Appends `value` to the end of the list.
  615. //
  616. // DEPRECATED: prefer `Value::List::Append()`.
  617. void Append(Value&& value);
  618. // DEPRECATED: prefer `Value::List::Append()`.
  619. void Append(bool value);
  620. template <typename T>
  621. void Append(const T* ptr) = delete;
  622. // DEPRECATED: prefer `Value::List::Append()`.
  623. void Append(int value);
  624. // DEPRECATED: prefer `Value::List::Append()`.
  625. void Append(double value);
  626. // DEPRECATED: prefer `Value::List::Append()`.
  627. void Append(StringPiece value);
  628. // DEPRECATED: prefer `Value::List::Append()`.
  629. void Append(StringPiece16 value);
  630. // DEPRECATED: prefer `Value::List::Append()`.
  631. void Append(const char* value);
  632. // DEPRECATED: prefer `Value::List::Append()`.
  633. void Append(std::string&& value);
  634. // Erases the Value pointed to by `iter`. Returns false if `iter` is out of
  635. // bounds.
  636. //
  637. // DEPRECATED: prefer `Value::List::erase(iter)`.
  638. bool EraseListIter(CheckedContiguousConstIterator<Value> iter);
  639. // Erases all Values that compare equal to `val`. Returns the number of
  640. // deleted Values.
  641. //
  642. // DEPRECATED: prefer `Value::List::EraseValue(val)`.
  643. size_t EraseListValue(const Value& val);
  644. // Erases all Values for which `pred` returns true. Returns the number of
  645. // deleted Values.
  646. //
  647. // DEPRECATED: prefer `Value::List::EraseIf(pred)`.
  648. template <typename Predicate>
  649. size_t EraseListValueIf(Predicate pred) {
  650. return base::EraseIf(list(), pred);
  651. }
  652. // Erases all Values from the list.
  653. //
  654. // DEPRECATED: prefer `Value::List::clear()`.
  655. void ClearList();
  656. // ===== DEPRECATED methods that require `type() == Type::DICT` =====
  657. // `FindKey` looks up `key` in the underlying dictionary. If found, it returns
  658. // a pointer to the element. Otherwise it returns nullptr.
  659. //
  660. // DEPRECATED: prefer `Value::Dict::Find()`.
  661. Value* FindKey(StringPiece key);
  662. const Value* FindKey(StringPiece key) const;
  663. // `FindKeyOfType` is similar to `FindKey`, but it also requires the found
  664. // value to have type `type`. If no type is found, or the found value is of a
  665. // different type nullptr is returned.
  666. //
  667. // DEPRECATED: prefer `Value::Dict::FindBool()`, `Value::Dict::FindInt()`, et
  668. // cetera.
  669. Value* FindKeyOfType(StringPiece key, Type type);
  670. const Value* FindKeyOfType(StringPiece key, Type type) const;
  671. // These are convenience forms of `FindKey`. They return `absl::nullopt` or
  672. // `nullptr` if the value is not found or doesn't have the type specified in
  673. // the function's name.
  674. //
  675. // DEPRECATED: prefer `Value::Dict::FindBool()`.
  676. absl::optional<bool> FindBoolKey(StringPiece key) const;
  677. // DEPRECATED: prefer `Value::Dict::FindInt()`.
  678. absl::optional<int> FindIntKey(StringPiece key) const;
  679. // Returns a non-null value for both `Value::Type::DOUBLE` and
  680. // `Value::Type::INT`, converting the latter to a double.
  681. //
  682. // DEPRECATED: prefer `Value::Dict::FindDouble()`.
  683. absl::optional<double> FindDoubleKey(StringPiece key) const;
  684. // DEPRECATED: prefer `Value::Dict::FindString()`.
  685. const std::string* FindStringKey(StringPiece key) const;
  686. std::string* FindStringKey(StringPiece key);
  687. // DEPRECATED: prefer `Value::Dict::FindBlob()`.
  688. const BlobStorage* FindBlobKey(StringPiece key) const;
  689. // DEPRECATED: prefer `Value::Dict::FindDict()`.
  690. const Value* FindDictKey(StringPiece key) const;
  691. Value* FindDictKey(StringPiece key);
  692. // DEPRECATED: prefer `Value::Dict::FindList()`.
  693. const Value* FindListKey(StringPiece key) const;
  694. Value* FindListKey(StringPiece key);
  695. // `SetKey` looks up `key` in the underlying dictionary and sets the mapped
  696. // value to `value`. If `key` could not be found, a new element is inserted.
  697. // A pointer to the modified item is returned.
  698. //
  699. // Note: Prefer `Set<Type>Key()` if the input is not already a `Value`.
  700. //
  701. // DEPRECATED: Prefer `Value::Dict::Set()`.
  702. Value* SetKey(StringPiece key, Value&& value);
  703. // `Set`Type>Key` looks up `key` in the underlying dictionary and associates a
  704. // corresponding Value() constructed from the second parameter. Compared to
  705. // `SetKey()`, this avoids un-necessary temporary `Value()` creation, as well
  706. // ambiguities in the value type.
  707. //
  708. // DEPRECATED: Prefer `Value::Dict::Set()`.
  709. Value* SetBoolKey(StringPiece key, bool val);
  710. // DEPRECATED: Prefer `Value::Dict::Set()`.
  711. Value* SetIntKey(StringPiece key, int val);
  712. // DEPRECATED: Prefer `Value::Dict::Set()`.
  713. Value* SetDoubleKey(StringPiece key, double val);
  714. // DEPRECATED: Prefer `Value::Dict::Set()`.
  715. Value* SetStringKey(StringPiece key, StringPiece val);
  716. // DEPRECATED: Prefer `Value::Dict::Set()`.
  717. Value* SetStringKey(StringPiece key, StringPiece16 val);
  718. // DEPRECATED: Prefer `Value::Dict::Set()`.
  719. Value* SetStringKey(StringPiece key, const char* val);
  720. // DEPRECATED: Prefer `Value::Dict::Set()`.
  721. Value* SetStringKey(StringPiece key, std::string&& val);
  722. // This attempts to remove the value associated with `key`. In case of
  723. // failure, e.g. the key does not exist, false is returned and the underlying
  724. // dictionary is not changed. In case of success, `key` is deleted from the
  725. // dictionary and the method returns true.
  726. //
  727. // Deprecated: Prefer `Value::Dict::Remove()`.
  728. bool RemoveKey(StringPiece key);
  729. // This attempts to extract the value associated with `key`. In case of
  730. // failure, e.g. the key does not exist, nullopt is returned and the
  731. // underlying dictionary is not changed. In case of success, `key` is deleted
  732. // from the dictionary and the method returns the extracted Value.
  733. //
  734. // DEPRECATED: Prefer `Value::Dict::Extract()`.
  735. absl::optional<Value> ExtractKey(StringPiece key);
  736. // Searches a hierarchy of dictionary values for a given value. If a path
  737. // of dictionaries exist, returns the item at that path. If any of the path
  738. // components do not exist or if any but the last path components are not
  739. // dictionaries, returns nullptr. The type of the leaf Value is not checked.
  740. //
  741. // This version takes a StringPiece for the path, using dots as separators.
  742. //
  743. // DEPRECATED: Prefer `Value::Dict::FindByDottedPath()`.
  744. Value* FindPath(StringPiece path);
  745. const Value* FindPath(StringPiece path) const;
  746. // There are also deprecated versions that take the path parameter
  747. // as either a std::initializer_list<StringPiece> or a
  748. // span<const StringPiece>. The latter is useful to use a
  749. // std::vector<std::string> as a parameter but creates huge dynamic
  750. // allocations and should be avoided!
  751. // Note: If there is only one component in the path, use `FindKey()` instead.
  752. //
  753. // Example:
  754. // std::vector<StringPiece> components = ...
  755. // auto* found = FindPath(components);
  756. //
  757. // DEPRECATED: These are not common, and there is no currently planned
  758. // replacement.
  759. Value* FindPath(std::initializer_list<StringPiece> path);
  760. Value* FindPath(span<const StringPiece> path);
  761. const Value* FindPath(std::initializer_list<StringPiece> path) const;
  762. const Value* FindPath(span<const StringPiece> path) const;
  763. // Like FindPath() but will only return the value if the leaf Value type
  764. // matches the given type. Will return nullptr otherwise.
  765. // Note: Prefer `Find<Type>Path()` for simple values.
  766. //
  767. // Note: If there is only one component in the path, use `FindKeyOfType()`
  768. // instead for slightly better performance.
  769. //
  770. // DEPRECATED: Use `Value::Dict::FindBoolByDottedPath()`,
  771. // `Value::Dict::FindIntByDottedPath()`, et cetera.
  772. Value* FindPathOfType(StringPiece path, Type type);
  773. const Value* FindPathOfType(StringPiece path, Type type) const;
  774. // Convenience accessors used when the expected type of a value is known.
  775. // Similar to Find<Type>Key() but accepts paths instead of keys.
  776. //
  777. // DEPRECATED: Use `Value::Dict::FindBoolByDottedPath()`, or
  778. // `Value::Dict::FindBool()` if the path only has one component, i.e. has no
  779. // dots.
  780. absl::optional<bool> FindBoolPath(StringPiece path) const;
  781. // DEPRECATED: Use `Value::Dict::FindIntByDottedPath()`, or
  782. // `Value::Dict::FindInt()` if the path only has one component, i.e. has no
  783. // dots.
  784. absl::optional<int> FindIntPath(StringPiece path) const;
  785. // DEPRECATED: Use `Value::Dict::FindDoubleByDottedPath()`, or
  786. // `Value::Dict::FindDouble()` if the path only has one component, i.e. has no
  787. // dots.
  788. absl::optional<double> FindDoublePath(StringPiece path) const;
  789. // DEPRECATED: Use `Value::Dict::FindStringByDottedPath()`, or
  790. // `Value::Dict::FindString()` if the path only has one component, i.e. has no
  791. // dots.
  792. const std::string* FindStringPath(StringPiece path) const;
  793. std::string* FindStringPath(StringPiece path);
  794. // DEPRECATED: Use `Value::Dict::FindDictByDottedPath()`, or
  795. // `Value::Dict::FindDict()` if the path only has one component, i.e. has no
  796. // dots.
  797. Value* FindDictPath(StringPiece path);
  798. const Value* FindDictPath(StringPiece path) const;
  799. // DEPRECATED: Use `Value::Dict::FindListByDottedPath()`, or
  800. // `Value::Dict::FindList()` if the path only has one component, i.e. has no
  801. // dots.
  802. Value* FindListPath(StringPiece path);
  803. const Value* FindListPath(StringPiece path) const;
  804. // The following forms are deprecated too, use the ones that take the path
  805. // as a single StringPiece instead.
  806. //
  807. // DEPRECATED: These are not common, and there is no currently planned
  808. // replacement.
  809. Value* FindPathOfType(std::initializer_list<StringPiece> path, Type type);
  810. Value* FindPathOfType(span<const StringPiece> path, Type type);
  811. const Value* FindPathOfType(std::initializer_list<StringPiece> path,
  812. Type type) const;
  813. const Value* FindPathOfType(span<const StringPiece> path, Type type) const;
  814. // Sets the given path, expanding and creating dictionary keys as necessary.
  815. //
  816. // If the current value is not a dictionary, the function returns nullptr. If
  817. // path components do not exist, they will be created. If any but the last
  818. // components matches a value that is not a dictionary, the function will fail
  819. // (it will not overwrite the value) and return nullptr. The last path
  820. // component will be unconditionally overwritten if it exists, and created if
  821. // it doesn't.
  822. //
  823. // Note: If there is only one component in the path, use `SetKey()` instead.
  824. // Note: Using `Set<Type>Path()` might be more convenient and efficient.
  825. //
  826. // DEPRECATED: Use `Value::Dict::SetByDottedPath()`.
  827. Value* SetPath(StringPiece path, Value&& value);
  828. // These setters are more convenient and efficient than the corresponding
  829. // SetPath(...) call.
  830. //
  831. // DEPRECATED: Use `Value::Dict::SetByDottedPath()`.
  832. Value* SetBoolPath(StringPiece path, bool value);
  833. // DEPRECATED: Use `Value::Dict::SetByDottedPath()`.
  834. Value* SetIntPath(StringPiece path, int value);
  835. // DEPRECATED: Use `Value::Dict::SetByDottedPath()`.
  836. Value* SetDoublePath(StringPiece path, double value);
  837. // DEPRECATED: Use `Value::Dict::SetByDottedPath()`.
  838. Value* SetStringPath(StringPiece path, StringPiece value);
  839. // DEPRECATED: Use `Value::Dict::SetByDottedPath()`.
  840. Value* SetStringPath(StringPiece path, const char* value);
  841. // DEPRECATED: Use `Value::Dict::SetByDottedPath()`.
  842. Value* SetStringPath(StringPiece path, std::string&& value);
  843. // DEPRECATED: Use `Value::Dict::SetByDottedPath()`.
  844. Value* SetStringPath(StringPiece path, StringPiece16 value);
  845. // DEPRECATED: Use `Value::Dict::SetByDottedPath()`.
  846. Value* SetPath(std::initializer_list<StringPiece> path, Value&& value);
  847. Value* SetPath(span<const StringPiece> path, Value&& value);
  848. // Tries to remove a Value at the given path.
  849. //
  850. // If the current value is not a dictionary or any path component does not
  851. // exist, this operation fails, leaves underlying Values untouched and returns
  852. // `false`. In case intermediate dictionaries become empty as a result of this
  853. // path removal, they will be removed as well.
  854. // Note: If there is only one component in the path, use `RemoveKey()`
  855. // instead.
  856. //
  857. // DEPRECATED: Use `Value::Dict::RemoveByDottedPath()`.
  858. bool RemovePath(StringPiece path);
  859. // Tries to extract a Value at the given path.
  860. //
  861. // If the current value is not a dictionary or any path component does not
  862. // exist, this operation fails, leaves underlying Values untouched and returns
  863. // nullopt. In case intermediate dictionaries become empty as a result of this
  864. // path removal, they will be removed as well. Returns the extracted value on
  865. // success.
  866. // Note: If there is only one component in the path, use `ExtractKey()`
  867. // instead.
  868. //
  869. // DEPRECATED: Use `Value::Dict::ExtractByDottedPath()`.
  870. absl::optional<Value> ExtractPath(StringPiece path);
  871. using dict_iterator_proxy = detail::dict_iterator_proxy;
  872. using const_dict_iterator_proxy = detail::const_dict_iterator_proxy;
  873. // `DictItems` returns a proxy object that exposes iterators to the underlying
  874. // dictionary. These are intended for iteration over all items in the
  875. // dictionary and are compatible with for-each loops and standard library
  876. // algorithms.
  877. //
  878. // Unlike with std::map, a range-for over the non-const version of
  879. // `DictItems()` will range over items of type
  880. // `pair<const std::string&, Value&>`, so code of the form
  881. // for (auto kv : my_value.DictItems())
  882. // Mutate(kv.second);
  883. // will actually alter `my_value` in place (if it isn't const).
  884. //
  885. // DEPRECATED: Use a range-based for loop over `base::Value::Dict` directly
  886. // instead.
  887. dict_iterator_proxy DictItems();
  888. const_dict_iterator_proxy DictItems() const;
  889. // DEPRECATED: prefer `Value::Dict::size()`.
  890. size_t DictSize() const;
  891. // DEPRECATED: prefer `Value::Dict::empty()`.
  892. bool DictEmpty() const;
  893. // DEPRECATED: prefer `Value::Dict::clear()`.
  894. void DictClear();
  895. // Merge `dictionary` into this value. This is done recursively, i.e. any
  896. // sub-dictionaries will be merged as well. In case of key collisions, the
  897. // passed in dictionary takes precedence and data already present will be
  898. // replaced. Values within `dictionary` are deep-copied, so `dictionary` may
  899. // be freed any time after this call.
  900. // Note: This requires that `type()` and `dictionary->type()` is
  901. // Type::DICT.
  902. //
  903. // DEPRECATED: prefer `Value::Dict::Merge()`.
  904. void MergeDictionary(const Value* dictionary);
  905. // These methods allow the convenient retrieval of the contents of the Value.
  906. // If the current object can be converted into the given type, the value is
  907. // returned through the `out_value` parameter and true is returned;
  908. // otherwise, false is returned and `out_value` is unchanged.
  909. // DictionaryValue::From is the equivalent for std::unique_ptr conversions.
  910. //
  911. // DEPRECATED: prefer direct use `base::Value::Dict` where possible, or
  912. // `GetIfDict()` otherwise.
  913. bool GetAsDictionary(DictionaryValue** out_value);
  914. bool GetAsDictionary(const DictionaryValue** out_value) const;
  915. // Note: Do not add more types. See the file-level comment above for why.
  916. // This creates a deep copy of the entire Value tree, and returns a pointer
  917. // to the copy. The caller gets ownership of the copy, of course.
  918. // Subclasses return their own type directly in their overrides;
  919. // this works because C++ supports covariant return types.
  920. // TODO(crbug.com/646113): Delete this and migrate callsites.
  921. //
  922. // DEPRECATED: prefer `Value::Clone()`.
  923. std::unique_ptr<Value> CreateDeepCopy() const;
  924. // Comparison operators so that Values can easily be used with standard
  925. // library algorithms and associative containers.
  926. BASE_EXPORT friend bool operator==(const Value& lhs, const Value& rhs);
  927. BASE_EXPORT friend bool operator!=(const Value& lhs, const Value& rhs);
  928. BASE_EXPORT friend bool operator<(const Value& lhs, const Value& rhs);
  929. BASE_EXPORT friend bool operator>(const Value& lhs, const Value& rhs);
  930. BASE_EXPORT friend bool operator<=(const Value& lhs, const Value& rhs);
  931. BASE_EXPORT friend bool operator>=(const Value& lhs, const Value& rhs);
  932. BASE_EXPORT friend bool operator==(const Value& lhs, bool rhs);
  933. friend bool operator==(bool lhs, const Value& rhs) { return rhs == lhs; }
  934. friend bool operator!=(const Value& lhs, bool rhs) { return !(lhs == rhs); }
  935. friend bool operator!=(bool lhs, const Value& rhs) { return !(lhs == rhs); }
  936. template <typename T>
  937. friend bool operator==(const Value& lhs, const T* rhs) = delete;
  938. template <typename T>
  939. friend bool operator==(const T* lhs, const Value& rhs) = delete;
  940. template <typename T>
  941. friend bool operator!=(const Value& lhs, const T* rhs) = delete;
  942. template <typename T>
  943. friend bool operator!=(const T* lhs, const Value& rhs) = delete;
  944. BASE_EXPORT friend bool operator==(const Value& lhs, int rhs);
  945. friend bool operator==(int lhs, const Value& rhs) { return rhs == lhs; }
  946. friend bool operator!=(const Value& lhs, int rhs) { return !(lhs == rhs); }
  947. friend bool operator!=(int lhs, const Value& rhs) { return !(lhs == rhs); }
  948. BASE_EXPORT friend bool operator==(const Value& lhs, double rhs);
  949. friend bool operator==(double lhs, const Value& rhs) { return rhs == lhs; }
  950. friend bool operator!=(const Value& lhs, double rhs) { return !(lhs == rhs); }
  951. friend bool operator!=(double lhs, const Value& rhs) { return !(lhs == rhs); }
  952. // Note: StringPiece16 overload intentionally omitted: Value internally stores
  953. // strings as UTF-8. While it is possible to implement a comparison operator
  954. // that would not require first creating a new UTF-8 string from the UTF-16
  955. // string argument, it is simpler to just not implement it at all for a rare
  956. // use case.
  957. BASE_EXPORT friend bool operator==(const Value& lhs, StringPiece rhs);
  958. friend bool operator==(StringPiece lhs, const Value& rhs) {
  959. return rhs == lhs;
  960. }
  961. friend bool operator!=(const Value& lhs, StringPiece rhs) {
  962. return !(lhs == rhs);
  963. }
  964. friend bool operator!=(StringPiece lhs, const Value& rhs) {
  965. return !(lhs == rhs);
  966. }
  967. friend bool operator==(const Value& lhs, const char* rhs) {
  968. return lhs == StringPiece(rhs);
  969. }
  970. friend bool operator==(const char* lhs, const Value& rhs) {
  971. return rhs == lhs;
  972. }
  973. friend bool operator!=(const Value& lhs, const char* rhs) {
  974. return !(lhs == rhs);
  975. }
  976. friend bool operator!=(const char* lhs, const Value& rhs) {
  977. return !(lhs == rhs);
  978. }
  979. friend bool operator==(const Value& lhs, const std::string& rhs) {
  980. return lhs == StringPiece(rhs);
  981. }
  982. friend bool operator==(const std::string& lhs, const Value& rhs) {
  983. return rhs == lhs;
  984. }
  985. friend bool operator!=(const Value& lhs, const std::string& rhs) {
  986. return !(lhs == rhs);
  987. }
  988. friend bool operator!=(const std::string& lhs, const Value& rhs) {
  989. return !(lhs == rhs);
  990. }
  991. // Note: Blob support intentionally omitted as an experiment for potentially
  992. // wholly removing Blob support from Value itself in the future.
  993. BASE_EXPORT friend bool operator==(const Value& lhs, const Value::Dict& rhs);
  994. friend bool operator==(const Value::Dict& lhs, const Value& rhs) {
  995. return rhs == lhs;
  996. }
  997. friend bool operator!=(const Value& lhs, const Value::Dict& rhs) {
  998. return !(lhs == rhs);
  999. }
  1000. friend bool operator!=(const Value::Dict& lhs, const Value& rhs) {
  1001. return !(lhs == rhs);
  1002. }
  1003. BASE_EXPORT friend bool operator==(const Value& lhs, const Value::List& rhs);
  1004. friend bool operator==(const Value::List& lhs, const Value& rhs) {
  1005. return rhs == lhs;
  1006. }
  1007. friend bool operator!=(const Value& lhs, const Value::List& rhs) {
  1008. return !(lhs == rhs);
  1009. }
  1010. friend bool operator!=(const Value::List& lhs, const Value& rhs) {
  1011. return !(lhs == rhs);
  1012. }
  1013. // Estimates dynamic memory usage. Requires tracing support
  1014. // (enable_base_tracing gn flag), otherwise always returns 0. See
  1015. // base/trace_event/memory_usage_estimator.h for more info.
  1016. size_t EstimateMemoryUsage() const;
  1017. // Serializes to a string for logging and debug purposes.
  1018. std::string DebugString() const;
  1019. #if BUILDFLAG(ENABLE_BASE_TRACING)
  1020. // Write this object into a trace.
  1021. void WriteIntoTrace(perfetto::TracedValue) const;
  1022. #endif // BUILDFLAG(ENABLE_BASE_TRACING)
  1023. template <typename Visitor>
  1024. auto Visit(Visitor&& visitor) const {
  1025. return absl::visit(std::forward<Visitor>(visitor), data_);
  1026. }
  1027. protected:
  1028. // TODO(https://crbug.com/1187091): Once deprecated list methods and ListView
  1029. // have been removed, make this a private member of List.
  1030. using ListStorage = DeprecatedListStorage;
  1031. // Checked convenience accessors for dict and list.
  1032. const LegacyDictStorage& dict() const { return GetDict().storage_; }
  1033. LegacyDictStorage& dict() { return GetDict().storage_; }
  1034. const ListStorage& list() const { return GetList().storage_; }
  1035. ListStorage& list() { return GetList().storage_; }
  1036. // Internal constructors, allowing the simplify the implementation of Clone().
  1037. explicit Value(const LegacyDictStorage& storage);
  1038. explicit Value(LegacyDictStorage&& storage) noexcept;
  1039. private:
  1040. // For access to DoubleStorage.
  1041. friend class ValueView;
  1042. // Special case for doubles, which are aligned to 8 bytes on some
  1043. // 32-bit architectures. In this case, a simple declaration as a
  1044. // double member would make the whole union 8 byte-aligned, which
  1045. // would also force 4 bytes of wasted padding space before it in
  1046. // the Value layout.
  1047. //
  1048. // To override this, store the value as an array of 32-bit integers, and
  1049. // perform the appropriate bit casts when reading / writing to it.
  1050. class BASE_EXPORT DoubleStorage {
  1051. public:
  1052. explicit DoubleStorage(double v);
  1053. DoubleStorage(const DoubleStorage&) = default;
  1054. DoubleStorage& operator=(const DoubleStorage&) = default;
  1055. // Provide an implicit conversion to double to simplify the use of visitors
  1056. // with `Value::Visit()`. Otherwise, visitors would need a branch for
  1057. // handling `DoubleStorage` like:
  1058. //
  1059. // value.Visit([] (const auto& member) {
  1060. // using T = std::decay_t<decltype(member)>;
  1061. // if constexpr (std::is_same_v<T, Value::DoubleStorage>) {
  1062. // SomeFunction(double{member});
  1063. // } else {
  1064. // SomeFunction(member);
  1065. // }
  1066. // });
  1067. operator double() const { return base::bit_cast<double>(v_); }
  1068. private:
  1069. friend bool operator==(const DoubleStorage& lhs, const DoubleStorage& rhs) {
  1070. return double{lhs} == double{rhs};
  1071. }
  1072. friend bool operator!=(const DoubleStorage& lhs, const DoubleStorage& rhs) {
  1073. return !(lhs == rhs);
  1074. }
  1075. friend bool operator<(const DoubleStorage& lhs, const DoubleStorage& rhs) {
  1076. return double{lhs} < double{rhs};
  1077. }
  1078. friend bool operator>(const DoubleStorage& lhs, const DoubleStorage& rhs) {
  1079. return rhs < lhs;
  1080. }
  1081. friend bool operator<=(const DoubleStorage& lhs, const DoubleStorage& rhs) {
  1082. return !(rhs < lhs);
  1083. }
  1084. friend bool operator>=(const DoubleStorage& lhs, const DoubleStorage& rhs) {
  1085. return !(lhs < rhs);
  1086. }
  1087. alignas(4) std::array<char, sizeof(double)> v_;
  1088. };
  1089. // Internal constructors, allowing the simplify the implementation of Clone().
  1090. explicit Value(absl::monostate);
  1091. explicit Value(DoubleStorage storage);
  1092. // A helper for static functions used for cloning a Value or a ValueView.
  1093. class CloningHelper;
  1094. absl::variant<absl::monostate,
  1095. bool,
  1096. int,
  1097. DoubleStorage,
  1098. std::string,
  1099. BlobStorage,
  1100. Dict,
  1101. List>
  1102. data_;
  1103. };
  1104. // DictionaryValue provides a key-value dictionary with (optional) "path"
  1105. // parsing for recursive access; see the comment at the top of the file. Keys
  1106. // are std::string's and should be UTF-8 encoded.
  1107. //
  1108. // DEPRECATED: prefer `Value::Dict`.
  1109. class BASE_EXPORT DictionaryValue : public Value {
  1110. public:
  1111. // Returns `value` if it is a dictionary, nullptr otherwise.
  1112. static std::unique_ptr<DictionaryValue> From(std::unique_ptr<Value> value);
  1113. DictionaryValue();
  1114. explicit DictionaryValue(const LegacyDictStorage& in_dict);
  1115. explicit DictionaryValue(LegacyDictStorage&& in_dict) noexcept;
  1116. // Sets the Value associated with the given path starting from this object.
  1117. // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
  1118. // into the next DictionaryValue down. Obviously, "." can't be used
  1119. // within a key, but there are no other restrictions on keys.
  1120. // If the key at any step of the way doesn't exist, or exists but isn't
  1121. // a DictionaryValue, a new DictionaryValue will be created and attached
  1122. // to the path in that location. `in_value` must be non-null.
  1123. // Returns a pointer to the inserted value.
  1124. //
  1125. // DEPRECATED: prefer `Value::Dict::Set()` (if the path only has one
  1126. // component, i.e. has no dots), or `Value::Dict::SetByDottedPath()`
  1127. // otherwise.
  1128. Value* Set(StringPiece path, std::unique_ptr<Value> in_value);
  1129. // Convenience forms of Set(). These methods will replace any existing
  1130. // value at that path, even if it has a different type.
  1131. //
  1132. // DEPRECATED: prefer `Value::Dict::Set()` (if the path only has one
  1133. // component, i.e. has no dots), or `Value::Dict::SetByDottedPath()`
  1134. // otherwise.
  1135. Value* SetBoolean(StringPiece path, bool in_value);
  1136. // DEPRECATED: prefer `Value::Dict::Set()` (if the path only has one
  1137. // component, i.e. has no dots), or `Value::Dict::SetByDottedPath()`
  1138. // otherwise.
  1139. Value* SetInteger(StringPiece path, int in_value);
  1140. // DEPRECATED: prefer `Value::Dict::Set()` (if the path only has one
  1141. // component, i.e. has no dots), or `Value::Dict::SetByDottedPath()`
  1142. // otherwise.
  1143. Value* SetString(StringPiece path, StringPiece in_value);
  1144. // DEPRECATED: prefer `Value::Dict::Set()` (if the path only has one
  1145. // component, i.e. has no dots), or `Value::Dict::SetByDottedPath()`
  1146. // otherwise.
  1147. Value* SetString(StringPiece path, const std::u16string& in_value);
  1148. // DEPRECATED: prefer `Value::Dict::Set()` (if the path only has one
  1149. // component, i.e. has no dots), or `Value::Dict::SetByDottedPath()`
  1150. // otherwise.
  1151. ListValue* SetList(StringPiece path, std::unique_ptr<ListValue> in_value);
  1152. // Like Set(), but without special treatment of '.'. This allows e.g. URLs to
  1153. // be used as paths.
  1154. //
  1155. // DEPRECATED: prefer `Value::Dict::Set()`.
  1156. Value* SetWithoutPathExpansion(StringPiece key,
  1157. std::unique_ptr<Value> in_value);
  1158. // Gets the Value associated with the given path starting from this object.
  1159. // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
  1160. // into the next DictionaryValue down. If the path can be resolved
  1161. // successfully, the value for the last key in the path will be returned
  1162. // through the `out_value` parameter, and the function will return true.
  1163. // Otherwise, it will return false and `out_value` will be untouched.
  1164. // Note that the dictionary always owns the value that's returned.
  1165. // `out_value` is optional and will only be set if non-NULL.
  1166. //
  1167. // DEPRECATED: prefer `Value::Dict::Find()` (if the path only has one
  1168. // component, i.e. has no dots), or `Value::Dict::FindByDottedPath()`
  1169. // otherwise.
  1170. bool Get(StringPiece path, const Value** out_value) const;
  1171. bool Get(StringPiece path, Value** out_value);
  1172. // These are convenience forms of `Get()`. The value will be retrieved
  1173. // and the return value will be true if the path is valid and the value at
  1174. // the end of the path can be returned in the form specified.
  1175. // `out_value` is optional and will only be set if non-NULL.
  1176. //
  1177. // DEPRECATED: prefer `Value::Dict::FindInt()` (if the path only has one
  1178. // component, i.e. has no dots), or `Value::Dict::FindIntByDottedPath()`
  1179. // otherwise.
  1180. bool GetInteger(StringPiece path, int* out_value) const;
  1181. // DEPRECATED: prefer `Value::Dict::FindString()` (if the path only has one
  1182. // component, i.e. has no dots), or `Value::Dict::FindStringByDottedPath()`
  1183. // otherwise.
  1184. bool GetString(StringPiece path, std::string* out_value) const;
  1185. // DEPRECATED: prefer `Value::Dict::FindDict()` (if the path only has one
  1186. // component, i.e. has no dots), or `Value::Dict::FindDictByDottedPath()`
  1187. // otherwise.
  1188. bool GetDictionary(StringPiece path, const DictionaryValue** out_value) const;
  1189. bool GetDictionary(StringPiece path, DictionaryValue** out_value);
  1190. // DEPRECATED: prefer `Value::Dict::FindList()` (if the path only has one
  1191. // component, i.e. has no dots), or `Value::Dict::FindListByDottedPath()`
  1192. // otherwise.
  1193. bool GetList(StringPiece path, const ListValue** out_value) const;
  1194. bool GetList(StringPiece path, ListValue** out_value);
  1195. // Swaps contents with the `other` dictionary.
  1196. void Swap(DictionaryValue* other);
  1197. // This class provides an iterator over both keys and values in the
  1198. // dictionary. It can't be used to modify the dictionary.
  1199. //
  1200. // DEPRECATED: Use a range-based for loop over `base::Value::Dict` directly
  1201. // instead.
  1202. class BASE_EXPORT Iterator {
  1203. public:
  1204. explicit Iterator(const DictionaryValue& target);
  1205. Iterator(const Iterator& other);
  1206. ~Iterator();
  1207. bool IsAtEnd() const { return it_ == target_.DictItems().end(); }
  1208. void Advance() { ++it_; }
  1209. const std::string& key() const { return it_->first; }
  1210. const Value& value() const { return it_->second; }
  1211. private:
  1212. const DictionaryValue& target_;
  1213. detail::const_dict_iterator it_;
  1214. };
  1215. // DEPRECATED, use `Value::Dict::Clone()` instead.
  1216. // TODO(crbug.com/646113): Delete this and migrate callsites.
  1217. std::unique_ptr<DictionaryValue> CreateDeepCopy() const;
  1218. };
  1219. // This type of Value represents a list of other Value values.
  1220. //
  1221. // DEPRECATED: prefer `base::Value::List`.
  1222. class BASE_EXPORT ListValue : public Value {
  1223. public:
  1224. using const_iterator = ListView::const_iterator;
  1225. using iterator = ListView::iterator;
  1226. // Returns `value` if it is a list, nullptr otherwise.
  1227. static std::unique_ptr<ListValue> From(std::unique_ptr<Value> value);
  1228. ListValue();
  1229. // Appends a Value to the end of the list.
  1230. // DEPRECATED: prefer `Value::List::Append()`.
  1231. using Value::Append;
  1232. // DEPRECATED: prefer `Value::List::Append()`. Provided to simplify
  1233. // incremental migration and intentionally only defined on ListValue and not
  1234. // Value.
  1235. void Append(base::Value::Dict in_dict);
  1236. void Append(base::Value::List in_list);
  1237. // Swaps contents with the `other` list.
  1238. //
  1239. // DEPRECATED: prefer `base::Value::List` + `std::swap()`.
  1240. void Swap(ListValue* other);
  1241. // Iteration: Use a range-based for loop over `base::Value::List` directly
  1242. // instead.
  1243. };
  1244. // Adapter so `Value::Dict` or `Value::List` can be directly passed to JSON
  1245. // serialization methods without having to clone the contents and transfer
  1246. // ownership of the clone to a `Value` wrapper object.
  1247. //
  1248. // Like `StringPiece` and `span<T>`, this adapter does NOT retain ownership. Any
  1249. // underlying object that is passed by reference (i.e. `std::string`,
  1250. // `Value::BlobStorage`, `Value::Dict`, `Value::List`, or `Value`) MUST remain
  1251. // live as long as there is a `ValueView` referencing it.
  1252. //
  1253. // While it might be nice to just use the `absl::variant` type directly, the
  1254. // need to use `std::reference_wrapper` makes it clunky. `absl::variant` and
  1255. // `std::reference_wrapper` both support implicit construction, but C++ only
  1256. // allows at most one user-defined conversion in an implicit conversion
  1257. // sequence. If this adapter and its implicit constructors did not exist,
  1258. // callers would need to use `std::ref` or `std::cref` to pass `Value::Dict` or
  1259. // `Value::List` to a function with a `ValueView` parameter.
  1260. class BASE_EXPORT GSL_POINTER ValueView {
  1261. public:
  1262. ValueView() = default;
  1263. ValueView(bool value) : data_view_(value) {}
  1264. template <typename T>
  1265. ValueView(const T*) = delete;
  1266. ValueView(int value) : data_view_(value) {}
  1267. ValueView(double value)
  1268. : data_view_(absl::in_place_type_t<Value::DoubleStorage>(), value) {}
  1269. ValueView(StringPiece value) : data_view_(value) {}
  1270. ValueView(const char* value) : ValueView(StringPiece(value)) {}
  1271. ValueView(const std::string& value) : ValueView(StringPiece(value)) {}
  1272. // Note: UTF-16 is intentionally not supported. ValueView is intended to be a
  1273. // low-cost view abstraction, but Value internally represents strings as
  1274. // UTF-8, so it would not be possible to implement this without allocating an
  1275. // entirely new UTF-8 string.
  1276. ValueView(const Value::BlobStorage& value) : data_view_(value) {}
  1277. ValueView(const Value::Dict& value) : data_view_(value) {}
  1278. ValueView(const Value::List& value) : data_view_(value) {}
  1279. ValueView(const Value& value);
  1280. // This is the only 'getter' method provided as `ValueView` is not intended
  1281. // to be a general replacement of `Value`.
  1282. template <typename Visitor>
  1283. auto Visit(Visitor&& visitor) const {
  1284. return absl::visit(std::forward<Visitor>(visitor), data_view_);
  1285. }
  1286. // Returns a clone of the underlying Value.
  1287. Value ToValue() const;
  1288. private:
  1289. using ViewType =
  1290. absl::variant<absl::monostate,
  1291. bool,
  1292. int,
  1293. Value::DoubleStorage,
  1294. StringPiece,
  1295. std::reference_wrapper<const Value::BlobStorage>,
  1296. std::reference_wrapper<const Value::Dict>,
  1297. std::reference_wrapper<const Value::List>>;
  1298. public:
  1299. using DoubleStorageForTest = Value::DoubleStorage;
  1300. const ViewType& data_view_for_test() const { return data_view_; }
  1301. private:
  1302. ViewType data_view_;
  1303. };
  1304. // This interface is implemented by classes that know how to serialize
  1305. // Value objects.
  1306. class BASE_EXPORT ValueSerializer {
  1307. public:
  1308. virtual ~ValueSerializer();
  1309. virtual bool Serialize(ValueView root) = 0;
  1310. };
  1311. // This interface is implemented by classes that know how to deserialize Value
  1312. // objects.
  1313. class BASE_EXPORT ValueDeserializer {
  1314. public:
  1315. virtual ~ValueDeserializer();
  1316. // This method deserializes the subclass-specific format into a Value object.
  1317. // If the return value is non-NULL, the caller takes ownership of returned
  1318. // Value.
  1319. //
  1320. // If the return value is nullptr, and if `error_code` is non-nullptr,
  1321. // `*error_code` will be set to an integer value representing the underlying
  1322. // error. See "enum ErrorCode" below for more detail about the integer value.
  1323. //
  1324. // If `error_message` is non-nullptr, it will be filled in with a formatted
  1325. // error message including the location of the error if appropriate.
  1326. virtual std::unique_ptr<Value> Deserialize(int* error_code,
  1327. std::string* error_message) = 0;
  1328. // The integer-valued error codes form four groups:
  1329. // - The value 0 means no error.
  1330. // - Values between 1 and 999 inclusive mean an error in the data (i.e.
  1331. // content). The bytes being deserialized are not in the right format.
  1332. // - Values 1000 and above mean an error in the metadata (i.e. context). The
  1333. // file could not be read, the network is down, etc.
  1334. // - Negative values are reserved.
  1335. //
  1336. // These values are persisted to logs. Entries should not be renumbered and
  1337. // numeric values should never be reused.
  1338. enum ErrorCode {
  1339. kErrorCodeNoError = 0,
  1340. // kErrorCodeInvalidFormat is a generic error code for "the data is not in
  1341. // the right format". Subclasses of ValueDeserializer may return other
  1342. // values for more specific errors.
  1343. kErrorCodeInvalidFormat = 1,
  1344. // kErrorCodeFirstMetadataError is the minimum value (inclusive) of the
  1345. // range of metadata errors.
  1346. kErrorCodeFirstMetadataError = 1000,
  1347. };
  1348. // The `error_code` argument can be one of the ErrorCode values, but it is
  1349. // not restricted to only being 0, 1 or 1000. Subclasses of ValueDeserializer
  1350. // can define their own error code values.
  1351. static inline bool ErrorCodeIsDataError(int error_code) {
  1352. return (kErrorCodeInvalidFormat <= error_code) &&
  1353. (error_code < kErrorCodeFirstMetadataError);
  1354. }
  1355. };
  1356. // Stream operator so Values can be pretty printed by gtest.
  1357. BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
  1358. BASE_EXPORT std::ostream& operator<<(std::ostream& out,
  1359. const Value::Dict& dict);
  1360. BASE_EXPORT std::ostream& operator<<(std::ostream& out,
  1361. const Value::List& list);
  1362. // Hints for DictionaryValue and ListValue; otherwise, gtest tends to prefer the
  1363. // default template implementation over an upcast to Value.
  1364. BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
  1365. const DictionaryValue& value) {
  1366. return out << static_cast<const Value&>(value);
  1367. }
  1368. BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
  1369. const ListValue& value) {
  1370. return out << static_cast<const Value&>(value);
  1371. }
  1372. // Stream operator so that enum class Types can be used in log statements.
  1373. BASE_EXPORT std::ostream& operator<<(std::ostream& out,
  1374. const Value::Type& type);
  1375. } // namespace base
  1376. #endif // BASE_VALUES_H_