1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/browsing_topics/topic_and_domains.h"
7 #include "base/check_op.h"
8 #include "base/json/values_util.h"
11 namespace browsing_topics {
15 const char kTopicNameKey[] = "topic";
16 const char kHashedDomainsNameKey[] = "hashed_domains";
20 TopicAndDomains::TopicAndDomains() = default;
22 TopicAndDomains::TopicAndDomains(Topic topic,
23 std::set<HashedDomain> hashed_domains)
24 : topic_(std::move(topic)), hashed_domains_(std::move(hashed_domains)) {}
26 TopicAndDomains::TopicAndDomains(TopicAndDomains&& other) = default;
28 TopicAndDomains& TopicAndDomains::operator=(TopicAndDomains&& other) = default;
30 TopicAndDomains::~TopicAndDomains() = default;
33 TopicAndDomains TopicAndDomains::FromDictValue(
34 const base::Value::Dict& dict_value) {
36 absl::optional<int> topic_value = dict_value.FindInt(kTopicNameKey);
38 topic = Topic(*topic_value);
40 std::set<HashedDomain> hashed_domains;
41 const base::Value::List* hashed_domains_value =
42 dict_value.FindList(kHashedDomainsNameKey);
43 if (hashed_domains_value) {
44 for (const base::Value& hashed_domain_value : *hashed_domains_value) {
45 absl::optional<int64_t> hashed_domain_int64_value =
46 base::ValueToInt64(hashed_domain_value);
47 if (!hashed_domain_int64_value)
48 return TopicAndDomains();
50 hashed_domains.insert(HashedDomain(hashed_domain_int64_value.value()));
54 return TopicAndDomains(topic, std::move(hashed_domains));
57 base::Value::Dict TopicAndDomains::ToDictValue() const {
58 base::Value::List hashed_domains_list;
59 for (const HashedDomain& hashed_domain : hashed_domains_) {
60 hashed_domains_list.Append(base::Int64ToValue(hashed_domain.value()));
63 base::Value::Dict result_dict;
64 result_dict.Set(kTopicNameKey, topic_.value());
65 result_dict.Set(kHashedDomainsNameKey, std::move(hashed_domains_list));
69 void TopicAndDomains::ClearDomain(const HashedDomain& domain) {
70 hashed_domains_.erase(domain);
73 } // namespace browsing_topics