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.
5 #include "base/values.h"
7 // values.h is a widely included header and its size has significant impact on
8 // build time. Try not to raise this limit unless absolutely necessary. See
9 // https://chromium.googlesource.com/chromium/src/+/HEAD/docs/wmax_tokens.md
11 #pragma clang max_tokens_here 400000
20 #include "base/as_const.h"
21 #include "base/bit_cast.h"
22 #include "base/check_op.h"
23 #include "base/containers/checked_iterators.h"
24 #include "base/containers/contains.h"
25 #include "base/cxx17_backports.h"
26 #include "base/json/json_writer.h"
27 #include "base/macros.h"
28 #include "base/memory/ptr_util.h"
29 #include "base/notreached.h"
30 #include "base/ranges/algorithm.h"
31 #include "base/strings/string_util.h"
32 #include "base/strings/utf_string_conversions.h"
33 #include "base/trace_event/base_tracing.h"
34 #include "base/tracing_buildflags.h"
35 #include "third_party/abseil-cpp/absl/types/optional.h"
36 #include "third_party/abseil-cpp/absl/types/variant.h"
38 #if BUILDFLAG(ENABLE_BASE_TRACING)
39 #include "base/trace_event/memory_usage_estimator.h" // no-presubmit-check
40 #endif // BUILDFLAG(ENABLE_BASE_TRACING)
46 const char* const kTypeNames[] = {"null", "boolean", "integer", "double",
47 "string", "binary", "dictionary", "list"};
48 static_assert(base::size(kTypeNames) ==
49 static_cast<size_t>(Value::Type::LIST) + 1,
50 "kTypeNames Has Wrong Size");
52 std::unique_ptr<Value> CopyWithoutEmptyChildren(const Value& node);
54 // Make a deep copy of |node|, but don't include empty lists or dictionaries
55 // in the copy. It's possible for this function to return NULL and it
56 // expects |node| to always be non-NULL.
57 std::unique_ptr<Value> CopyListWithoutEmptyChildren(const Value& list) {
58 Value copy(Value::Type::LIST);
59 for (const auto& entry : list.GetList()) {
60 std::unique_ptr<Value> child_copy = CopyWithoutEmptyChildren(entry);
62 copy.Append(std::move(*child_copy));
64 return copy.GetList().empty() ? nullptr
65 : std::make_unique<Value>(std::move(copy));
68 std::unique_ptr<DictionaryValue> CopyDictionaryWithoutEmptyChildren(
69 const DictionaryValue& dict) {
70 std::unique_ptr<DictionaryValue> copy;
71 for (auto it : dict.DictItems()) {
72 std::unique_ptr<Value> child_copy = CopyWithoutEmptyChildren(it.second);
75 copy = std::make_unique<DictionaryValue>();
76 copy->SetKey(it.first, std::move(*child_copy));
82 std::unique_ptr<Value> CopyWithoutEmptyChildren(const Value& node) {
83 switch (node.type()) {
84 case Value::Type::LIST:
85 return CopyListWithoutEmptyChildren(static_cast<const ListValue&>(node));
87 case Value::Type::DICTIONARY:
88 return CopyDictionaryWithoutEmptyChildren(
89 static_cast<const DictionaryValue&>(node));
92 return std::make_unique<Value>(node.Clone());
96 // Helper class to enumerate the path components from a StringPiece
97 // without performing heap allocations. Components are simply separated
98 // by single dots (e.g. "foo.bar.baz" -> ["foo", "bar", "baz"]).
101 // PathSplitter splitter(some_path);
102 // while (splitter.HasNext()) {
103 // StringPiece component = splitter.Next();
109 explicit PathSplitter(StringPiece path) : path_(path) {}
111 bool HasNext() const { return pos_ < path_.size(); }
116 size_t pos = path_.find('.', start);
118 if (pos == path_.npos) {
125 return path_.substr(start, end - start);
136 Value Value::FromUniquePtrValue(std::unique_ptr<Value> val) {
137 return std::move(*val);
141 std::unique_ptr<Value> Value::ToUniquePtrValue(Value val) {
142 return std::make_unique<Value>(std::move(val));
146 const DictionaryValue& Value::AsDictionaryValue(const Value& val) {
147 CHECK(val.is_dict());
148 return static_cast<const DictionaryValue&>(val);
152 const ListValue& Value::AsListValue(const Value& val) {
153 CHECK(val.is_list());
154 return static_cast<const ListValue&>(val);
157 Value::Value() noexcept = default;
159 Value::Value(Value&& that) noexcept = default;
161 Value::Value(Type type) {
162 // Initialize with the default value.
168 data_.emplace<bool>(false);
171 data_.emplace<int>(0);
174 data_.emplace<DoubleStorage>(bit_cast<DoubleStorage>(0.0));
177 data_.emplace<std::string>();
180 data_.emplace<BlobStorage>();
182 case Type::DICTIONARY:
183 data_.emplace<LegacyDictStorage>();
186 data_.emplace<ListStorage>();
193 Value::Value(bool in_bool) : data_(in_bool) {}
195 Value::Value(int in_int) : data_(in_int) {}
197 Value::Value(double in_double) : data_(bit_cast<DoubleStorage>(in_double)) {
198 if (!std::isfinite(in_double)) {
199 NOTREACHED() << "Non-finite (i.e. NaN or positive/negative infinity) "
200 << "values cannot be represented in JSON";
201 data_ = bit_cast<DoubleStorage>(0.0);
205 Value::Value(const char* in_string) : Value(std::string(in_string)) {}
207 Value::Value(StringPiece in_string) : Value(std::string(in_string)) {}
209 Value::Value(std::string&& in_string) noexcept : data_(std::move(in_string)) {
210 DCHECK(IsStringUTF8AllowingNoncharacters(GetString()));
213 Value::Value(const char16_t* in_string16) : Value(StringPiece16(in_string16)) {}
215 Value::Value(StringPiece16 in_string16) : Value(UTF16ToUTF8(in_string16)) {}
217 Value::Value(const std::vector<char>& in_blob)
218 : data_(absl::in_place_type_t<BlobStorage>(),
222 Value::Value(base::span<const uint8_t> in_blob)
223 : data_(absl::in_place_type_t<BlobStorage>(),
227 Value::Value(BlobStorage&& in_blob) noexcept : data_(std::move(in_blob)) {}
229 Value::Value(const DictStorage& in_dict)
230 : data_(absl::in_place_type_t<LegacyDictStorage>()) {
231 dict().reserve(in_dict.size());
232 for (const auto& it : in_dict) {
233 dict().try_emplace(dict().end(), it.first,
234 std::make_unique<Value>(it.second.Clone()));
238 Value::Value(DictStorage&& in_dict) noexcept
239 : data_(absl::in_place_type_t<LegacyDictStorage>()) {
240 dict().reserve(in_dict.size());
241 for (auto& it : in_dict) {
242 dict().try_emplace(dict().end(), std::move(it.first),
243 std::make_unique<Value>(std::move(it.second)));
247 Value::Value(span<const Value> in_list)
248 : data_(absl::in_place_type_t<ListStorage>()) {
249 list().reserve(in_list.size());
250 for (const auto& val : in_list)
251 list().emplace_back(val.Clone());
254 Value::Value(ListStorage&& in_list) noexcept : data_(std::move(in_list)) {}
256 Value& Value::operator=(Value&& that) noexcept = default;
258 Value::Value(const LegacyDictStorage& storage)
259 : data_(absl::in_place_type_t<LegacyDictStorage>()) {
260 dict().reserve(storage.size());
261 for (const auto& it : storage) {
262 dict().try_emplace(dict().end(), it.first,
263 std::make_unique<Value>(it.second->Clone()));
267 Value::Value(LegacyDictStorage&& storage) noexcept
268 : data_(std::move(storage)) {}
270 Value::Value(absl::monostate) {}
272 Value::Value(DoubleStorage storage) : data_(std::move(storage)) {}
274 double Value::AsDoubleInternal() const {
275 return bit_cast<double>(absl::get<DoubleStorage>(data_));
278 Value Value::Clone() const {
279 return absl::visit([](const auto& member) { return Value(member); }, data_);
282 Value::~Value() = default;
285 const char* Value::GetTypeName(Value::Type type) {
286 DCHECK_GE(static_cast<int>(type), 0);
287 DCHECK_LT(static_cast<size_t>(type), base::size(kTypeNames));
288 return kTypeNames[static_cast<size_t>(type)];
291 absl::optional<bool> Value::GetIfBool() const {
292 return is_bool() ? absl::make_optional(GetBool()) : absl::nullopt;
295 absl::optional<int> Value::GetIfInt() const {
296 return is_int() ? absl::make_optional(GetInt()) : absl::nullopt;
299 absl::optional<double> Value::GetIfDouble() const {
300 return (is_int() || is_double()) ? absl::make_optional(GetDouble())
304 const std::string* Value::GetIfString() const {
305 return absl::get_if<std::string>(&data_);
308 const Value::BlobStorage* Value::GetIfBlob() const {
309 return absl::get_if<BlobStorage>(&data_);
312 bool Value::GetBool() const {
313 return absl::get<bool>(data_);
316 int Value::GetInt() const {
317 return absl::get<int>(data_);
320 double Value::GetDouble() const {
322 return AsDoubleInternal();
329 const std::string& Value::GetString() const {
330 return absl::get<std::string>(data_);
333 std::string& Value::GetString() {
334 return absl::get<std::string>(data_);
337 const Value::BlobStorage& Value::GetBlob() const {
338 return absl::get<BlobStorage>(data_);
341 Value::ListView Value::GetList() {
345 Value::ConstListView Value::GetList() const {
349 Value::ListStorage Value::TakeList() && {
350 return std::exchange(list(), {});
353 void Value::Append(bool value) {
354 list().emplace_back(value);
357 void Value::Append(int value) {
358 list().emplace_back(value);
361 void Value::Append(double value) {
362 list().emplace_back(value);
365 void Value::Append(const char* value) {
366 list().emplace_back(value);
369 void Value::Append(StringPiece value) {
370 list().emplace_back(value);
373 void Value::Append(std::string&& value) {
374 list().emplace_back(std::move(value));
377 void Value::Append(const char16_t* value) {
378 list().emplace_back(value);
381 void Value::Append(StringPiece16 value) {
382 list().emplace_back(value);
385 void Value::Append(Value&& value) {
386 list().emplace_back(std::move(value));
389 CheckedContiguousIterator<Value> Value::Insert(
390 CheckedContiguousConstIterator<Value> pos,
392 const auto offset = pos - make_span(list()).begin();
393 list().insert(list().begin() + offset, std::move(value));
394 return make_span(list()).begin() + offset;
397 bool Value::EraseListIter(CheckedContiguousConstIterator<Value> iter) {
398 const auto offset = iter - ListView(list()).begin();
399 auto list_iter = list().begin() + offset;
400 if (list_iter == list().end())
403 list().erase(list_iter);
407 size_t Value::EraseListValue(const Value& val) {
408 return EraseListValueIf([&val](const Value& other) { return val == other; });
411 void Value::ClearList() {
415 Value* Value::FindKey(StringPiece key) {
416 return const_cast<Value*>(as_const(*this).FindKey(key));
419 const Value* Value::FindKey(StringPiece key) const {
420 auto found = dict().find(key);
421 if (found == dict().end())
423 return found->second.get();
426 Value* Value::FindKeyOfType(StringPiece key, Type type) {
427 return const_cast<Value*>(as_const(*this).FindKeyOfType(key, type));
430 const Value* Value::FindKeyOfType(StringPiece key, Type type) const {
431 const Value* result = FindKey(key);
432 if (!result || result->type() != type)
437 absl::optional<bool> Value::FindBoolKey(StringPiece key) const {
438 const Value* result = FindKeyOfType(key, Type::BOOLEAN);
439 return result ? absl::make_optional(result->GetBool()) : absl::nullopt;
442 absl::optional<int> Value::FindIntKey(StringPiece key) const {
443 const Value* result = FindKeyOfType(key, Type::INTEGER);
444 return result ? absl::make_optional(result->GetInt()) : absl::nullopt;
447 absl::optional<double> Value::FindDoubleKey(StringPiece key) const {
448 if (const Value* cur = FindKey(key)) {
449 if (cur->is_int() || cur->is_double())
450 return cur->GetDouble();
453 return absl::nullopt;
456 const std::string* Value::FindStringKey(StringPiece key) const {
457 const Value* result = FindKey(key);
458 return result ? absl::get_if<std::string>(&result->data_) : nullptr;
461 std::string* Value::FindStringKey(StringPiece key) {
462 return const_cast<std::string*>(as_const(*this).FindStringKey(key));
465 const Value::BlobStorage* Value::FindBlobKey(StringPiece key) const {
466 const Value* result = FindKey(key);
467 return result ? absl::get_if<BlobStorage>(&result->data_) : nullptr;
470 const Value* Value::FindDictKey(StringPiece key) const {
471 return FindKeyOfType(key, Type::DICTIONARY);
474 Value* Value::FindDictKey(StringPiece key) {
475 return FindKeyOfType(key, Type::DICTIONARY);
478 const Value* Value::FindListKey(StringPiece key) const {
479 return FindKeyOfType(key, Type::LIST);
482 Value* Value::FindListKey(StringPiece key) {
483 return FindKeyOfType(key, Type::LIST);
486 Value* Value::SetKey(StringPiece key, Value&& value) {
487 return SetKeyInternal(key, std::make_unique<Value>(std::move(value)));
490 Value* Value::SetKey(std::string&& key, Value&& value) {
492 .insert_or_assign(std::move(key),
493 std::make_unique<Value>(std::move(value)))
494 .first->second.get();
497 Value* Value::SetKey(const char* key, Value&& value) {
498 return SetKeyInternal(key, std::make_unique<Value>(std::move(value)));
501 Value* Value::SetBoolKey(StringPiece key, bool value) {
502 return SetKeyInternal(key, std::make_unique<Value>(value));
505 Value* Value::SetIntKey(StringPiece key, int value) {
506 return SetKeyInternal(key, std::make_unique<Value>(value));
509 Value* Value::SetDoubleKey(StringPiece key, double value) {
510 return SetKeyInternal(key, std::make_unique<Value>(value));
513 Value* Value::SetStringKey(StringPiece key, StringPiece value) {
514 return SetKeyInternal(key, std::make_unique<Value>(value));
517 Value* Value::SetStringKey(StringPiece key, StringPiece16 value) {
518 return SetKeyInternal(key, std::make_unique<Value>(value));
521 Value* Value::SetStringKey(StringPiece key, const char* value) {
522 return SetKeyInternal(key, std::make_unique<Value>(value));
525 Value* Value::SetStringKey(StringPiece key, std::string&& value) {
526 return SetKeyInternal(key, std::make_unique<Value>(std::move(value)));
529 bool Value::RemoveKey(StringPiece key) {
530 return dict().erase(key) != 0;
533 absl::optional<Value> Value::ExtractKey(StringPiece key) {
534 auto found = dict().find(key);
535 if (found == dict().end())
536 return absl::nullopt;
538 Value value = std::move(*found->second);
540 return std::move(value);
543 Value* Value::FindPath(StringPiece path) {
544 return const_cast<Value*>(as_const(*this).FindPath(path));
547 const Value* Value::FindPath(StringPiece path) const {
549 const Value* cur = this;
550 PathSplitter splitter(path);
551 while (splitter.HasNext()) {
552 if (!cur->is_dict() || (cur = cur->FindKey(splitter.Next())) == nullptr)
558 Value* Value::FindPathOfType(StringPiece path, Type type) {
559 return const_cast<Value*>(as_const(*this).FindPathOfType(path, type));
562 const Value* Value::FindPathOfType(StringPiece path, Type type) const {
563 const Value* cur = FindPath(path);
564 if (!cur || cur->type() != type)
569 absl::optional<bool> Value::FindBoolPath(StringPiece path) const {
570 const Value* cur = FindPath(path);
571 if (!cur || !cur->is_bool())
572 return absl::nullopt;
573 return cur->GetBool();
576 absl::optional<int> Value::FindIntPath(StringPiece path) const {
577 const Value* cur = FindPath(path);
578 if (!cur || !cur->is_int())
579 return absl::nullopt;
580 return cur->GetInt();
583 absl::optional<double> Value::FindDoublePath(StringPiece path) const {
584 if (const Value* cur = FindPath(path)) {
585 if (cur->is_int() || cur->is_double())
586 return cur->GetDouble();
589 return absl::nullopt;
592 const std::string* Value::FindStringPath(StringPiece path) const {
593 const Value* result = FindPath(path);
594 return result ? absl::get_if<std::string>(&result->data_) : nullptr;
597 std::string* Value::FindStringPath(StringPiece path) {
598 return const_cast<std::string*>(as_const(*this).FindStringPath(path));
601 const Value::BlobStorage* Value::FindBlobPath(StringPiece path) const {
602 const Value* result = FindPath(path);
603 return result ? absl::get_if<BlobStorage>(&result->data_) : nullptr;
606 const Value* Value::FindDictPath(StringPiece path) const {
607 return FindPathOfType(path, Type::DICTIONARY);
610 Value* Value::FindDictPath(StringPiece path) {
611 return FindPathOfType(path, Type::DICTIONARY);
614 const Value* Value::FindListPath(StringPiece path) const {
615 return FindPathOfType(path, Type::LIST);
618 Value* Value::FindListPath(StringPiece path) {
619 return FindPathOfType(path, Type::LIST);
622 Value* Value::SetPath(StringPiece path, Value&& value) {
623 return SetPathInternal(path, std::make_unique<Value>(std::move(value)));
626 Value* Value::SetBoolPath(StringPiece path, bool value) {
627 return SetPathInternal(path, std::make_unique<Value>(value));
630 Value* Value::SetIntPath(StringPiece path, int value) {
631 return SetPathInternal(path, std::make_unique<Value>(value));
634 Value* Value::SetDoublePath(StringPiece path, double value) {
635 return SetPathInternal(path, std::make_unique<Value>(value));
638 Value* Value::SetStringPath(StringPiece path, StringPiece value) {
639 return SetPathInternal(path, std::make_unique<Value>(value));
642 Value* Value::SetStringPath(StringPiece path, std::string&& value) {
643 return SetPathInternal(path, std::make_unique<Value>(std::move(value)));
646 Value* Value::SetStringPath(StringPiece path, const char* value) {
647 return SetPathInternal(path, std::make_unique<Value>(value));
650 Value* Value::SetStringPath(StringPiece path, StringPiece16 value) {
651 return SetPathInternal(path, std::make_unique<Value>(value));
654 bool Value::RemovePath(StringPiece path) {
655 return ExtractPath(path).has_value();
658 absl::optional<Value> Value::ExtractPath(StringPiece path) {
659 if (!is_dict() || path.empty())
660 return absl::nullopt;
662 // NOTE: PathSplitter is not being used here because recursion is used to
663 // ensure that dictionaries that become empty due to this operation are
664 // removed automatically.
665 size_t pos = path.find('.');
666 if (pos == path.npos)
667 return ExtractKey(path);
669 auto found = dict().find(path.substr(0, pos));
670 if (found == dict().end() || !found->second->is_dict())
671 return absl::nullopt;
673 absl::optional<Value> extracted =
674 found->second->ExtractPath(path.substr(pos + 1));
675 if (extracted && found->second->dict().empty())
681 // DEPRECATED METHODS
682 Value* Value::FindPath(std::initializer_list<StringPiece> path) {
683 return const_cast<Value*>(as_const(*this).FindPath(path));
686 Value* Value::FindPath(span<const StringPiece> path) {
687 return const_cast<Value*>(as_const(*this).FindPath(path));
690 const Value* Value::FindPath(std::initializer_list<StringPiece> path) const {
691 DCHECK_GE(path.size(), 2u) << "Use FindKey() for a path of length 1.";
692 return FindPath(make_span(path.begin(), path.size()));
695 const Value* Value::FindPath(span<const StringPiece> path) const {
696 const Value* cur = this;
697 for (const StringPiece& component : path) {
698 if (!cur->is_dict() || (cur = cur->FindKey(component)) == nullptr)
704 Value* Value::FindPathOfType(std::initializer_list<StringPiece> path,
706 return const_cast<Value*>(as_const(*this).FindPathOfType(path, type));
709 Value* Value::FindPathOfType(span<const StringPiece> path, Type type) {
710 return const_cast<Value*>(as_const(*this).FindPathOfType(path, type));
713 const Value* Value::FindPathOfType(std::initializer_list<StringPiece> path,
715 DCHECK_GE(path.size(), 2u) << "Use FindKeyOfType() for a path of length 1.";
716 return FindPathOfType(make_span(path.begin(), path.size()), type);
719 const Value* Value::FindPathOfType(span<const StringPiece> path,
721 const Value* result = FindPath(path);
722 if (!result || result->type() != type)
727 Value* Value::SetPath(std::initializer_list<StringPiece> path, Value&& value) {
728 DCHECK_GE(path.size(), 2u) << "Use SetKey() for a path of length 1.";
729 return SetPath(make_span(path.begin(), path.size()), std::move(value));
732 Value* Value::SetPath(span<const StringPiece> path, Value&& value) {
733 DCHECK(path.begin() != path.end()); // Can't be empty path.
735 // Walk/construct intermediate dictionaries. The last element requires
736 // special handling so skip it in this loop.
738 auto cur_path = path.begin();
739 for (; (cur_path + 1) < path.end(); ++cur_path) {
743 // Use lower_bound to avoid doing the search twice for missing keys.
744 const StringPiece path_component = *cur_path;
745 auto found = cur->dict().lower_bound(path_component);
746 if (found == cur->dict().end() || found->first != path_component) {
747 // No key found, insert one.
748 auto inserted = cur->dict().try_emplace(
749 found, path_component, std::make_unique<Value>(Type::DICTIONARY));
750 cur = inserted->second.get();
752 cur = found->second.get();
756 // "cur" will now contain the last dictionary to insert or replace into.
759 return cur->SetKey(*cur_path, std::move(value));
762 Value::dict_iterator_proxy Value::DictItems() {
763 return dict_iterator_proxy(&dict());
766 Value::const_dict_iterator_proxy Value::DictItems() const {
767 return const_dict_iterator_proxy(&dict());
770 Value::DictStorage Value::TakeDict() && {
772 storage.reserve(dict().size());
773 for (auto& pair : dict()) {
774 storage.try_emplace(storage.end(), std::move(pair.first),
775 std::move(*pair.second));
782 size_t Value::DictSize() const {
783 return dict().size();
786 bool Value::DictEmpty() const {
787 return dict().empty();
790 void Value::DictClear() {
794 void Value::MergeDictionary(const Value* dictionary) {
795 for (const auto& pair : dictionary->dict()) {
796 const auto& key = pair.first;
797 const auto& val = pair.second;
798 // Check whether we have to merge dictionaries.
799 if (val->is_dict()) {
800 auto found = dict().find(key);
801 if (found != dict().end() && found->second->is_dict()) {
802 found->second->MergeDictionary(val.get());
807 // All other cases: Make a copy and hook it up.
808 SetKey(key, val->Clone());
812 bool Value::GetAsBoolean(bool* out_value) const {
813 if (out_value && is_bool()) {
814 *out_value = GetBool();
820 bool Value::GetAsString(std::string* out_value) const {
821 if (out_value && is_string()) {
822 *out_value = GetString();
828 bool Value::GetAsString(std::u16string* out_value) const {
829 if (out_value && is_string()) {
830 *out_value = UTF8ToUTF16(GetString());
836 bool Value::GetAsString(const Value** out_value) const {
837 if (out_value && is_string()) {
844 bool Value::GetAsString(StringPiece* out_value) const {
845 if (out_value && is_string()) {
846 *out_value = GetString();
852 bool Value::GetAsList(ListValue** out_value) {
853 if (out_value && is_list()) {
854 *out_value = static_cast<ListValue*>(this);
860 bool Value::GetAsList(const ListValue** out_value) const {
861 if (out_value && is_list()) {
862 *out_value = static_cast<const ListValue*>(this);
868 bool Value::GetAsDictionary(DictionaryValue** out_value) {
869 if (out_value && is_dict()) {
870 *out_value = static_cast<DictionaryValue*>(this);
876 bool Value::GetAsDictionary(const DictionaryValue** out_value) const {
877 if (out_value && is_dict()) {
878 *out_value = static_cast<const DictionaryValue*>(this);
884 Value* Value::DeepCopy() const {
885 return new Value(Clone());
888 std::unique_ptr<Value> Value::CreateDeepCopy() const {
889 return std::make_unique<Value>(Clone());
892 bool operator==(const Value& lhs, const Value& rhs) {
893 if (lhs.type() != rhs.type())
896 switch (lhs.type()) {
897 case Value::Type::NONE:
899 case Value::Type::BOOLEAN:
900 return lhs.GetBool() == rhs.GetBool();
901 case Value::Type::INTEGER:
902 return lhs.GetInt() == rhs.GetInt();
903 case Value::Type::DOUBLE:
904 return lhs.AsDoubleInternal() == rhs.AsDoubleInternal();
905 case Value::Type::STRING:
906 return lhs.GetString() == rhs.GetString();
907 case Value::Type::BINARY:
908 return lhs.GetBlob() == rhs.GetBlob();
909 // TODO(crbug.com/646113): Clean this up when DictionaryValue and ListValue
910 // are completely inlined.
911 case Value::Type::DICTIONARY:
912 if (lhs.dict().size() != rhs.dict().size())
915 std::begin(lhs.dict()), std::end(lhs.dict()), std::begin(rhs.dict()),
916 [](const auto& u, const auto& v) {
917 return std::tie(u.first, *u.second) == std::tie(v.first, *v.second);
919 case Value::Type::LIST:
920 return lhs.list() == rhs.list();
927 bool operator!=(const Value& lhs, const Value& rhs) {
928 return !(lhs == rhs);
931 bool operator<(const Value& lhs, const Value& rhs) {
932 if (lhs.type() != rhs.type())
933 return lhs.type() < rhs.type();
935 switch (lhs.type()) {
936 case Value::Type::NONE:
938 case Value::Type::BOOLEAN:
939 return lhs.GetBool() < rhs.GetBool();
940 case Value::Type::INTEGER:
941 return lhs.GetInt() < rhs.GetInt();
942 case Value::Type::DOUBLE:
943 return lhs.AsDoubleInternal() < rhs.AsDoubleInternal();
944 case Value::Type::STRING:
945 return lhs.GetString() < rhs.GetString();
946 case Value::Type::BINARY:
947 return lhs.GetBlob() < rhs.GetBlob();
948 // TODO(crbug.com/646113): Clean this up when DictionaryValue and ListValue
949 // are completely inlined.
950 case Value::Type::DICTIONARY:
951 return std::lexicographical_compare(
952 std::begin(lhs.dict()), std::end(lhs.dict()), std::begin(rhs.dict()),
953 std::end(rhs.dict()),
954 [](const Value::LegacyDictStorage::value_type& u,
955 const Value::LegacyDictStorage::value_type& v) {
956 return std::tie(u.first, *u.second) < std::tie(v.first, *v.second);
958 case Value::Type::LIST:
959 return lhs.list() < rhs.list();
966 bool operator>(const Value& lhs, const Value& rhs) {
970 bool operator<=(const Value& lhs, const Value& rhs) {
974 bool operator>=(const Value& lhs, const Value& rhs) {
978 bool Value::Equals(const Value* other) const {
980 return *this == *other;
983 size_t Value::EstimateMemoryUsage() const {
985 #if BUILDFLAG(ENABLE_BASE_TRACING)
987 return base::trace_event::EstimateMemoryUsage(GetString());
989 return base::trace_event::EstimateMemoryUsage(GetBlob());
990 case Type::DICTIONARY:
991 return base::trace_event::EstimateMemoryUsage(dict());
993 return base::trace_event::EstimateMemoryUsage(list());
994 #endif // BUILDFLAG(ENABLE_BASE_TRACING)
1000 std::string Value::DebugString() const {
1002 JSONWriter::WriteWithOptions(*this, JSONWriter::OPTIONS_PRETTY_PRINT, &json);
1006 #if BUILDFLAG(ENABLE_BASE_TRACING)
1007 void Value::WriteIntoTrace(perfetto::TracedValue context) const {
1010 std::move(context).WriteBoolean(GetBool());
1013 std::move(context).WriteInt64(GetInt());
1016 std::move(context).WriteDouble(GetDouble());
1019 std::move(context).WriteString(GetString());
1022 std::move(context).WriteString("<binary data not supported>");
1024 case Type::DICTIONARY: {
1025 perfetto::TracedDictionary dict = std::move(context).WriteDictionary();
1026 for (auto kv : DictItems())
1027 dict.Add(perfetto::DynamicString{kv.first}, kv.second);
1031 perfetto::TracedArray array = std::move(context).WriteArray();
1032 for (const auto& item : GetList())
1037 std::move(context).WriteString("<none>");
1041 #endif // BUILDFLAG(ENABLE_BASE_TRACING)
1043 Value* Value::SetKeyInternal(StringPiece key,
1044 std::unique_ptr<Value>&& val_ptr) {
1046 // NOTE: We can't use |insert_or_assign| here, as only |try_emplace| does
1047 // an explicit conversion from StringPiece to std::string if necessary.
1048 auto result = dict().try_emplace(key, std::move(val_ptr));
1049 if (!result.second) {
1050 // val_ptr is guaranteed to be still intact at this point.
1051 result.first->second = std::move(val_ptr);
1053 return result.first->second.get();
1056 Value* Value::SetPathInternal(StringPiece path,
1057 std::unique_ptr<Value>&& value_ptr) {
1058 PathSplitter splitter(path);
1059 DCHECK(splitter.HasNext()) << "Cannot call SetPath() with empty path";
1060 // Walk/construct intermediate dictionaries. The last element requires
1061 // special handling so skip it in this loop.
1063 StringPiece path_component = splitter.Next();
1064 while (splitter.HasNext()) {
1065 if (!cur->is_dict())
1068 // Use lower_bound to avoid doing the search twice for missing keys.
1069 auto found = cur->dict().lower_bound(path_component);
1070 if (found == cur->dict().end() || found->first != path_component) {
1071 // No key found, insert one.
1072 auto inserted = cur->dict().try_emplace(
1073 found, path_component, std::make_unique<Value>(Type::DICTIONARY));
1074 cur = inserted->second.get();
1076 cur = found->second.get();
1078 path_component = splitter.Next();
1081 // "cur" will now contain the last dictionary to insert or replace into.
1082 if (!cur->is_dict())
1084 return cur->SetKeyInternal(path_component, std::move(value_ptr));
1087 ///////////////////// DictionaryValue ////////////////////
1090 std::unique_ptr<DictionaryValue> DictionaryValue::From(
1091 std::unique_ptr<Value> value) {
1092 DictionaryValue* out;
1093 if (value && value->GetAsDictionary(&out)) {
1094 ignore_result(value.release());
1095 return WrapUnique(out);
1100 DictionaryValue::DictionaryValue() : Value(Type::DICTIONARY) {}
1102 DictionaryValue::DictionaryValue(const LegacyDictStorage& storage)
1105 DictionaryValue::DictionaryValue(LegacyDictStorage&& storage) noexcept
1106 : Value(std::move(storage)) {}
1108 bool DictionaryValue::HasKey(StringPiece key) const {
1109 DCHECK(IsStringUTF8AllowingNoncharacters(key));
1110 auto current_entry = dict().find(key);
1111 DCHECK((current_entry == dict().end()) || current_entry->second);
1112 return current_entry != dict().end();
1115 void DictionaryValue::Clear() {
1119 Value* DictionaryValue::Set(StringPiece path, std::unique_ptr<Value> in_value) {
1120 DCHECK(IsStringUTF8AllowingNoncharacters(path));
1123 // IMPORTANT NOTE: Do not replace with SetPathInternal() yet, because the
1124 // latter fails when over-writing a non-dict intermediate node, while this
1125 // method just replaces it with one. This difference makes some tests actually
1126 // fail (http://crbug.com/949461).
1127 StringPiece current_path(path);
1128 Value* current_dictionary = this;
1129 for (size_t delimiter_position = current_path.find('.');
1130 delimiter_position != StringPiece::npos;
1131 delimiter_position = current_path.find('.')) {
1132 // Assume that we're indexing into a dictionary.
1133 StringPiece key = current_path.substr(0, delimiter_position);
1134 Value* child_dictionary =
1135 current_dictionary->FindKeyOfType(key, Type::DICTIONARY);
1136 if (!child_dictionary) {
1138 current_dictionary->SetKey(key, Value(Type::DICTIONARY));
1141 current_dictionary = child_dictionary;
1142 current_path = current_path.substr(delimiter_position + 1);
1145 return static_cast<DictionaryValue*>(current_dictionary)
1146 ->SetWithoutPathExpansion(current_path, std::move(in_value));
1149 Value* DictionaryValue::SetBoolean(StringPiece path, bool in_value) {
1150 return Set(path, std::make_unique<Value>(in_value));
1153 Value* DictionaryValue::SetInteger(StringPiece path, int in_value) {
1154 return Set(path, std::make_unique<Value>(in_value));
1157 Value* DictionaryValue::SetDouble(StringPiece path, double in_value) {
1158 return Set(path, std::make_unique<Value>(in_value));
1161 Value* DictionaryValue::SetString(StringPiece path, StringPiece in_value) {
1162 return Set(path, std::make_unique<Value>(in_value));
1165 Value* DictionaryValue::SetString(StringPiece path,
1166 const std::u16string& in_value) {
1167 return Set(path, std::make_unique<Value>(in_value));
1170 DictionaryValue* DictionaryValue::SetDictionary(
1172 std::unique_ptr<DictionaryValue> in_value) {
1173 return static_cast<DictionaryValue*>(Set(path, std::move(in_value)));
1176 ListValue* DictionaryValue::SetList(StringPiece path,
1177 std::unique_ptr<ListValue> in_value) {
1178 return static_cast<ListValue*>(Set(path, std::move(in_value)));
1181 Value* DictionaryValue::SetWithoutPathExpansion(
1183 std::unique_ptr<Value> in_value) {
1184 // NOTE: We can't use |insert_or_assign| here, as only |try_emplace| does
1185 // an explicit conversion from StringPiece to std::string if necessary.
1186 auto result = dict().try_emplace(key, std::move(in_value));
1187 if (!result.second) {
1188 // in_value is guaranteed to be still intact at this point.
1189 result.first->second = std::move(in_value);
1191 return result.first->second.get();
1194 bool DictionaryValue::Get(StringPiece path, const Value** out_value) const {
1195 DCHECK(IsStringUTF8AllowingNoncharacters(path));
1196 const Value* value = FindPath(path);
1204 bool DictionaryValue::Get(StringPiece path, Value** out_value) {
1205 return as_const(*this).Get(path, const_cast<const Value**>(out_value));
1208 bool DictionaryValue::GetBoolean(StringPiece path, bool* bool_value) const {
1210 if (!Get(path, &value))
1213 return value->GetAsBoolean(bool_value);
1216 bool DictionaryValue::GetInteger(StringPiece path, int* out_value) const {
1218 if (!Get(path, &value))
1221 bool is_int = value->is_int();
1222 if (is_int && out_value)
1223 *out_value = value->GetInt();
1227 bool DictionaryValue::GetDouble(StringPiece path, double* out_value) const {
1229 if (!Get(path, &value))
1232 const bool is_convertible_to_double = value->is_double() || value->is_int();
1233 if (out_value && is_convertible_to_double) {
1234 *out_value = value->GetDouble();
1237 return is_convertible_to_double;
1240 bool DictionaryValue::GetString(StringPiece path,
1241 std::string* out_value) const {
1243 if (!Get(path, &value))
1246 return value->GetAsString(out_value);
1249 bool DictionaryValue::GetString(StringPiece path,
1250 std::u16string* out_value) const {
1252 if (!Get(path, &value))
1255 return value->GetAsString(out_value);
1258 bool DictionaryValue::GetStringASCII(StringPiece path,
1259 std::string* out_value) const {
1261 if (!GetString(path, &out))
1264 if (!IsStringASCII(out)) {
1269 out_value->assign(out);
1273 bool DictionaryValue::GetBinary(StringPiece path,
1274 const Value** out_value) const {
1276 bool result = Get(path, &value);
1277 if (!result || !value->is_blob())
1286 bool DictionaryValue::GetBinary(StringPiece path, Value** out_value) {
1287 return as_const(*this).GetBinary(path, const_cast<const Value**>(out_value));
1290 bool DictionaryValue::GetDictionary(StringPiece path,
1291 const DictionaryValue** out_value) const {
1293 bool result = Get(path, &value);
1294 if (!result || !value->is_dict())
1298 *out_value = static_cast<const DictionaryValue*>(value);
1303 bool DictionaryValue::GetDictionary(StringPiece path,
1304 DictionaryValue** out_value) {
1305 return as_const(*this).GetDictionary(
1306 path, const_cast<const DictionaryValue**>(out_value));
1309 bool DictionaryValue::GetList(StringPiece path,
1310 const ListValue** out_value) const {
1312 bool result = Get(path, &value);
1313 if (!result || !value->is_list())
1317 *out_value = static_cast<const ListValue*>(value);
1322 bool DictionaryValue::GetList(StringPiece path, ListValue** out_value) {
1323 return as_const(*this).GetList(path,
1324 const_cast<const ListValue**>(out_value));
1327 bool DictionaryValue::GetDictionaryWithoutPathExpansion(
1329 const DictionaryValue** out_value) const {
1330 const Value* value = FindKey(key);
1331 if (!value || !value->is_dict())
1335 *out_value = static_cast<const DictionaryValue*>(value);
1340 bool DictionaryValue::GetDictionaryWithoutPathExpansion(
1342 DictionaryValue** out_value) {
1343 return as_const(*this).GetDictionaryWithoutPathExpansion(
1344 key, const_cast<const DictionaryValue**>(out_value));
1347 bool DictionaryValue::GetListWithoutPathExpansion(
1349 const ListValue** out_value) const {
1350 const Value* value = FindKey(key);
1351 if (!value || !value->is_list())
1355 *out_value = static_cast<const ListValue*>(value);
1360 bool DictionaryValue::GetListWithoutPathExpansion(StringPiece key,
1361 ListValue** out_value) {
1362 return as_const(*this).GetListWithoutPathExpansion(
1363 key, const_cast<const ListValue**>(out_value));
1366 std::unique_ptr<DictionaryValue> DictionaryValue::DeepCopyWithoutEmptyChildren()
1368 std::unique_ptr<DictionaryValue> copy =
1369 CopyDictionaryWithoutEmptyChildren(*this);
1371 copy = std::make_unique<DictionaryValue>();
1375 void DictionaryValue::Swap(DictionaryValue* other) {
1376 CHECK(other->is_dict());
1377 dict().swap(other->dict());
1380 DictionaryValue::Iterator::Iterator(const DictionaryValue& target)
1381 : target_(target), it_(target.DictItems().begin()) {}
1383 DictionaryValue::Iterator::Iterator(const Iterator& other) = default;
1385 DictionaryValue::Iterator::~Iterator() = default;
1387 DictionaryValue* DictionaryValue::DeepCopy() const {
1388 return new DictionaryValue(dict());
1391 std::unique_ptr<DictionaryValue> DictionaryValue::CreateDeepCopy() const {
1392 return std::make_unique<DictionaryValue>(dict());
1395 ///////////////////// ListValue ////////////////////
1398 std::unique_ptr<ListValue> ListValue::From(std::unique_ptr<Value> value) {
1400 if (value && value->GetAsList(&out)) {
1401 ignore_result(value.release());
1402 return WrapUnique(out);
1407 ListValue::ListValue() : Value(Type::LIST) {}
1408 ListValue::ListValue(span<const Value> in_list) : Value(in_list) {}
1409 ListValue::ListValue(ListStorage&& in_list) noexcept
1410 : Value(std::move(in_list)) {}
1412 bool ListValue::Set(size_t index, std::unique_ptr<Value> in_value) {
1416 if (index >= list().size())
1417 list().resize(index + 1);
1419 list()[index] = std::move(*in_value);
1423 bool ListValue::Get(size_t index, const Value** out_value) const {
1424 if (index >= list().size())
1428 *out_value = &list()[index];
1433 bool ListValue::Get(size_t index, Value** out_value) {
1434 return as_const(*this).Get(index, const_cast<const Value**>(out_value));
1437 bool ListValue::GetBoolean(size_t index, bool* bool_value) const {
1439 if (!Get(index, &value))
1442 return value->GetAsBoolean(bool_value);
1445 bool ListValue::GetString(size_t index, std::string* out_value) const {
1447 if (!Get(index, &value))
1450 return value->GetAsString(out_value);
1453 bool ListValue::GetString(size_t index, std::u16string* out_value) const {
1455 if (!Get(index, &value))
1458 return value->GetAsString(out_value);
1461 bool ListValue::GetDictionary(size_t index,
1462 const DictionaryValue** out_value) const {
1464 bool result = Get(index, &value);
1465 if (!result || !value->is_dict())
1469 *out_value = static_cast<const DictionaryValue*>(value);
1474 bool ListValue::GetDictionary(size_t index, DictionaryValue** out_value) {
1475 return as_const(*this).GetDictionary(
1476 index, const_cast<const DictionaryValue**>(out_value));
1479 void ListValue::Append(std::unique_ptr<Value> in_value) {
1480 list().push_back(std::move(*in_value));
1483 void ListValue::AppendBoolean(bool in_value) {
1484 list().emplace_back(in_value);
1487 void ListValue::AppendInteger(int in_value) {
1488 list().emplace_back(in_value);
1491 void ListValue::AppendString(StringPiece in_value) {
1492 list().emplace_back(in_value);
1495 void ListValue::AppendString(const std::u16string& in_value) {
1496 list().emplace_back(in_value);
1499 void ListValue::Swap(ListValue* other) {
1500 CHECK(other->is_list());
1501 list().swap(other->list());
1504 std::unique_ptr<ListValue> ListValue::CreateDeepCopy() const {
1505 return std::make_unique<ListValue>(list());
1508 ValueSerializer::~ValueSerializer() = default;
1510 ValueDeserializer::~ValueDeserializer() = default;
1512 std::ostream& operator<<(std::ostream& out, const Value& value) {
1513 return out << value.DebugString();
1516 std::ostream& operator<<(std::ostream& out, const Value::Type& type) {
1517 if (static_cast<int>(type) < 0 ||
1518 static_cast<size_t>(type) >= base::size(kTypeNames))
1519 return out << "Invalid Type (index = " << static_cast<int>(type) << ")";
1520 return out << Value::GetTypeName(type);