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"
15 #include "base/bit_cast.h"
16 #include "base/check_op.h"
17 #include "base/containers/checked_iterators.h"
18 #include "base/json/json_writer.h"
19 #include "base/memory/ptr_util.h"
20 #include "base/notreached.h"
21 #include "base/stl_util.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/tracing_buildflags.h"
26 #if BUILDFLAG(ENABLE_BASE_TRACING)
27 #include "base/trace_event/memory_usage_estimator.h"
28 #endif // BUILDFLAG(ENABLE_BASE_TRACING)
32 // base::Value must be standard layout to guarantee that writing to
33 // |bool_type_| then reading |type_| is defined behaviour. See:
36 // If a standard-layout union contains several standard-layout structs that
37 // share a common initial sequence (9.2), and if an object of this
38 // standard-layout union type contains one of the standard-layout structs,
39 // it is permitted to inspect the common initial sequence of any of
40 // standard-layout struct members;
42 static_assert(std::is_standard_layout<Value>::value,
43 "base::Value should be a standard-layout C++ class in order "
44 "to avoid undefined behaviour in its implementation!");
46 static_assert(sizeof(Value::DoubleStorage) == sizeof(double),
47 "The double and DoubleStorage types should have the same size");
51 const char* const kTypeNames[] = {"null", "boolean", "integer", "double",
52 "string", "binary", "dictionary", "list"};
53 static_assert(base::size(kTypeNames) ==
54 static_cast<size_t>(Value::Type::LIST) + 1,
55 "kTypeNames Has Wrong Size");
57 std::unique_ptr<Value> CopyWithoutEmptyChildren(const Value& node);
59 // Make a deep copy of |node|, but don't include empty lists or dictionaries
60 // in the copy. It's possible for this function to return NULL and it
61 // expects |node| to always be non-NULL.
62 std::unique_ptr<Value> CopyListWithoutEmptyChildren(const Value& list) {
63 Value copy(Value::Type::LIST);
64 for (const auto& entry : list.GetList()) {
65 std::unique_ptr<Value> child_copy = CopyWithoutEmptyChildren(entry);
67 copy.Append(std::move(*child_copy));
69 return copy.GetList().empty() ? nullptr
70 : std::make_unique<Value>(std::move(copy));
73 std::unique_ptr<DictionaryValue> CopyDictionaryWithoutEmptyChildren(
74 const DictionaryValue& dict) {
75 std::unique_ptr<DictionaryValue> copy;
76 for (const auto& it : dict.DictItems()) {
77 std::unique_ptr<Value> child_copy = CopyWithoutEmptyChildren(it.second);
80 copy = std::make_unique<DictionaryValue>();
81 copy->SetKey(it.first, std::move(*child_copy));
87 std::unique_ptr<Value> CopyWithoutEmptyChildren(const Value& node) {
88 switch (node.type()) {
89 case Value::Type::LIST:
90 return CopyListWithoutEmptyChildren(static_cast<const ListValue&>(node));
92 case Value::Type::DICTIONARY:
93 return CopyDictionaryWithoutEmptyChildren(
94 static_cast<const DictionaryValue&>(node));
97 return std::make_unique<Value>(node.Clone());
101 // Helper class to enumerate the path components from a StringPiece
102 // without performing heap allocations. Components are simply separated
103 // by single dots (e.g. "foo.bar.baz" -> ["foo", "bar", "baz"]).
106 // PathSplitter splitter(some_path);
107 // while (splitter.HasNext()) {
108 // StringPiece component = splitter.Next();
114 explicit PathSplitter(StringPiece path) : path_(path) {}
116 bool HasNext() const { return pos_ < path_.size(); }
121 size_t pos = path_.find('.', start);
123 if (pos == path_.npos) {
130 return path_.substr(start, end - start);
141 std::unique_ptr<Value> Value::CreateWithCopiedBuffer(const char* buffer,
143 return std::make_unique<Value>(BlobStorage(buffer, buffer + size));
147 Value Value::FromUniquePtrValue(std::unique_ptr<Value> val) {
148 return std::move(*val);
152 std::unique_ptr<Value> Value::ToUniquePtrValue(Value val) {
153 return std::make_unique<Value>(std::move(val));
157 const DictionaryValue& Value::AsDictionaryValue(const Value& val) {
158 CHECK(val.is_dict());
159 return static_cast<const DictionaryValue&>(val);
163 const ListValue& Value::AsListValue(const Value& val) {
164 CHECK(val.is_list());
165 return static_cast<const ListValue&>(val);
168 Value::Value(Value&& that) noexcept {
169 InternalMoveConstructFrom(std::move(that));
172 Value::Value(Type type) : type_(type) {
173 // Initialize with the default value.
185 double_value_ = bit_cast<DoubleStorage>(0.0);
188 new (&string_value_) std::string();
191 new (&binary_value_) BlobStorage();
193 case Type::DICTIONARY:
194 new (&dict_) DictStorage();
197 new (&list_) ListStorage();
199 // TODO(crbug.com/859477): Remove after root cause is found.
205 // TODO(crbug.com/859477): Revert to NOTREACHED() after root cause is found.
209 Value::Value(bool in_bool) : type_(Type::BOOLEAN), bool_value_(in_bool) {}
211 Value::Value(int in_int) : type_(Type::INTEGER), int_value_(in_int) {}
213 Value::Value(double in_double)
214 : type_(Type::DOUBLE), double_value_(bit_cast<DoubleStorage>(in_double)) {
215 if (!std::isfinite(in_double)) {
216 NOTREACHED() << "Non-finite (i.e. NaN or positive/negative infinity) "
217 << "values cannot be represented in JSON";
218 double_value_ = bit_cast<DoubleStorage>(0.0);
222 Value::Value(const char* in_string) : Value(std::string(in_string)) {}
224 Value::Value(StringPiece in_string) : Value(std::string(in_string)) {}
226 Value::Value(std::string&& in_string) noexcept
227 : type_(Type::STRING), string_value_(std::move(in_string)) {
228 DCHECK(IsStringUTF8AllowingNoncharacters(string_value_));
231 Value::Value(const char16* in_string16) : Value(StringPiece16(in_string16)) {}
233 Value::Value(StringPiece16 in_string16) : Value(UTF16ToUTF8(in_string16)) {}
235 Value::Value(const std::vector<char>& in_blob)
236 : type_(Type::BINARY), binary_value_(in_blob.begin(), in_blob.end()) {}
238 Value::Value(base::span<const uint8_t> in_blob)
239 : type_(Type::BINARY), binary_value_(in_blob.begin(), in_blob.end()) {}
241 Value::Value(BlobStorage&& in_blob) noexcept
242 : type_(Type::BINARY), binary_value_(std::move(in_blob)) {}
244 Value::Value(const DictStorage& in_dict) : type_(Type::DICTIONARY), dict_() {
245 dict_.reserve(in_dict.size());
246 for (const auto& it : in_dict) {
247 dict_.try_emplace(dict_.end(), it.first,
248 std::make_unique<Value>(it.second->Clone()));
252 Value::Value(DictStorage&& in_dict) noexcept
253 : type_(Type::DICTIONARY), dict_(std::move(in_dict)) {}
255 Value::Value(span<const Value> in_list) : type_(Type::LIST), list_() {
256 list_.reserve(in_list.size());
257 for (const auto& val : in_list)
258 list_.emplace_back(val.Clone());
261 Value::Value(ListStorage&& in_list) noexcept
262 : type_(Type::LIST), list_(std::move(in_list)) {}
264 Value& Value::operator=(Value&& that) noexcept {
266 InternalMoveConstructFrom(std::move(that));
271 double Value::AsDoubleInternal() const {
272 return bit_cast<double>(double_value_);
275 Value Value::Clone() const {
280 return Value(bool_value_);
282 return Value(int_value_);
284 return Value(AsDoubleInternal());
286 return Value(string_value_);
288 return Value(binary_value_);
289 case Type::DICTIONARY:
293 // TODO(crbug.com/859477): Remove after root cause is found.
299 // TODO(crbug.com/859477): Revert to NOTREACHED() after root cause is found.
306 // TODO(crbug.com/859477): Remove after root cause is found.
311 const char* Value::GetTypeName(Value::Type type) {
312 DCHECK_GE(static_cast<int>(type), 0);
313 DCHECK_LT(static_cast<size_t>(type), base::size(kTypeNames));
314 return kTypeNames[static_cast<size_t>(type)];
317 bool Value::GetBool() const {
322 int Value::GetInt() const {
327 double Value::GetDouble() const {
329 return AsDoubleInternal();
336 const std::string& Value::GetString() const {
338 return string_value_;
341 std::string& Value::GetString() {
343 return string_value_;
346 const Value::BlobStorage& Value::GetBlob() const {
348 return binary_value_;
351 Value::ListView Value::GetList() {
356 Value::ConstListView Value::GetList() const {
361 Value::ListStorage Value::TakeList() {
363 return std::exchange(list_, ListStorage());
366 void Value::Append(bool value) {
368 list_.emplace_back(value);
371 void Value::Append(int value) {
373 list_.emplace_back(value);
376 void Value::Append(double value) {
378 list_.emplace_back(value);
381 void Value::Append(const char* value) {
383 list_.emplace_back(value);
386 void Value::Append(StringPiece value) {
388 list_.emplace_back(value);
391 void Value::Append(std::string&& value) {
393 list_.emplace_back(std::move(value));
396 void Value::Append(const char16* value) {
398 list_.emplace_back(value);
401 void Value::Append(StringPiece16 value) {
403 list_.emplace_back(value);
406 void Value::Append(Value&& value) {
408 list_.emplace_back(std::move(value));
411 CheckedContiguousIterator<Value> Value::Insert(
412 CheckedContiguousConstIterator<Value> pos,
415 const auto offset = pos - make_span(list_).begin();
416 list_.insert(list_.begin() + offset, std::move(value));
417 return make_span(list_).begin() + offset;
420 bool Value::EraseListIter(CheckedContiguousConstIterator<Value> iter) {
422 const auto offset = iter - ListView(list_).begin();
423 auto list_iter = list_.begin() + offset;
424 if (list_iter == list_.end())
427 list_.erase(list_iter);
431 size_t Value::EraseListValue(const Value& val) {
432 return EraseListValueIf([&val](const Value& other) { return val == other; });
435 void Value::ClearList() {
440 Value* Value::FindKey(StringPiece key) {
441 return const_cast<Value*>(as_const(*this).FindKey(key));
444 const Value* Value::FindKey(StringPiece key) const {
446 auto found = dict_.find(key);
447 if (found == dict_.end())
449 return found->second.get();
452 Value* Value::FindKeyOfType(StringPiece key, Type type) {
453 return const_cast<Value*>(as_const(*this).FindKeyOfType(key, type));
456 const Value* Value::FindKeyOfType(StringPiece key, Type type) const {
457 const Value* result = FindKey(key);
458 if (!result || result->type() != type)
463 base::Optional<bool> Value::FindBoolKey(StringPiece key) const {
464 const Value* result = FindKeyOfType(key, Type::BOOLEAN);
465 return result ? base::make_optional(result->bool_value_) : base::nullopt;
468 base::Optional<int> Value::FindIntKey(StringPiece key) const {
469 const Value* result = FindKeyOfType(key, Type::INTEGER);
470 return result ? base::make_optional(result->int_value_) : base::nullopt;
473 base::Optional<double> Value::FindDoubleKey(StringPiece key) const {
474 const Value* result = FindKey(key);
476 if (result->is_int())
477 return static_cast<double>(result->int_value_);
478 if (result->is_double()) {
479 return result->AsDoubleInternal();
482 return base::nullopt;
485 const std::string* Value::FindStringKey(StringPiece key) const {
486 const Value* result = FindKeyOfType(key, Type::STRING);
487 return result ? &result->string_value_ : nullptr;
490 std::string* Value::FindStringKey(StringPiece key) {
491 Value* result = FindKeyOfType(key, Type::STRING);
492 return result ? &result->string_value_ : nullptr;
495 const Value::BlobStorage* Value::FindBlobKey(StringPiece key) const {
496 const Value* value = FindKeyOfType(key, Type::BINARY);
497 return value ? &value->binary_value_ : nullptr;
500 const Value* Value::FindDictKey(StringPiece key) const {
501 return FindKeyOfType(key, Type::DICTIONARY);
504 Value* Value::FindDictKey(StringPiece key) {
505 return FindKeyOfType(key, Type::DICTIONARY);
508 const Value* Value::FindListKey(StringPiece key) const {
509 return FindKeyOfType(key, Type::LIST);
512 Value* Value::FindListKey(StringPiece key) {
513 return FindKeyOfType(key, Type::LIST);
516 Value* Value::SetKey(StringPiece key, Value&& value) {
517 return SetKeyInternal(key, std::make_unique<Value>(std::move(value)));
520 Value* Value::SetKey(std::string&& key, Value&& value) {
523 .insert_or_assign(std::move(key),
524 std::make_unique<Value>(std::move(value)))
525 .first->second.get();
528 Value* Value::SetKey(const char* key, Value&& value) {
529 return SetKeyInternal(key, std::make_unique<Value>(std::move(value)));
532 Value* Value::SetBoolKey(StringPiece key, bool value) {
533 return SetKeyInternal(key, std::make_unique<Value>(value));
536 Value* Value::SetIntKey(StringPiece key, int value) {
537 return SetKeyInternal(key, std::make_unique<Value>(value));
540 Value* Value::SetDoubleKey(StringPiece key, double value) {
541 return SetKeyInternal(key, std::make_unique<Value>(value));
544 Value* Value::SetStringKey(StringPiece key, StringPiece value) {
545 return SetKeyInternal(key, std::make_unique<Value>(value));
548 Value* Value::SetStringKey(StringPiece key, StringPiece16 value) {
549 return SetKeyInternal(key, std::make_unique<Value>(value));
552 Value* Value::SetStringKey(StringPiece key, const char* value) {
553 return SetKeyInternal(key, std::make_unique<Value>(value));
556 Value* Value::SetStringKey(StringPiece key, std::string&& value) {
557 return SetKeyInternal(key, std::make_unique<Value>(std::move(value)));
560 bool Value::RemoveKey(StringPiece key) {
562 return dict_.erase(key) != 0;
565 Optional<Value> Value::ExtractKey(StringPiece key) {
567 auto found = dict_.find(key);
568 if (found == dict_.end())
571 Value value = std::move(*found->second);
573 return std::move(value);
576 Value* Value::FindPath(StringPiece path) {
577 return const_cast<Value*>(as_const(*this).FindPath(path));
580 const Value* Value::FindPath(StringPiece path) const {
582 const Value* cur = this;
583 PathSplitter splitter(path);
584 while (splitter.HasNext()) {
585 if (!cur->is_dict() || (cur = cur->FindKey(splitter.Next())) == nullptr)
591 Value* Value::FindPathOfType(StringPiece path, Type type) {
592 return const_cast<Value*>(as_const(*this).FindPathOfType(path, type));
595 const Value* Value::FindPathOfType(StringPiece path, Type type) const {
596 const Value* cur = FindPath(path);
597 if (!cur || cur->type() != type)
602 base::Optional<bool> Value::FindBoolPath(StringPiece path) const {
603 const Value* cur = FindPath(path);
604 if (!cur || !cur->is_bool())
605 return base::nullopt;
606 return cur->bool_value_;
609 base::Optional<int> Value::FindIntPath(StringPiece path) const {
610 const Value* cur = FindPath(path);
611 if (!cur || !cur->is_int())
612 return base::nullopt;
613 return cur->int_value_;
616 base::Optional<double> Value::FindDoublePath(StringPiece path) const {
617 const Value* cur = FindPath(path);
620 return static_cast<double>(cur->int_value_);
621 if (cur->is_double())
622 return cur->AsDoubleInternal();
624 return base::nullopt;
627 const std::string* Value::FindStringPath(StringPiece path) const {
628 const Value* cur = FindPath(path);
629 if (!cur || !cur->is_string())
631 return &cur->string_value_;
634 std::string* Value::FindStringPath(StringPiece path) {
635 return const_cast<std::string*>(as_const(*this).FindStringPath(path));
638 const Value::BlobStorage* Value::FindBlobPath(StringPiece path) const {
639 const Value* cur = FindPath(path);
640 if (!cur || !cur->is_blob())
642 return &cur->binary_value_;
645 const Value* Value::FindDictPath(StringPiece path) const {
646 return FindPathOfType(path, Type::DICTIONARY);
649 Value* Value::FindDictPath(StringPiece path) {
650 return FindPathOfType(path, Type::DICTIONARY);
653 const Value* Value::FindListPath(StringPiece path) const {
654 return FindPathOfType(path, Type::LIST);
657 Value* Value::FindListPath(StringPiece path) {
658 return FindPathOfType(path, Type::LIST);
661 Value* Value::SetPath(StringPiece path, Value&& value) {
662 return SetPathInternal(path, std::make_unique<Value>(std::move(value)));
665 Value* Value::SetBoolPath(StringPiece path, bool value) {
666 return SetPathInternal(path, std::make_unique<Value>(value));
669 Value* Value::SetIntPath(StringPiece path, int value) {
670 return SetPathInternal(path, std::make_unique<Value>(value));
673 Value* Value::SetDoublePath(StringPiece path, double value) {
674 return SetPathInternal(path, std::make_unique<Value>(value));
677 Value* Value::SetStringPath(StringPiece path, StringPiece value) {
678 return SetPathInternal(path, std::make_unique<Value>(value));
681 Value* Value::SetStringPath(StringPiece path, std::string&& value) {
682 return SetPathInternal(path, std::make_unique<Value>(std::move(value)));
685 Value* Value::SetStringPath(StringPiece path, const char* value) {
686 return SetPathInternal(path, std::make_unique<Value>(value));
689 Value* Value::SetStringPath(StringPiece path, StringPiece16 value) {
690 return SetPathInternal(path, std::make_unique<Value>(value));
693 bool Value::RemovePath(StringPiece path) {
694 return ExtractPath(path).has_value();
697 Optional<Value> Value::ExtractPath(StringPiece path) {
698 if (!is_dict() || path.empty())
701 // NOTE: PathSplitter is not being used here because recursion is used to
702 // ensure that dictionaries that become empty due to this operation are
703 // removed automatically.
704 size_t pos = path.find('.');
705 if (pos == path.npos)
706 return ExtractKey(path);
708 auto found = dict_.find(path.substr(0, pos));
709 if (found == dict_.end() || !found->second->is_dict())
712 Optional<Value> extracted = found->second->ExtractPath(path.substr(pos + 1));
713 if (extracted && found->second->dict_.empty())
719 // DEPRECATED METHODS
720 Value* Value::FindPath(std::initializer_list<StringPiece> path) {
721 return const_cast<Value*>(as_const(*this).FindPath(path));
724 Value* Value::FindPath(span<const StringPiece> path) {
725 return const_cast<Value*>(as_const(*this).FindPath(path));
728 const Value* Value::FindPath(std::initializer_list<StringPiece> path) const {
729 DCHECK_GE(path.size(), 2u) << "Use FindKey() for a path of length 1.";
730 return FindPath(make_span(path.begin(), path.size()));
733 const Value* Value::FindPath(span<const StringPiece> path) const {
734 const Value* cur = this;
735 for (const StringPiece component : path) {
736 if (!cur->is_dict() || (cur = cur->FindKey(component)) == nullptr)
742 Value* Value::FindPathOfType(std::initializer_list<StringPiece> path,
744 return const_cast<Value*>(as_const(*this).FindPathOfType(path, type));
747 Value* Value::FindPathOfType(span<const StringPiece> path, Type type) {
748 return const_cast<Value*>(as_const(*this).FindPathOfType(path, type));
751 const Value* Value::FindPathOfType(std::initializer_list<StringPiece> path,
753 DCHECK_GE(path.size(), 2u) << "Use FindKeyOfType() for a path of length 1.";
754 return FindPathOfType(make_span(path.begin(), path.size()), type);
757 const Value* Value::FindPathOfType(span<const StringPiece> path,
759 const Value* result = FindPath(path);
760 if (!result || result->type() != type)
765 Value* Value::SetPath(std::initializer_list<StringPiece> path, Value&& value) {
766 DCHECK_GE(path.size(), 2u) << "Use SetKey() for a path of length 1.";
767 return SetPath(make_span(path.begin(), path.size()), std::move(value));
770 Value* Value::SetPath(span<const StringPiece> path, Value&& value) {
771 DCHECK(path.begin() != path.end()); // Can't be empty path.
773 // Walk/construct intermediate dictionaries. The last element requires
774 // special handling so skip it in this loop.
776 auto cur_path = path.begin();
777 for (; (cur_path + 1) < path.end(); ++cur_path) {
781 // Use lower_bound to avoid doing the search twice for missing keys.
782 const StringPiece path_component = *cur_path;
783 auto found = cur->dict_.lower_bound(path_component);
784 if (found == cur->dict_.end() || found->first != path_component) {
785 // No key found, insert one.
786 auto inserted = cur->dict_.try_emplace(
787 found, path_component, std::make_unique<Value>(Type::DICTIONARY));
788 cur = inserted->second.get();
790 cur = found->second.get();
794 // "cur" will now contain the last dictionary to insert or replace into.
797 return cur->SetKey(*cur_path, std::move(value));
800 bool Value::RemovePath(std::initializer_list<StringPiece> path) {
801 DCHECK_GE(path.size(), 2u) << "Use RemoveKey() for a path of length 1.";
802 return RemovePath(make_span(path.begin(), path.size()));
805 bool Value::RemovePath(span<const StringPiece> path) {
806 if (!is_dict() || path.empty())
809 if (path.size() == 1)
810 return RemoveKey(path[0]);
812 auto found = dict_.find(path[0]);
813 if (found == dict_.end() || !found->second->is_dict())
816 bool removed = found->second->RemovePath(path.subspan(1));
817 if (removed && found->second->dict_.empty())
823 Value::dict_iterator_proxy Value::DictItems() {
825 return dict_iterator_proxy(&dict_);
828 Value::const_dict_iterator_proxy Value::DictItems() const {
830 return const_dict_iterator_proxy(&dict_);
833 size_t Value::DictSize() const {
838 bool Value::DictEmpty() const {
840 return dict_.empty();
843 void Value::MergeDictionary(const Value* dictionary) {
845 CHECK(dictionary->is_dict());
846 for (const auto& pair : dictionary->dict_) {
847 const auto& key = pair.first;
848 const auto& val = pair.second;
849 // Check whether we have to merge dictionaries.
850 if (val->is_dict()) {
851 auto found = dict_.find(key);
852 if (found != dict_.end() && found->second->is_dict()) {
853 found->second->MergeDictionary(val.get());
858 // All other cases: Make a copy and hook it up.
859 SetKey(key, val->Clone());
863 bool Value::GetAsBoolean(bool* out_value) const {
864 if (out_value && is_bool()) {
865 *out_value = bool_value_;
871 bool Value::GetAsInteger(int* out_value) const {
872 if (out_value && is_int()) {
873 *out_value = int_value_;
879 bool Value::GetAsDouble(double* out_value) const {
880 if (out_value && is_double()) {
881 *out_value = AsDoubleInternal();
884 if (out_value && is_int()) {
885 // Allow promotion from int to double.
886 *out_value = int_value_;
889 return is_double() || is_int();
892 bool Value::GetAsString(std::string* out_value) const {
893 if (out_value && is_string()) {
894 *out_value = string_value_;
900 bool Value::GetAsString(string16* out_value) const {
901 if (out_value && is_string()) {
902 *out_value = UTF8ToUTF16(string_value_);
908 bool Value::GetAsString(const Value** out_value) const {
909 if (out_value && is_string()) {
916 bool Value::GetAsString(StringPiece* out_value) const {
917 if (out_value && is_string()) {
918 *out_value = string_value_;
924 bool Value::GetAsList(ListValue** out_value) {
925 if (out_value && is_list()) {
926 *out_value = static_cast<ListValue*>(this);
932 bool Value::GetAsList(const ListValue** out_value) const {
933 if (out_value && is_list()) {
934 *out_value = static_cast<const ListValue*>(this);
940 bool Value::GetAsDictionary(DictionaryValue** out_value) {
941 if (out_value && is_dict()) {
942 *out_value = static_cast<DictionaryValue*>(this);
948 bool Value::GetAsDictionary(const DictionaryValue** out_value) const {
949 if (out_value && is_dict()) {
950 *out_value = static_cast<const DictionaryValue*>(this);
956 Value* Value::DeepCopy() const {
957 return new Value(Clone());
960 std::unique_ptr<Value> Value::CreateDeepCopy() const {
961 return std::make_unique<Value>(Clone());
964 bool operator==(const Value& lhs, const Value& rhs) {
965 if (lhs.type_ != rhs.type_)
969 case Value::Type::NONE:
971 case Value::Type::BOOLEAN:
972 return lhs.bool_value_ == rhs.bool_value_;
973 case Value::Type::INTEGER:
974 return lhs.int_value_ == rhs.int_value_;
975 case Value::Type::DOUBLE:
976 return lhs.AsDoubleInternal() == rhs.AsDoubleInternal();
977 case Value::Type::STRING:
978 return lhs.string_value_ == rhs.string_value_;
979 case Value::Type::BINARY:
980 return lhs.binary_value_ == rhs.binary_value_;
981 // TODO(crbug.com/646113): Clean this up when DictionaryValue and ListValue
982 // are completely inlined.
983 case Value::Type::DICTIONARY:
984 if (lhs.dict_.size() != rhs.dict_.size())
986 return std::equal(std::begin(lhs.dict_), std::end(lhs.dict_),
987 std::begin(rhs.dict_),
988 [](const auto& u, const auto& v) {
989 return std::tie(u.first, *u.second) ==
990 std::tie(v.first, *v.second);
992 case Value::Type::LIST:
993 return lhs.list_ == rhs.list_;
994 // TODO(crbug.com/859477): Remove after root cause is found.
995 case Value::Type::DEAD:
1000 // TODO(crbug.com/859477): Revert to NOTREACHED() after root cause is found.
1005 bool operator!=(const Value& lhs, const Value& rhs) {
1006 return !(lhs == rhs);
1009 bool operator<(const Value& lhs, const Value& rhs) {
1010 if (lhs.type_ != rhs.type_)
1011 return lhs.type_ < rhs.type_;
1013 switch (lhs.type_) {
1014 case Value::Type::NONE:
1016 case Value::Type::BOOLEAN:
1017 return lhs.bool_value_ < rhs.bool_value_;
1018 case Value::Type::INTEGER:
1019 return lhs.int_value_ < rhs.int_value_;
1020 case Value::Type::DOUBLE:
1021 return lhs.AsDoubleInternal() < rhs.AsDoubleInternal();
1022 case Value::Type::STRING:
1023 return lhs.string_value_ < rhs.string_value_;
1024 case Value::Type::BINARY:
1025 return lhs.binary_value_ < rhs.binary_value_;
1026 // TODO(crbug.com/646113): Clean this up when DictionaryValue and ListValue
1027 // are completely inlined.
1028 case Value::Type::DICTIONARY:
1029 return std::lexicographical_compare(
1030 std::begin(lhs.dict_), std::end(lhs.dict_), std::begin(rhs.dict_),
1031 std::end(rhs.dict_),
1032 [](const Value::DictStorage::value_type& u,
1033 const Value::DictStorage::value_type& v) {
1034 return std::tie(u.first, *u.second) < std::tie(v.first, *v.second);
1036 case Value::Type::LIST:
1037 return lhs.list_ < rhs.list_;
1038 // TODO(crbug.com/859477): Remove after root cause is found.
1039 case Value::Type::DEAD:
1044 // TODO(crbug.com/859477): Revert to NOTREACHED() after root cause is found.
1049 bool operator>(const Value& lhs, const Value& rhs) {
1053 bool operator<=(const Value& lhs, const Value& rhs) {
1054 return !(rhs < lhs);
1057 bool operator>=(const Value& lhs, const Value& rhs) {
1058 return !(lhs < rhs);
1061 bool Value::Equals(const Value* other) const {
1063 return *this == *other;
1066 size_t Value::EstimateMemoryUsage() const {
1068 #if BUILDFLAG(ENABLE_BASE_TRACING)
1070 return base::trace_event::EstimateMemoryUsage(string_value_);
1072 return base::trace_event::EstimateMemoryUsage(binary_value_);
1073 case Type::DICTIONARY:
1074 return base::trace_event::EstimateMemoryUsage(dict_);
1076 return base::trace_event::EstimateMemoryUsage(list_);
1077 #endif // BUILDFLAG(ENABLE_BASE_TRACING)
1083 void Value::InternalMoveConstructFrom(Value&& that) {
1090 bool_value_ = that.bool_value_;
1093 int_value_ = that.int_value_;
1096 double_value_ = that.double_value_;
1099 new (&string_value_) std::string(std::move(that.string_value_));
1102 new (&binary_value_) BlobStorage(std::move(that.binary_value_));
1104 case Type::DICTIONARY:
1105 new (&dict_) DictStorage(std::move(that.dict_));
1108 new (&list_) ListStorage(std::move(that.list_));
1110 // TODO(crbug.com/859477): Remove after root cause is found.
1116 // TODO(crbug.com/859477): Revert to NOTREACHED() after root cause is found.
1120 void Value::InternalCleanup() {
1130 string_value_.~basic_string();
1133 binary_value_.~BlobStorage();
1135 case Type::DICTIONARY:
1136 dict_.~DictStorage();
1139 list_.~ListStorage();
1141 // TODO(crbug.com/859477): Remove after root cause is found.
1147 // TODO(crbug.com/859477): Revert to NOTREACHED() after root cause is found.
1151 Value* Value::SetKeyInternal(StringPiece key,
1152 std::unique_ptr<Value>&& val_ptr) {
1154 // NOTE: We can't use |insert_or_assign| here, as only |try_emplace| does
1155 // an explicit conversion from StringPiece to std::string if necessary.
1156 auto result = dict_.try_emplace(key, std::move(val_ptr));
1157 if (!result.second) {
1158 // val_ptr is guaranteed to be still intact at this point.
1159 result.first->second = std::move(val_ptr);
1161 return result.first->second.get();
1164 Value* Value::SetPathInternal(StringPiece path,
1165 std::unique_ptr<Value>&& value_ptr) {
1166 PathSplitter splitter(path);
1167 DCHECK(splitter.HasNext()) << "Cannot call SetPath() with empty path";
1168 // Walk/construct intermediate dictionaries. The last element requires
1169 // special handling so skip it in this loop.
1171 StringPiece path_component = splitter.Next();
1172 while (splitter.HasNext()) {
1173 if (!cur->is_dict())
1176 // Use lower_bound to avoid doing the search twice for missing keys.
1177 auto found = cur->dict_.lower_bound(path_component);
1178 if (found == cur->dict_.end() || found->first != path_component) {
1179 // No key found, insert one.
1180 auto inserted = cur->dict_.try_emplace(
1181 found, path_component, std::make_unique<Value>(Type::DICTIONARY));
1182 cur = inserted->second.get();
1184 cur = found->second.get();
1186 path_component = splitter.Next();
1189 // "cur" will now contain the last dictionary to insert or replace into.
1190 if (!cur->is_dict())
1192 return cur->SetKeyInternal(path_component, std::move(value_ptr));
1195 ///////////////////// DictionaryValue ////////////////////
1198 std::unique_ptr<DictionaryValue> DictionaryValue::From(
1199 std::unique_ptr<Value> value) {
1200 DictionaryValue* out;
1201 if (value && value->GetAsDictionary(&out)) {
1202 ignore_result(value.release());
1203 return WrapUnique(out);
1208 DictionaryValue::DictionaryValue() : Value(Type::DICTIONARY) {}
1209 DictionaryValue::DictionaryValue(const DictStorage& in_dict) : Value(in_dict) {}
1210 DictionaryValue::DictionaryValue(DictStorage&& in_dict) noexcept
1211 : Value(std::move(in_dict)) {}
1213 bool DictionaryValue::HasKey(StringPiece key) const {
1214 DCHECK(IsStringUTF8AllowingNoncharacters(key));
1215 auto current_entry = dict_.find(key);
1216 DCHECK((current_entry == dict_.end()) || current_entry->second);
1217 return current_entry != dict_.end();
1220 void DictionaryValue::Clear() {
1224 Value* DictionaryValue::Set(StringPiece path, std::unique_ptr<Value> in_value) {
1225 DCHECK(IsStringUTF8AllowingNoncharacters(path));
1228 // IMPORTANT NOTE: Do not replace with SetPathInternal() yet, because the
1229 // latter fails when over-writing a non-dict intermediate node, while this
1230 // method just replaces it with one. This difference makes some tests actually
1231 // fail (http://crbug.com/949461).
1232 StringPiece current_path(path);
1233 Value* current_dictionary = this;
1234 for (size_t delimiter_position = current_path.find('.');
1235 delimiter_position != StringPiece::npos;
1236 delimiter_position = current_path.find('.')) {
1237 // Assume that we're indexing into a dictionary.
1238 StringPiece key = current_path.substr(0, delimiter_position);
1239 Value* child_dictionary =
1240 current_dictionary->FindKeyOfType(key, Type::DICTIONARY);
1241 if (!child_dictionary) {
1243 current_dictionary->SetKey(key, Value(Type::DICTIONARY));
1246 current_dictionary = child_dictionary;
1247 current_path = current_path.substr(delimiter_position + 1);
1250 return static_cast<DictionaryValue*>(current_dictionary)
1251 ->SetWithoutPathExpansion(current_path, std::move(in_value));
1254 Value* DictionaryValue::SetBoolean(StringPiece path, bool in_value) {
1255 return Set(path, std::make_unique<Value>(in_value));
1258 Value* DictionaryValue::SetInteger(StringPiece path, int in_value) {
1259 return Set(path, std::make_unique<Value>(in_value));
1262 Value* DictionaryValue::SetDouble(StringPiece path, double in_value) {
1263 return Set(path, std::make_unique<Value>(in_value));
1266 Value* DictionaryValue::SetString(StringPiece path, StringPiece in_value) {
1267 return Set(path, std::make_unique<Value>(in_value));
1270 Value* DictionaryValue::SetString(StringPiece path, const string16& in_value) {
1271 return Set(path, std::make_unique<Value>(in_value));
1274 DictionaryValue* DictionaryValue::SetDictionary(
1276 std::unique_ptr<DictionaryValue> in_value) {
1277 return static_cast<DictionaryValue*>(Set(path, std::move(in_value)));
1280 ListValue* DictionaryValue::SetList(StringPiece path,
1281 std::unique_ptr<ListValue> in_value) {
1282 return static_cast<ListValue*>(Set(path, std::move(in_value)));
1285 Value* DictionaryValue::SetWithoutPathExpansion(
1287 std::unique_ptr<Value> in_value) {
1288 // NOTE: We can't use |insert_or_assign| here, as only |try_emplace| does
1289 // an explicit conversion from StringPiece to std::string if necessary.
1290 auto result = dict_.try_emplace(key, std::move(in_value));
1291 if (!result.second) {
1292 // in_value is guaranteed to be still intact at this point.
1293 result.first->second = std::move(in_value);
1295 return result.first->second.get();
1298 bool DictionaryValue::Get(StringPiece path,
1299 const Value** out_value) const {
1300 DCHECK(IsStringUTF8AllowingNoncharacters(path));
1301 const Value* value = FindPath(path);
1309 bool DictionaryValue::Get(StringPiece path, Value** out_value) {
1310 return as_const(*this).Get(path, const_cast<const Value**>(out_value));
1313 bool DictionaryValue::GetBoolean(StringPiece path, bool* bool_value) const {
1315 if (!Get(path, &value))
1318 return value->GetAsBoolean(bool_value);
1321 bool DictionaryValue::GetInteger(StringPiece path, int* out_value) const {
1323 if (!Get(path, &value))
1326 return value->GetAsInteger(out_value);
1329 bool DictionaryValue::GetDouble(StringPiece path, double* out_value) const {
1331 if (!Get(path, &value))
1334 return value->GetAsDouble(out_value);
1337 bool DictionaryValue::GetString(StringPiece path,
1338 std::string* out_value) const {
1340 if (!Get(path, &value))
1343 return value->GetAsString(out_value);
1346 bool DictionaryValue::GetString(StringPiece path, string16* out_value) const {
1348 if (!Get(path, &value))
1351 return value->GetAsString(out_value);
1354 bool DictionaryValue::GetStringASCII(StringPiece path,
1355 std::string* out_value) const {
1357 if (!GetString(path, &out))
1360 if (!IsStringASCII(out)) {
1365 out_value->assign(out);
1369 bool DictionaryValue::GetBinary(StringPiece path,
1370 const Value** out_value) const {
1372 bool result = Get(path, &value);
1373 if (!result || !value->is_blob())
1382 bool DictionaryValue::GetBinary(StringPiece path, Value** out_value) {
1383 return as_const(*this).GetBinary(path, const_cast<const Value**>(out_value));
1386 bool DictionaryValue::GetDictionary(StringPiece path,
1387 const DictionaryValue** out_value) const {
1389 bool result = Get(path, &value);
1390 if (!result || !value->is_dict())
1394 *out_value = static_cast<const DictionaryValue*>(value);
1399 bool DictionaryValue::GetDictionary(StringPiece path,
1400 DictionaryValue** out_value) {
1401 return as_const(*this).GetDictionary(
1402 path, const_cast<const DictionaryValue**>(out_value));
1405 bool DictionaryValue::GetList(StringPiece path,
1406 const ListValue** out_value) const {
1408 bool result = Get(path, &value);
1409 if (!result || !value->is_list())
1413 *out_value = static_cast<const ListValue*>(value);
1418 bool DictionaryValue::GetList(StringPiece path, ListValue** out_value) {
1419 return as_const(*this).GetList(path,
1420 const_cast<const ListValue**>(out_value));
1423 bool DictionaryValue::GetWithoutPathExpansion(StringPiece key,
1424 const Value** out_value) const {
1425 DCHECK(IsStringUTF8AllowingNoncharacters(key));
1426 auto entry_iterator = dict_.find(key);
1427 if (entry_iterator == dict_.end())
1431 *out_value = entry_iterator->second.get();
1435 bool DictionaryValue::GetWithoutPathExpansion(StringPiece key,
1436 Value** out_value) {
1437 return as_const(*this).GetWithoutPathExpansion(
1438 key, const_cast<const Value**>(out_value));
1441 bool DictionaryValue::GetBooleanWithoutPathExpansion(StringPiece key,
1442 bool* out_value) const {
1444 if (!GetWithoutPathExpansion(key, &value))
1447 return value->GetAsBoolean(out_value);
1450 bool DictionaryValue::GetIntegerWithoutPathExpansion(StringPiece key,
1451 int* out_value) const {
1453 if (!GetWithoutPathExpansion(key, &value))
1456 return value->GetAsInteger(out_value);
1459 bool DictionaryValue::GetDoubleWithoutPathExpansion(StringPiece key,
1460 double* out_value) const {
1462 if (!GetWithoutPathExpansion(key, &value))
1465 return value->GetAsDouble(out_value);
1468 bool DictionaryValue::GetStringWithoutPathExpansion(
1470 std::string* out_value) const {
1472 if (!GetWithoutPathExpansion(key, &value))
1475 return value->GetAsString(out_value);
1478 bool DictionaryValue::GetStringWithoutPathExpansion(StringPiece key,
1479 string16* out_value) const {
1481 if (!GetWithoutPathExpansion(key, &value))
1484 return value->GetAsString(out_value);
1487 bool DictionaryValue::GetDictionaryWithoutPathExpansion(
1489 const DictionaryValue** out_value) const {
1491 bool result = GetWithoutPathExpansion(key, &value);
1492 if (!result || !value->is_dict())
1496 *out_value = static_cast<const DictionaryValue*>(value);
1501 bool DictionaryValue::GetDictionaryWithoutPathExpansion(
1503 DictionaryValue** out_value) {
1504 return as_const(*this).GetDictionaryWithoutPathExpansion(
1505 key, const_cast<const DictionaryValue**>(out_value));
1508 bool DictionaryValue::GetListWithoutPathExpansion(
1510 const ListValue** out_value) const {
1512 bool result = GetWithoutPathExpansion(key, &value);
1513 if (!result || !value->is_list())
1517 *out_value = static_cast<const ListValue*>(value);
1522 bool DictionaryValue::GetListWithoutPathExpansion(StringPiece key,
1523 ListValue** out_value) {
1524 return as_const(*this).GetListWithoutPathExpansion(
1525 key, const_cast<const ListValue**>(out_value));
1528 bool DictionaryValue::Remove(StringPiece path,
1529 std::unique_ptr<Value>* out_value) {
1530 DCHECK(IsStringUTF8AllowingNoncharacters(path));
1531 StringPiece current_path(path);
1532 DictionaryValue* current_dictionary = this;
1533 size_t delimiter_position = current_path.rfind('.');
1534 if (delimiter_position != StringPiece::npos) {
1535 if (!GetDictionary(current_path.substr(0, delimiter_position),
1536 ¤t_dictionary))
1538 current_path = current_path.substr(delimiter_position + 1);
1541 return current_dictionary->RemoveWithoutPathExpansion(current_path,
1545 bool DictionaryValue::RemoveWithoutPathExpansion(
1547 std::unique_ptr<Value>* out_value) {
1548 DCHECK(IsStringUTF8AllowingNoncharacters(key));
1549 auto entry_iterator = dict_.find(key);
1550 if (entry_iterator == dict_.end())
1554 *out_value = std::move(entry_iterator->second);
1555 dict_.erase(entry_iterator);
1559 bool DictionaryValue::RemovePath(StringPiece path,
1560 std::unique_ptr<Value>* out_value) {
1561 bool result = false;
1562 size_t delimiter_position = path.find('.');
1564 if (delimiter_position == std::string::npos)
1565 return RemoveWithoutPathExpansion(path, out_value);
1567 StringPiece subdict_path = path.substr(0, delimiter_position);
1568 DictionaryValue* subdict = nullptr;
1569 if (!GetDictionary(subdict_path, &subdict))
1571 result = subdict->RemovePath(path.substr(delimiter_position + 1),
1573 if (result && subdict->empty())
1574 RemoveWithoutPathExpansion(subdict_path, nullptr);
1579 std::unique_ptr<DictionaryValue> DictionaryValue::DeepCopyWithoutEmptyChildren()
1581 std::unique_ptr<DictionaryValue> copy =
1582 CopyDictionaryWithoutEmptyChildren(*this);
1584 copy = std::make_unique<DictionaryValue>();
1588 void DictionaryValue::Swap(DictionaryValue* other) {
1589 CHECK(other->is_dict());
1590 dict_.swap(other->dict_);
1593 DictionaryValue::Iterator::Iterator(const DictionaryValue& target)
1594 : target_(target), it_(target.dict_.begin()) {}
1596 DictionaryValue::Iterator::Iterator(const Iterator& other) = default;
1598 DictionaryValue::Iterator::~Iterator() = default;
1600 DictionaryValue* DictionaryValue::DeepCopy() const {
1601 return new DictionaryValue(dict_);
1604 std::unique_ptr<DictionaryValue> DictionaryValue::CreateDeepCopy() const {
1605 return std::make_unique<DictionaryValue>(dict_);
1608 ///////////////////// ListValue ////////////////////
1611 std::unique_ptr<ListValue> ListValue::From(std::unique_ptr<Value> value) {
1613 if (value && value->GetAsList(&out)) {
1614 ignore_result(value.release());
1615 return WrapUnique(out);
1620 ListValue::ListValue() : Value(Type::LIST) {}
1621 ListValue::ListValue(span<const Value> in_list) : Value(in_list) {}
1622 ListValue::ListValue(ListStorage&& in_list) noexcept
1623 : Value(std::move(in_list)) {}
1625 void ListValue::Clear() {
1629 void ListValue::Reserve(size_t n) {
1633 bool ListValue::Set(size_t index, std::unique_ptr<Value> in_value) {
1637 if (index >= list_.size())
1638 list_.resize(index + 1);
1640 list_[index] = std::move(*in_value);
1644 bool ListValue::Get(size_t index, const Value** out_value) const {
1645 if (index >= list_.size())
1649 *out_value = &list_[index];
1654 bool ListValue::Get(size_t index, Value** out_value) {
1655 return as_const(*this).Get(index, const_cast<const Value**>(out_value));
1658 bool ListValue::GetBoolean(size_t index, bool* bool_value) const {
1660 if (!Get(index, &value))
1663 return value->GetAsBoolean(bool_value);
1666 bool ListValue::GetInteger(size_t index, int* out_value) const {
1668 if (!Get(index, &value))
1671 return value->GetAsInteger(out_value);
1674 bool ListValue::GetDouble(size_t index, double* out_value) const {
1676 if (!Get(index, &value))
1679 return value->GetAsDouble(out_value);
1682 bool ListValue::GetString(size_t index, std::string* out_value) const {
1684 if (!Get(index, &value))
1687 return value->GetAsString(out_value);
1690 bool ListValue::GetString(size_t index, string16* out_value) const {
1692 if (!Get(index, &value))
1695 return value->GetAsString(out_value);
1698 bool ListValue::GetDictionary(size_t index,
1699 const DictionaryValue** out_value) const {
1701 bool result = Get(index, &value);
1702 if (!result || !value->is_dict())
1706 *out_value = static_cast<const DictionaryValue*>(value);
1711 bool ListValue::GetDictionary(size_t index, DictionaryValue** out_value) {
1712 return as_const(*this).GetDictionary(
1713 index, const_cast<const DictionaryValue**>(out_value));
1716 bool ListValue::GetList(size_t index, const ListValue** out_value) const {
1718 bool result = Get(index, &value);
1719 if (!result || !value->is_list())
1723 *out_value = static_cast<const ListValue*>(value);
1728 bool ListValue::GetList(size_t index, ListValue** out_value) {
1729 return as_const(*this).GetList(index,
1730 const_cast<const ListValue**>(out_value));
1733 bool ListValue::Remove(size_t index, std::unique_ptr<Value>* out_value) {
1734 if (index >= list_.size())
1738 *out_value = std::make_unique<Value>(std::move(list_[index]));
1740 list_.erase(list_.begin() + index);
1744 bool ListValue::Remove(const Value& value, size_t* index) {
1745 auto it = std::find(list_.begin(), list_.end(), value);
1747 if (it == list_.end())
1751 *index = std::distance(list_.begin(), it);
1757 ListValue::iterator ListValue::Erase(iterator iter,
1758 std::unique_ptr<Value>* out_value) {
1760 *out_value = std::make_unique<Value>(std::move(*iter));
1762 auto list_iter = list_.begin() + (iter - GetList().begin());
1763 CHECK(list_iter != list_.end());
1764 list_iter = list_.erase(list_iter);
1765 return GetList().begin() + (list_iter - list_.begin());
1768 void ListValue::Append(std::unique_ptr<Value> in_value) {
1769 list_.push_back(std::move(*in_value));
1772 void ListValue::AppendBoolean(bool in_value) {
1773 list_.emplace_back(in_value);
1776 void ListValue::AppendInteger(int in_value) {
1777 list_.emplace_back(in_value);
1780 void ListValue::AppendDouble(double in_value) {
1781 list_.emplace_back(in_value);
1784 void ListValue::AppendString(StringPiece in_value) {
1785 list_.emplace_back(in_value);
1788 void ListValue::AppendString(const string16& in_value) {
1789 list_.emplace_back(in_value);
1792 void ListValue::AppendStrings(const std::vector<std::string>& in_values) {
1793 list_.reserve(list_.size() + in_values.size());
1794 for (const auto& in_value : in_values)
1795 list_.emplace_back(in_value);
1798 void ListValue::AppendStrings(const std::vector<string16>& in_values) {
1799 list_.reserve(list_.size() + in_values.size());
1800 for (const auto& in_value : in_values)
1801 list_.emplace_back(in_value);
1804 bool ListValue::AppendIfNotPresent(std::unique_ptr<Value> in_value) {
1806 if (Contains(list_, *in_value))
1809 list_.push_back(std::move(*in_value));
1813 bool ListValue::Insert(size_t index, std::unique_ptr<Value> in_value) {
1815 if (index > list_.size())
1818 list_.insert(list_.begin() + index, std::move(*in_value));
1822 ListValue::const_iterator ListValue::Find(const Value& value) const {
1823 return std::find(GetList().begin(), GetList().end(), value);
1826 void ListValue::Swap(ListValue* other) {
1827 CHECK(other->is_list());
1828 list_.swap(other->list_);
1831 ListValue* ListValue::DeepCopy() const {
1832 return new ListValue(list_);
1835 std::unique_ptr<ListValue> ListValue::CreateDeepCopy() const {
1836 return std::make_unique<ListValue>(list_);
1839 ValueSerializer::~ValueSerializer() = default;
1841 ValueDeserializer::~ValueDeserializer() = default;
1843 std::ostream& operator<<(std::ostream& out, const Value& value) {
1845 JSONWriter::WriteWithOptions(value, JSONWriter::OPTIONS_PRETTY_PRINT, &json);
1849 std::ostream& operator<<(std::ostream& out, const Value::Type& type) {
1850 if (static_cast<int>(type) < 0 ||
1851 static_cast<size_t>(type) >= base::size(kTypeNames))
1852 return out << "Invalid Type (index = " << static_cast<int>(type) << ")";
1853 return out << Value::GetTypeName(type);