blob: df12c2987e8df77c2c3025fde3ba98572330a460 [file] [log] [blame]
Scott Graham66962112018-06-08 12:42:08 -07001// 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
5#include "base/values.h"
6
7#include <string.h>
8
9#include <algorithm>
10#include <cmath>
11#include <new>
12#include <ostream>
13#include <utility>
14
15#include "base/json/json_writer.h"
16#include "base/logging.h"
17#include "base/memory/ptr_util.h"
18#include "base/stl_util.h"
19#include "base/strings/string_util.h"
20#include "base/strings/utf_string_conversions.h"
Scott Graham66962112018-06-08 12:42:08 -070021
22namespace base {
23
24namespace {
25
26const char* const kTypeNames[] = {"null", "boolean", "integer", "double",
27 "string", "binary", "dictionary", "list"};
28static_assert(arraysize(kTypeNames) ==
29 static_cast<size_t>(Value::Type::LIST) + 1,
30 "kTypeNames Has Wrong Size");
31
32std::unique_ptr<Value> CopyWithoutEmptyChildren(const Value& node);
33
34// Make a deep copy of |node|, but don't include empty lists or dictionaries
35// in the copy. It's possible for this function to return NULL and it
36// expects |node| to always be non-NULL.
37std::unique_ptr<Value> CopyListWithoutEmptyChildren(const Value& list) {
38 Value copy(Value::Type::LIST);
39 for (const auto& entry : list.GetList()) {
40 std::unique_ptr<Value> child_copy = CopyWithoutEmptyChildren(entry);
41 if (child_copy)
42 copy.GetList().push_back(std::move(*child_copy));
43 }
44 return copy.GetList().empty() ? nullptr
45 : std::make_unique<Value>(std::move(copy));
46}
47
48std::unique_ptr<DictionaryValue> CopyDictionaryWithoutEmptyChildren(
49 const DictionaryValue& dict) {
50 std::unique_ptr<DictionaryValue> copy;
51 for (DictionaryValue::Iterator it(dict); !it.IsAtEnd(); it.Advance()) {
52 std::unique_ptr<Value> child_copy = CopyWithoutEmptyChildren(it.value());
53 if (child_copy) {
54 if (!copy)
55 copy = std::make_unique<DictionaryValue>();
56 copy->SetWithoutPathExpansion(it.key(), std::move(child_copy));
57 }
58 }
59 return copy;
60}
61
62std::unique_ptr<Value> CopyWithoutEmptyChildren(const Value& node) {
63 switch (node.type()) {
64 case Value::Type::LIST:
65 return CopyListWithoutEmptyChildren(static_cast<const ListValue&>(node));
66
67 case Value::Type::DICTIONARY:
68 return CopyDictionaryWithoutEmptyChildren(
69 static_cast<const DictionaryValue&>(node));
70
71 default:
72 return std::make_unique<Value>(node.Clone());
73 }
74}
75
76} // namespace
77
78// static
79std::unique_ptr<Value> Value::CreateWithCopiedBuffer(const char* buffer,
80 size_t size) {
81 return std::make_unique<Value>(BlobStorage(buffer, buffer + size));
82}
83
84// static
85Value Value::FromUniquePtrValue(std::unique_ptr<Value> val) {
86 return std::move(*val);
87}
88
89// static
90std::unique_ptr<Value> Value::ToUniquePtrValue(Value val) {
91 return std::make_unique<Value>(std::move(val));
92}
93
94Value::Value(Value&& that) noexcept {
95 InternalMoveConstructFrom(std::move(that));
96}
97
98Value::Value() noexcept : type_(Type::NONE) {}
99
100Value::Value(Type type) : type_(type) {
101 // Initialize with the default value.
102 switch (type_) {
103 case Type::NONE:
104 return;
105
106 case Type::BOOLEAN:
107 bool_value_ = false;
108 return;
109 case Type::INTEGER:
110 int_value_ = 0;
111 return;
112 case Type::DOUBLE:
113 double_value_ = 0.0;
114 return;
115 case Type::STRING:
116 new (&string_value_) std::string();
117 return;
118 case Type::BINARY:
119 new (&binary_value_) BlobStorage();
120 return;
121 case Type::DICTIONARY:
122 new (&dict_) DictStorage();
123 return;
124 case Type::LIST:
125 new (&list_) ListStorage();
126 return;
127 }
128}
129
130Value::Value(bool in_bool) : type_(Type::BOOLEAN), bool_value_(in_bool) {}
131
132Value::Value(int in_int) : type_(Type::INTEGER), int_value_(in_int) {}
133
134Value::Value(double in_double) : type_(Type::DOUBLE), double_value_(in_double) {
135 if (!std::isfinite(double_value_)) {
136 NOTREACHED() << "Non-finite (i.e. NaN or positive/negative infinity) "
137 << "values cannot be represented in JSON";
138 double_value_ = 0.0;
139 }
140}
141
142Value::Value(const char* in_string) : Value(std::string(in_string)) {}
143
144Value::Value(StringPiece in_string) : Value(std::string(in_string)) {}
145
146Value::Value(std::string&& in_string) noexcept
147 : type_(Type::STRING), string_value_(std::move(in_string)) {
148 DCHECK(IsStringUTF8(string_value_));
149}
150
151Value::Value(const char16* in_string16) : Value(StringPiece16(in_string16)) {}
152
153Value::Value(StringPiece16 in_string16) : Value(UTF16ToUTF8(in_string16)) {}
154
155Value::Value(const BlobStorage& in_blob)
156 : type_(Type::BINARY), binary_value_(in_blob) {}
157
158Value::Value(BlobStorage&& in_blob) noexcept
159 : type_(Type::BINARY), binary_value_(std::move(in_blob)) {}
160
161Value::Value(const DictStorage& in_dict) : type_(Type::DICTIONARY), dict_() {
162 dict_.reserve(in_dict.size());
163 for (const auto& it : in_dict) {
164 dict_.try_emplace(dict_.end(), it.first,
165 std::make_unique<Value>(it.second->Clone()));
166 }
167}
168
169Value::Value(DictStorage&& in_dict) noexcept
170 : type_(Type::DICTIONARY), dict_(std::move(in_dict)) {}
171
172Value::Value(const ListStorage& in_list) : type_(Type::LIST), list_() {
173 list_.reserve(in_list.size());
174 for (const auto& val : in_list)
175 list_.emplace_back(val.Clone());
176}
177
178Value::Value(ListStorage&& in_list) noexcept
179 : type_(Type::LIST), list_(std::move(in_list)) {}
180
181Value& Value::operator=(Value&& that) noexcept {
182 InternalCleanup();
183 InternalMoveConstructFrom(std::move(that));
184
185 return *this;
186}
187
188Value Value::Clone() const {
189 switch (type_) {
190 case Type::NONE:
191 return Value();
192 case Type::BOOLEAN:
193 return Value(bool_value_);
194 case Type::INTEGER:
195 return Value(int_value_);
196 case Type::DOUBLE:
197 return Value(double_value_);
198 case Type::STRING:
199 return Value(string_value_);
200 case Type::BINARY:
201 return Value(binary_value_);
202 case Type::DICTIONARY:
203 return Value(dict_);
204 case Type::LIST:
205 return Value(list_);
206 }
207
208 NOTREACHED();
209 return Value();
210}
211
212Value::~Value() {
213 InternalCleanup();
214}
215
216// static
217const char* Value::GetTypeName(Value::Type type) {
218 DCHECK_GE(static_cast<int>(type), 0);
219 DCHECK_LT(static_cast<size_t>(type), arraysize(kTypeNames));
220 return kTypeNames[static_cast<size_t>(type)];
221}
222
223bool Value::GetBool() const {
224 CHECK(is_bool());
225 return bool_value_;
226}
227
228int Value::GetInt() const {
229 CHECK(is_int());
230 return int_value_;
231}
232
233double Value::GetDouble() const {
234 if (is_double())
235 return double_value_;
236 if (is_int())
237 return int_value_;
238 CHECK(false);
239 return 0.0;
240}
241
242const std::string& Value::GetString() const {
243 CHECK(is_string());
244 return string_value_;
245}
246
247const Value::BlobStorage& Value::GetBlob() const {
248 CHECK(is_blob());
249 return binary_value_;
250}
251
252Value::ListStorage& Value::GetList() {
253 CHECK(is_list());
254 return list_;
255}
256
257const Value::ListStorage& Value::GetList() const {
258 CHECK(is_list());
259 return list_;
260}
261
262Value* Value::FindKey(StringPiece key) {
263 return const_cast<Value*>(static_cast<const Value*>(this)->FindKey(key));
264}
265
266const Value* Value::FindKey(StringPiece key) const {
267 CHECK(is_dict());
268 auto found = dict_.find(key);
269 if (found == dict_.end())
270 return nullptr;
271 return found->second.get();
272}
273
274Value* Value::FindKeyOfType(StringPiece key, Type type) {
275 return const_cast<Value*>(
276 static_cast<const Value*>(this)->FindKeyOfType(key, type));
277}
278
279const Value* Value::FindKeyOfType(StringPiece key, Type type) const {
280 const Value* result = FindKey(key);
281 if (!result || result->type() != type)
282 return nullptr;
283 return result;
284}
285
286bool Value::RemoveKey(StringPiece key) {
287 CHECK(is_dict());
288 // NOTE: Can't directly return dict_->erase(key) due to MSVC warning C4800.
289 return dict_.erase(key) != 0;
290}
291
292Value* Value::SetKey(StringPiece key, Value value) {
293 CHECK(is_dict());
294 // NOTE: We can't use |insert_or_assign| here, as only |try_emplace| does
295 // an explicit conversion from StringPiece to std::string if necessary.
296 auto val_ptr = std::make_unique<Value>(std::move(value));
297 auto result = dict_.try_emplace(key, std::move(val_ptr));
298 if (!result.second) {
299 // val_ptr is guaranteed to be still intact at this point.
300 result.first->second = std::move(val_ptr);
301 }
302 return result.first->second.get();
303}
304
305Value* Value::SetKey(std::string&& key, Value value) {
306 CHECK(is_dict());
307 return dict_
308 .insert_or_assign(std::move(key),
309 std::make_unique<Value>(std::move(value)))
310 .first->second.get();
311}
312
313Value* Value::SetKey(const char* key, Value value) {
314 return SetKey(StringPiece(key), std::move(value));
315}
316
317Value* Value::FindPath(std::initializer_list<StringPiece> path) {
318 return const_cast<Value*>(const_cast<const Value*>(this)->FindPath(path));
319}
320
321Value* Value::FindPath(span<const StringPiece> path) {
322 return const_cast<Value*>(const_cast<const Value*>(this)->FindPath(path));
323}
324
325const Value* Value::FindPath(std::initializer_list<StringPiece> path) const {
326 DCHECK_GE(path.size(), 2u) << "Use FindKey() for a path of length 1.";
327 return FindPath(make_span(path.begin(), path.size()));
328}
329
330const Value* Value::FindPath(span<const StringPiece> path) const {
331 const Value* cur = this;
332 for (const StringPiece component : path) {
333 if (!cur->is_dict() || (cur = cur->FindKey(component)) == nullptr)
334 return nullptr;
335 }
336 return cur;
337}
338
339Value* Value::FindPathOfType(std::initializer_list<StringPiece> path,
340 Type type) {
341 return const_cast<Value*>(
342 const_cast<const Value*>(this)->FindPathOfType(path, type));
343}
344
345Value* Value::FindPathOfType(span<const StringPiece> path, Type type) {
346 return const_cast<Value*>(
347 const_cast<const Value*>(this)->FindPathOfType(path, type));
348}
349
350const Value* Value::FindPathOfType(std::initializer_list<StringPiece> path,
351 Type type) const {
352 DCHECK_GE(path.size(), 2u) << "Use FindKeyOfType() for a path of length 1.";
353 return FindPathOfType(make_span(path.begin(), path.size()), type);
354}
355
356const Value* Value::FindPathOfType(span<const StringPiece> path,
357 Type type) const {
358 const Value* result = FindPath(path);
359 if (!result || result->type() != type)
360 return nullptr;
361 return result;
362}
363
364Value* Value::SetPath(std::initializer_list<StringPiece> path, Value value) {
365 DCHECK_GE(path.size(), 2u) << "Use SetKey() for a path of length 1.";
366 return SetPath(make_span(path.begin(), path.size()), std::move(value));
367}
368
369Value* Value::SetPath(span<const StringPiece> path, Value value) {
370 DCHECK_NE(path.begin(), path.end()); // Can't be empty path.
371
372 // Walk/construct intermediate dictionaries. The last element requires
373 // special handling so skip it in this loop.
374 Value* cur = this;
375 const StringPiece* cur_path = path.begin();
376 for (; (cur_path + 1) < path.end(); ++cur_path) {
377 if (!cur->is_dict())
378 return nullptr;
379
380 // Use lower_bound to avoid doing the search twice for missing keys.
381 const StringPiece path_component = *cur_path;
382 auto found = cur->dict_.lower_bound(path_component);
383 if (found == cur->dict_.end() || found->first != path_component) {
384 // No key found, insert one.
385 auto inserted = cur->dict_.try_emplace(
386 found, path_component, std::make_unique<Value>(Type::DICTIONARY));
387 cur = inserted->second.get();
388 } else {
389 cur = found->second.get();
390 }
391 }
392
393 // "cur" will now contain the last dictionary to insert or replace into.
394 if (!cur->is_dict())
395 return nullptr;
396 return cur->SetKey(*cur_path, std::move(value));
397}
398
399bool Value::RemovePath(std::initializer_list<StringPiece> path) {
400 DCHECK_GE(path.size(), 2u) << "Use RemoveKey() for a path of length 1.";
401 return RemovePath(make_span(path.begin(), path.size()));
402}
403
404bool Value::RemovePath(span<const StringPiece> path) {
405 if (!is_dict() || path.empty())
406 return false;
407
408 if (path.size() == 1)
409 return RemoveKey(path[0]);
410
411 auto found = dict_.find(path[0]);
412 if (found == dict_.end() || !found->second->is_dict())
413 return false;
414
415 bool removed = found->second->RemovePath(path.subspan(1));
416 if (removed && found->second->dict_.empty())
417 dict_.erase(found);
418
419 return removed;
420}
421
422Value::dict_iterator_proxy Value::DictItems() {
423 CHECK(is_dict());
424 return dict_iterator_proxy(&dict_);
425}
426
427Value::const_dict_iterator_proxy Value::DictItems() const {
428 CHECK(is_dict());
429 return const_dict_iterator_proxy(&dict_);
430}
431
432size_t Value::DictSize() const {
433 CHECK(is_dict());
434 return dict_.size();
435}
436
437bool Value::DictEmpty() const {
438 CHECK(is_dict());
439 return dict_.empty();
440}
441
442bool Value::GetAsBoolean(bool* out_value) const {
443 if (out_value && is_bool()) {
444 *out_value = bool_value_;
445 return true;
446 }
447 return is_bool();
448}
449
450bool Value::GetAsInteger(int* out_value) const {
451 if (out_value && is_int()) {
452 *out_value = int_value_;
453 return true;
454 }
455 return is_int();
456}
457
458bool Value::GetAsDouble(double* out_value) const {
459 if (out_value && is_double()) {
460 *out_value = double_value_;
461 return true;
462 } else if (out_value && is_int()) {
463 // Allow promotion from int to double.
464 *out_value = int_value_;
465 return true;
466 }
467 return is_double() || is_int();
468}
469
470bool Value::GetAsString(std::string* out_value) const {
471 if (out_value && is_string()) {
472 *out_value = string_value_;
473 return true;
474 }
475 return is_string();
476}
477
478bool Value::GetAsString(string16* out_value) const {
479 if (out_value && is_string()) {
480 *out_value = UTF8ToUTF16(string_value_);
481 return true;
482 }
483 return is_string();
484}
485
486bool Value::GetAsString(const Value** out_value) const {
487 if (out_value && is_string()) {
488 *out_value = static_cast<const Value*>(this);
489 return true;
490 }
491 return is_string();
492}
493
494bool Value::GetAsString(StringPiece* out_value) const {
495 if (out_value && is_string()) {
496 *out_value = string_value_;
497 return true;
498 }
499 return is_string();
500}
501
502bool Value::GetAsList(ListValue** out_value) {
503 if (out_value && is_list()) {
504 *out_value = static_cast<ListValue*>(this);
505 return true;
506 }
507 return is_list();
508}
509
510bool Value::GetAsList(const ListValue** out_value) const {
511 if (out_value && is_list()) {
512 *out_value = static_cast<const ListValue*>(this);
513 return true;
514 }
515 return is_list();
516}
517
518bool Value::GetAsDictionary(DictionaryValue** out_value) {
519 if (out_value && is_dict()) {
520 *out_value = static_cast<DictionaryValue*>(this);
521 return true;
522 }
523 return is_dict();
524}
525
526bool Value::GetAsDictionary(const DictionaryValue** out_value) const {
527 if (out_value && is_dict()) {
528 *out_value = static_cast<const DictionaryValue*>(this);
529 return true;
530 }
531 return is_dict();
532}
533
534Value* Value::DeepCopy() const {
535 return new Value(Clone());
536}
537
538std::unique_ptr<Value> Value::CreateDeepCopy() const {
539 return std::make_unique<Value>(Clone());
540}
541
542bool operator==(const Value& lhs, const Value& rhs) {
543 if (lhs.type_ != rhs.type_)
544 return false;
545
546 switch (lhs.type_) {
547 case Value::Type::NONE:
548 return true;
549 case Value::Type::BOOLEAN:
550 return lhs.bool_value_ == rhs.bool_value_;
551 case Value::Type::INTEGER:
552 return lhs.int_value_ == rhs.int_value_;
553 case Value::Type::DOUBLE:
554 return lhs.double_value_ == rhs.double_value_;
555 case Value::Type::STRING:
556 return lhs.string_value_ == rhs.string_value_;
557 case Value::Type::BINARY:
558 return lhs.binary_value_ == rhs.binary_value_;
559 // TODO(crbug.com/646113): Clean this up when DictionaryValue and ListValue
560 // are completely inlined.
561 case Value::Type::DICTIONARY:
562 if (lhs.dict_.size() != rhs.dict_.size())
563 return false;
564 return std::equal(std::begin(lhs.dict_), std::end(lhs.dict_),
565 std::begin(rhs.dict_),
566 [](const auto& u, const auto& v) {
567 return std::tie(u.first, *u.second) ==
568 std::tie(v.first, *v.second);
569 });
570 case Value::Type::LIST:
571 return lhs.list_ == rhs.list_;
572 }
573
574 NOTREACHED();
575 return false;
576}
577
578bool operator!=(const Value& lhs, const Value& rhs) {
579 return !(lhs == rhs);
580}
581
582bool operator<(const Value& lhs, const Value& rhs) {
583 if (lhs.type_ != rhs.type_)
584 return lhs.type_ < rhs.type_;
585
586 switch (lhs.type_) {
587 case Value::Type::NONE:
588 return false;
589 case Value::Type::BOOLEAN:
590 return lhs.bool_value_ < rhs.bool_value_;
591 case Value::Type::INTEGER:
592 return lhs.int_value_ < rhs.int_value_;
593 case Value::Type::DOUBLE:
594 return lhs.double_value_ < rhs.double_value_;
595 case Value::Type::STRING:
596 return lhs.string_value_ < rhs.string_value_;
597 case Value::Type::BINARY:
598 return lhs.binary_value_ < rhs.binary_value_;
599 // TODO(crbug.com/646113): Clean this up when DictionaryValue and ListValue
600 // are completely inlined.
601 case Value::Type::DICTIONARY:
602 return std::lexicographical_compare(
603 std::begin(lhs.dict_), std::end(lhs.dict_), std::begin(rhs.dict_),
604 std::end(rhs.dict_),
605 [](const Value::DictStorage::value_type& u,
606 const Value::DictStorage::value_type& v) {
607 return std::tie(u.first, *u.second) < std::tie(v.first, *v.second);
608 });
609 case Value::Type::LIST:
610 return lhs.list_ < rhs.list_;
611 }
612
613 NOTREACHED();
614 return false;
615}
616
617bool operator>(const Value& lhs, const Value& rhs) {
618 return rhs < lhs;
619}
620
621bool operator<=(const Value& lhs, const Value& rhs) {
622 return !(rhs < lhs);
623}
624
625bool operator>=(const Value& lhs, const Value& rhs) {
626 return !(lhs < rhs);
627}
628
629bool Value::Equals(const Value* other) const {
630 DCHECK(other);
631 return *this == *other;
632}
633
Scott Graham66962112018-06-08 12:42:08 -0700634void Value::InternalMoveConstructFrom(Value&& that) {
635 type_ = that.type_;
636
637 switch (type_) {
638 case Type::NONE:
639 return;
640 case Type::BOOLEAN:
641 bool_value_ = that.bool_value_;
642 return;
643 case Type::INTEGER:
644 int_value_ = that.int_value_;
645 return;
646 case Type::DOUBLE:
647 double_value_ = that.double_value_;
648 return;
649 case Type::STRING:
650 new (&string_value_) std::string(std::move(that.string_value_));
651 return;
652 case Type::BINARY:
653 new (&binary_value_) BlobStorage(std::move(that.binary_value_));
654 return;
655 case Type::DICTIONARY:
656 new (&dict_) DictStorage(std::move(that.dict_));
657 return;
658 case Type::LIST:
659 new (&list_) ListStorage(std::move(that.list_));
660 return;
661 }
662}
663
664void Value::InternalCleanup() {
665 switch (type_) {
666 case Type::NONE:
667 case Type::BOOLEAN:
668 case Type::INTEGER:
669 case Type::DOUBLE:
670 // Nothing to do
671 return;
672
673 case Type::STRING:
674 string_value_.~basic_string();
675 return;
676 case Type::BINARY:
677 binary_value_.~BlobStorage();
678 return;
679 case Type::DICTIONARY:
680 dict_.~DictStorage();
681 return;
682 case Type::LIST:
683 list_.~ListStorage();
684 return;
685 }
686}
687
688///////////////////// DictionaryValue ////////////////////
689
690// static
691std::unique_ptr<DictionaryValue> DictionaryValue::From(
692 std::unique_ptr<Value> value) {
693 DictionaryValue* out;
694 if (value && value->GetAsDictionary(&out)) {
695 ignore_result(value.release());
696 return WrapUnique(out);
697 }
698 return nullptr;
699}
700
701DictionaryValue::DictionaryValue() : Value(Type::DICTIONARY) {}
702DictionaryValue::DictionaryValue(const DictStorage& in_dict) : Value(in_dict) {}
703DictionaryValue::DictionaryValue(DictStorage&& in_dict) noexcept
704 : Value(std::move(in_dict)) {}
705
706bool DictionaryValue::HasKey(StringPiece key) const {
707 DCHECK(IsStringUTF8(key));
708 auto current_entry = dict_.find(key);
709 DCHECK((current_entry == dict_.end()) || current_entry->second);
710 return current_entry != dict_.end();
711}
712
713void DictionaryValue::Clear() {
714 dict_.clear();
715}
716
717Value* DictionaryValue::Set(StringPiece path, std::unique_ptr<Value> in_value) {
718 DCHECK(IsStringUTF8(path));
719 DCHECK(in_value);
720
721 StringPiece current_path(path);
722 Value* current_dictionary = this;
723 for (size_t delimiter_position = current_path.find('.');
724 delimiter_position != StringPiece::npos;
725 delimiter_position = current_path.find('.')) {
726 // Assume that we're indexing into a dictionary.
727 StringPiece key = current_path.substr(0, delimiter_position);
728 Value* child_dictionary =
729 current_dictionary->FindKeyOfType(key, Type::DICTIONARY);
730 if (!child_dictionary) {
731 child_dictionary =
732 current_dictionary->SetKey(key, Value(Type::DICTIONARY));
733 }
734
735 current_dictionary = child_dictionary;
736 current_path = current_path.substr(delimiter_position + 1);
737 }
738
739 return static_cast<DictionaryValue*>(current_dictionary)
740 ->SetWithoutPathExpansion(current_path, std::move(in_value));
741}
742
743Value* DictionaryValue::SetBoolean(StringPiece path, bool in_value) {
744 return Set(path, std::make_unique<Value>(in_value));
745}
746
747Value* DictionaryValue::SetInteger(StringPiece path, int in_value) {
748 return Set(path, std::make_unique<Value>(in_value));
749}
750
751Value* DictionaryValue::SetDouble(StringPiece path, double in_value) {
752 return Set(path, std::make_unique<Value>(in_value));
753}
754
755Value* DictionaryValue::SetString(StringPiece path, StringPiece in_value) {
756 return Set(path, std::make_unique<Value>(in_value));
757}
758
759Value* DictionaryValue::SetString(StringPiece path, const string16& in_value) {
760 return Set(path, std::make_unique<Value>(in_value));
761}
762
763DictionaryValue* DictionaryValue::SetDictionary(
764 StringPiece path,
765 std::unique_ptr<DictionaryValue> in_value) {
766 return static_cast<DictionaryValue*>(Set(path, std::move(in_value)));
767}
768
769ListValue* DictionaryValue::SetList(StringPiece path,
770 std::unique_ptr<ListValue> in_value) {
771 return static_cast<ListValue*>(Set(path, std::move(in_value)));
772}
773
774Value* DictionaryValue::SetWithoutPathExpansion(
775 StringPiece key,
776 std::unique_ptr<Value> in_value) {
777 // NOTE: We can't use |insert_or_assign| here, as only |try_emplace| does
778 // an explicit conversion from StringPiece to std::string if necessary.
779 auto result = dict_.try_emplace(key, std::move(in_value));
780 if (!result.second) {
781 // in_value is guaranteed to be still intact at this point.
782 result.first->second = std::move(in_value);
783 }
784 return result.first->second.get();
785}
786
787bool DictionaryValue::Get(StringPiece path,
788 const Value** out_value) const {
789 DCHECK(IsStringUTF8(path));
790 StringPiece current_path(path);
791 const DictionaryValue* current_dictionary = this;
792 for (size_t delimiter_position = current_path.find('.');
793 delimiter_position != std::string::npos;
794 delimiter_position = current_path.find('.')) {
795 const DictionaryValue* child_dictionary = nullptr;
796 if (!current_dictionary->GetDictionaryWithoutPathExpansion(
797 current_path.substr(0, delimiter_position), &child_dictionary)) {
798 return false;
799 }
800
801 current_dictionary = child_dictionary;
802 current_path = current_path.substr(delimiter_position + 1);
803 }
804
805 return current_dictionary->GetWithoutPathExpansion(current_path, out_value);
806}
807
808bool DictionaryValue::Get(StringPiece path, Value** out_value) {
809 return static_cast<const DictionaryValue&>(*this).Get(
810 path,
811 const_cast<const Value**>(out_value));
812}
813
814bool DictionaryValue::GetBoolean(StringPiece path, bool* bool_value) const {
815 const Value* value;
816 if (!Get(path, &value))
817 return false;
818
819 return value->GetAsBoolean(bool_value);
820}
821
822bool DictionaryValue::GetInteger(StringPiece path, int* out_value) const {
823 const Value* value;
824 if (!Get(path, &value))
825 return false;
826
827 return value->GetAsInteger(out_value);
828}
829
830bool DictionaryValue::GetDouble(StringPiece path, double* out_value) const {
831 const Value* value;
832 if (!Get(path, &value))
833 return false;
834
835 return value->GetAsDouble(out_value);
836}
837
838bool DictionaryValue::GetString(StringPiece path,
839 std::string* out_value) const {
840 const Value* value;
841 if (!Get(path, &value))
842 return false;
843
844 return value->GetAsString(out_value);
845}
846
847bool DictionaryValue::GetString(StringPiece path, string16* out_value) const {
848 const Value* value;
849 if (!Get(path, &value))
850 return false;
851
852 return value->GetAsString(out_value);
853}
854
855bool DictionaryValue::GetStringASCII(StringPiece path,
856 std::string* out_value) const {
857 std::string out;
858 if (!GetString(path, &out))
859 return false;
860
861 if (!IsStringASCII(out)) {
862 NOTREACHED();
863 return false;
864 }
865
866 out_value->assign(out);
867 return true;
868}
869
870bool DictionaryValue::GetBinary(StringPiece path,
871 const Value** out_value) const {
872 const Value* value;
873 bool result = Get(path, &value);
874 if (!result || !value->is_blob())
875 return false;
876
877 if (out_value)
878 *out_value = value;
879
880 return true;
881}
882
883bool DictionaryValue::GetBinary(StringPiece path, Value** out_value) {
884 return static_cast<const DictionaryValue&>(*this).GetBinary(
885 path, const_cast<const Value**>(out_value));
886}
887
888bool DictionaryValue::GetDictionary(StringPiece path,
889 const DictionaryValue** out_value) const {
890 const Value* value;
891 bool result = Get(path, &value);
892 if (!result || !value->is_dict())
893 return false;
894
895 if (out_value)
896 *out_value = static_cast<const DictionaryValue*>(value);
897
898 return true;
899}
900
901bool DictionaryValue::GetDictionary(StringPiece path,
902 DictionaryValue** out_value) {
903 return static_cast<const DictionaryValue&>(*this).GetDictionary(
904 path,
905 const_cast<const DictionaryValue**>(out_value));
906}
907
908bool DictionaryValue::GetList(StringPiece path,
909 const ListValue** out_value) const {
910 const Value* value;
911 bool result = Get(path, &value);
912 if (!result || !value->is_list())
913 return false;
914
915 if (out_value)
916 *out_value = static_cast<const ListValue*>(value);
917
918 return true;
919}
920
921bool DictionaryValue::GetList(StringPiece path, ListValue** out_value) {
922 return static_cast<const DictionaryValue&>(*this).GetList(
923 path,
924 const_cast<const ListValue**>(out_value));
925}
926
927bool DictionaryValue::GetWithoutPathExpansion(StringPiece key,
928 const Value** out_value) const {
929 DCHECK(IsStringUTF8(key));
930 auto entry_iterator = dict_.find(key);
931 if (entry_iterator == dict_.end())
932 return false;
933
934 if (out_value)
935 *out_value = entry_iterator->second.get();
936 return true;
937}
938
939bool DictionaryValue::GetWithoutPathExpansion(StringPiece key,
940 Value** out_value) {
941 return static_cast<const DictionaryValue&>(*this).GetWithoutPathExpansion(
942 key,
943 const_cast<const Value**>(out_value));
944}
945
946bool DictionaryValue::GetBooleanWithoutPathExpansion(StringPiece key,
947 bool* out_value) const {
948 const Value* value;
949 if (!GetWithoutPathExpansion(key, &value))
950 return false;
951
952 return value->GetAsBoolean(out_value);
953}
954
955bool DictionaryValue::GetIntegerWithoutPathExpansion(StringPiece key,
956 int* out_value) const {
957 const Value* value;
958 if (!GetWithoutPathExpansion(key, &value))
959 return false;
960
961 return value->GetAsInteger(out_value);
962}
963
964bool DictionaryValue::GetDoubleWithoutPathExpansion(StringPiece key,
965 double* out_value) const {
966 const Value* value;
967 if (!GetWithoutPathExpansion(key, &value))
968 return false;
969
970 return value->GetAsDouble(out_value);
971}
972
973bool DictionaryValue::GetStringWithoutPathExpansion(
974 StringPiece key,
975 std::string* out_value) const {
976 const Value* value;
977 if (!GetWithoutPathExpansion(key, &value))
978 return false;
979
980 return value->GetAsString(out_value);
981}
982
983bool DictionaryValue::GetStringWithoutPathExpansion(StringPiece key,
984 string16* out_value) const {
985 const Value* value;
986 if (!GetWithoutPathExpansion(key, &value))
987 return false;
988
989 return value->GetAsString(out_value);
990}
991
992bool DictionaryValue::GetDictionaryWithoutPathExpansion(
993 StringPiece key,
994 const DictionaryValue** out_value) const {
995 const Value* value;
996 bool result = GetWithoutPathExpansion(key, &value);
997 if (!result || !value->is_dict())
998 return false;
999
1000 if (out_value)
1001 *out_value = static_cast<const DictionaryValue*>(value);
1002
1003 return true;
1004}
1005
1006bool DictionaryValue::GetDictionaryWithoutPathExpansion(
1007 StringPiece key,
1008 DictionaryValue** out_value) {
1009 const DictionaryValue& const_this =
1010 static_cast<const DictionaryValue&>(*this);
1011 return const_this.GetDictionaryWithoutPathExpansion(
1012 key,
1013 const_cast<const DictionaryValue**>(out_value));
1014}
1015
1016bool DictionaryValue::GetListWithoutPathExpansion(
1017 StringPiece key,
1018 const ListValue** out_value) const {
1019 const Value* value;
1020 bool result = GetWithoutPathExpansion(key, &value);
1021 if (!result || !value->is_list())
1022 return false;
1023
1024 if (out_value)
1025 *out_value = static_cast<const ListValue*>(value);
1026
1027 return true;
1028}
1029
1030bool DictionaryValue::GetListWithoutPathExpansion(StringPiece key,
1031 ListValue** out_value) {
1032 return
1033 static_cast<const DictionaryValue&>(*this).GetListWithoutPathExpansion(
1034 key,
1035 const_cast<const ListValue**>(out_value));
1036}
1037
1038bool DictionaryValue::Remove(StringPiece path,
1039 std::unique_ptr<Value>* out_value) {
1040 DCHECK(IsStringUTF8(path));
1041 StringPiece current_path(path);
1042 DictionaryValue* current_dictionary = this;
1043 size_t delimiter_position = current_path.rfind('.');
1044 if (delimiter_position != StringPiece::npos) {
1045 if (!GetDictionary(current_path.substr(0, delimiter_position),
1046 &current_dictionary))
1047 return false;
1048 current_path = current_path.substr(delimiter_position + 1);
1049 }
1050
1051 return current_dictionary->RemoveWithoutPathExpansion(current_path,
1052 out_value);
1053}
1054
1055bool DictionaryValue::RemoveWithoutPathExpansion(
1056 StringPiece key,
1057 std::unique_ptr<Value>* out_value) {
1058 DCHECK(IsStringUTF8(key));
1059 auto entry_iterator = dict_.find(key);
1060 if (entry_iterator == dict_.end())
1061 return false;
1062
1063 if (out_value)
1064 *out_value = std::move(entry_iterator->second);
1065 dict_.erase(entry_iterator);
1066 return true;
1067}
1068
1069bool DictionaryValue::RemovePath(StringPiece path,
1070 std::unique_ptr<Value>* out_value) {
1071 bool result = false;
1072 size_t delimiter_position = path.find('.');
1073
1074 if (delimiter_position == std::string::npos)
1075 return RemoveWithoutPathExpansion(path, out_value);
1076
1077 StringPiece subdict_path = path.substr(0, delimiter_position);
1078 DictionaryValue* subdict = nullptr;
1079 if (!GetDictionary(subdict_path, &subdict))
1080 return false;
1081 result = subdict->RemovePath(path.substr(delimiter_position + 1),
1082 out_value);
1083 if (result && subdict->empty())
1084 RemoveWithoutPathExpansion(subdict_path, nullptr);
1085
1086 return result;
1087}
1088
1089std::unique_ptr<DictionaryValue> DictionaryValue::DeepCopyWithoutEmptyChildren()
1090 const {
1091 std::unique_ptr<DictionaryValue> copy =
1092 CopyDictionaryWithoutEmptyChildren(*this);
1093 if (!copy)
1094 copy = std::make_unique<DictionaryValue>();
1095 return copy;
1096}
1097
1098void DictionaryValue::MergeDictionary(const DictionaryValue* dictionary) {
1099 CHECK(dictionary->is_dict());
1100 for (DictionaryValue::Iterator it(*dictionary); !it.IsAtEnd(); it.Advance()) {
1101 const Value* merge_value = &it.value();
1102 // Check whether we have to merge dictionaries.
1103 if (merge_value->is_dict()) {
1104 DictionaryValue* sub_dict;
1105 if (GetDictionaryWithoutPathExpansion(it.key(), &sub_dict)) {
1106 sub_dict->MergeDictionary(
1107 static_cast<const DictionaryValue*>(merge_value));
1108 continue;
1109 }
1110 }
1111 // All other cases: Make a copy and hook it up.
1112 SetKey(it.key(), merge_value->Clone());
1113 }
1114}
1115
1116void DictionaryValue::Swap(DictionaryValue* other) {
1117 CHECK(other->is_dict());
1118 dict_.swap(other->dict_);
1119}
1120
1121DictionaryValue::Iterator::Iterator(const DictionaryValue& target)
1122 : target_(target), it_(target.dict_.begin()) {}
1123
1124DictionaryValue::Iterator::Iterator(const Iterator& other) = default;
1125
1126DictionaryValue::Iterator::~Iterator() = default;
1127
1128DictionaryValue* DictionaryValue::DeepCopy() const {
1129 return new DictionaryValue(dict_);
1130}
1131
1132std::unique_ptr<DictionaryValue> DictionaryValue::CreateDeepCopy() const {
1133 return std::make_unique<DictionaryValue>(dict_);
1134}
1135
1136///////////////////// ListValue ////////////////////
1137
1138// static
1139std::unique_ptr<ListValue> ListValue::From(std::unique_ptr<Value> value) {
1140 ListValue* out;
1141 if (value && value->GetAsList(&out)) {
1142 ignore_result(value.release());
1143 return WrapUnique(out);
1144 }
1145 return nullptr;
1146}
1147
1148ListValue::ListValue() : Value(Type::LIST) {}
1149ListValue::ListValue(const ListStorage& in_list) : Value(in_list) {}
1150ListValue::ListValue(ListStorage&& in_list) noexcept
1151 : Value(std::move(in_list)) {}
1152
1153void ListValue::Clear() {
1154 list_.clear();
1155}
1156
1157void ListValue::Reserve(size_t n) {
1158 list_.reserve(n);
1159}
1160
1161bool ListValue::Set(size_t index, std::unique_ptr<Value> in_value) {
1162 if (!in_value)
1163 return false;
1164
1165 if (index >= list_.size())
1166 list_.resize(index + 1);
1167
1168 list_[index] = std::move(*in_value);
1169 return true;
1170}
1171
1172bool ListValue::Get(size_t index, const Value** out_value) const {
1173 if (index >= list_.size())
1174 return false;
1175
1176 if (out_value)
1177 *out_value = &list_[index];
1178
1179 return true;
1180}
1181
1182bool ListValue::Get(size_t index, Value** out_value) {
1183 return static_cast<const ListValue&>(*this).Get(
1184 index,
1185 const_cast<const Value**>(out_value));
1186}
1187
1188bool ListValue::GetBoolean(size_t index, bool* bool_value) const {
1189 const Value* value;
1190 if (!Get(index, &value))
1191 return false;
1192
1193 return value->GetAsBoolean(bool_value);
1194}
1195
1196bool ListValue::GetInteger(size_t index, int* out_value) const {
1197 const Value* value;
1198 if (!Get(index, &value))
1199 return false;
1200
1201 return value->GetAsInteger(out_value);
1202}
1203
1204bool ListValue::GetDouble(size_t index, double* out_value) const {
1205 const Value* value;
1206 if (!Get(index, &value))
1207 return false;
1208
1209 return value->GetAsDouble(out_value);
1210}
1211
1212bool ListValue::GetString(size_t index, std::string* out_value) const {
1213 const Value* value;
1214 if (!Get(index, &value))
1215 return false;
1216
1217 return value->GetAsString(out_value);
1218}
1219
1220bool ListValue::GetString(size_t index, string16* out_value) const {
1221 const Value* value;
1222 if (!Get(index, &value))
1223 return false;
1224
1225 return value->GetAsString(out_value);
1226}
1227
1228bool ListValue::GetDictionary(size_t index,
1229 const DictionaryValue** out_value) const {
1230 const Value* value;
1231 bool result = Get(index, &value);
1232 if (!result || !value->is_dict())
1233 return false;
1234
1235 if (out_value)
1236 *out_value = static_cast<const DictionaryValue*>(value);
1237
1238 return true;
1239}
1240
1241bool ListValue::GetDictionary(size_t index, DictionaryValue** out_value) {
1242 return static_cast<const ListValue&>(*this).GetDictionary(
1243 index,
1244 const_cast<const DictionaryValue**>(out_value));
1245}
1246
1247bool ListValue::GetList(size_t index, const ListValue** out_value) const {
1248 const Value* value;
1249 bool result = Get(index, &value);
1250 if (!result || !value->is_list())
1251 return false;
1252
1253 if (out_value)
1254 *out_value = static_cast<const ListValue*>(value);
1255
1256 return true;
1257}
1258
1259bool ListValue::GetList(size_t index, ListValue** out_value) {
1260 return static_cast<const ListValue&>(*this).GetList(
1261 index,
1262 const_cast<const ListValue**>(out_value));
1263}
1264
1265bool ListValue::Remove(size_t index, std::unique_ptr<Value>* out_value) {
1266 if (index >= list_.size())
1267 return false;
1268
1269 if (out_value)
1270 *out_value = std::make_unique<Value>(std::move(list_[index]));
1271
1272 list_.erase(list_.begin() + index);
1273 return true;
1274}
1275
1276bool ListValue::Remove(const Value& value, size_t* index) {
1277 auto it = std::find(list_.begin(), list_.end(), value);
1278
1279 if (it == list_.end())
1280 return false;
1281
1282 if (index)
1283 *index = std::distance(list_.begin(), it);
1284
1285 list_.erase(it);
1286 return true;
1287}
1288
1289ListValue::iterator ListValue::Erase(iterator iter,
1290 std::unique_ptr<Value>* out_value) {
1291 if (out_value)
1292 *out_value = std::make_unique<Value>(std::move(*iter));
1293
1294 return list_.erase(iter);
1295}
1296
1297void ListValue::Append(std::unique_ptr<Value> in_value) {
1298 list_.push_back(std::move(*in_value));
1299}
1300
1301void ListValue::AppendBoolean(bool in_value) {
1302 list_.emplace_back(in_value);
1303}
1304
1305void ListValue::AppendInteger(int in_value) {
1306 list_.emplace_back(in_value);
1307}
1308
1309void ListValue::AppendDouble(double in_value) {
1310 list_.emplace_back(in_value);
1311}
1312
1313void ListValue::AppendString(StringPiece in_value) {
1314 list_.emplace_back(in_value);
1315}
1316
1317void ListValue::AppendString(const string16& in_value) {
1318 list_.emplace_back(in_value);
1319}
1320
1321void ListValue::AppendStrings(const std::vector<std::string>& in_values) {
1322 list_.reserve(list_.size() + in_values.size());
1323 for (const auto& in_value : in_values)
1324 list_.emplace_back(in_value);
1325}
1326
1327void ListValue::AppendStrings(const std::vector<string16>& in_values) {
1328 list_.reserve(list_.size() + in_values.size());
1329 for (const auto& in_value : in_values)
1330 list_.emplace_back(in_value);
1331}
1332
1333bool ListValue::AppendIfNotPresent(std::unique_ptr<Value> in_value) {
1334 DCHECK(in_value);
1335 if (ContainsValue(list_, *in_value))
1336 return false;
1337
1338 list_.push_back(std::move(*in_value));
1339 return true;
1340}
1341
1342bool ListValue::Insert(size_t index, std::unique_ptr<Value> in_value) {
1343 DCHECK(in_value);
1344 if (index > list_.size())
1345 return false;
1346
1347 list_.insert(list_.begin() + index, std::move(*in_value));
1348 return true;
1349}
1350
1351ListValue::const_iterator ListValue::Find(const Value& value) const {
1352 return std::find(list_.begin(), list_.end(), value);
1353}
1354
1355void ListValue::Swap(ListValue* other) {
1356 CHECK(other->is_list());
1357 list_.swap(other->list_);
1358}
1359
1360ListValue* ListValue::DeepCopy() const {
1361 return new ListValue(list_);
1362}
1363
1364std::unique_ptr<ListValue> ListValue::CreateDeepCopy() const {
1365 return std::make_unique<ListValue>(list_);
1366}
1367
1368ValueSerializer::~ValueSerializer() = default;
1369
1370ValueDeserializer::~ValueDeserializer() = default;
1371
1372std::ostream& operator<<(std::ostream& out, const Value& value) {
1373 std::string json;
1374 JSONWriter::WriteWithOptions(value, JSONWriter::OPTIONS_PRETTY_PRINT, &json);
1375 return out << json;
1376}
1377
1378std::ostream& operator<<(std::ostream& out, const Value::Type& type) {
1379 if (static_cast<int>(type) < 0 ||
1380 static_cast<size_t>(type) >= arraysize(kTypeNames))
1381 return out << "Invalid Type (index = " << static_cast<int>(type) << ")";
1382 return out << Value::GetTypeName(type);
1383}
1384
1385} // namespace base