1 // Copyright 2014 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/search_engines/search_host_to_urls_map.h"
9 #include "base/ranges/algorithm.h"
10 #include "components/search_engines/template_url.h"
12 SearchHostToURLsMap::SearchHostToURLsMap()
13 : initialized_(false) {
16 SearchHostToURLsMap::~SearchHostToURLsMap() {
19 void SearchHostToURLsMap::Init(
20 const TemplateURL::OwnedTemplateURLVector& template_urls,
21 const SearchTermsData& search_terms_data) {
22 DCHECK(!initialized_);
23 initialized_ = true; // Set here so Add doesn't assert.
24 Add(template_urls, search_terms_data);
27 void SearchHostToURLsMap::Add(TemplateURL* template_url,
28 const SearchTermsData& search_terms_data) {
31 DCHECK_NE(TemplateURL::OMNIBOX_API_EXTENSION, template_url->type());
33 const GURL url(template_url->GenerateSearchURL(search_terms_data));
34 if (!url.is_valid() || !url.has_host())
37 host_to_urls_map_[url.host()].insert(template_url);
40 void SearchHostToURLsMap::Remove(const TemplateURL* template_url) {
43 DCHECK_NE(TemplateURL::OMNIBOX_API_EXTENSION, template_url->type());
45 // A given TemplateURL only occurs once in the map.
46 auto set_with_url = base::ranges::find_if(
48 [&](std::pair<const std::string, TemplateURLSet>& entry) {
49 return entry.second.erase(template_url);
52 if (set_with_url != host_to_urls_map_.end() && set_with_url->second.empty())
53 host_to_urls_map_.erase(set_with_url);
56 TemplateURL* SearchHostToURLsMap::GetTemplateURLForHost(
57 base::StringPiece host) {
60 HostToURLsMap::const_iterator iter = host_to_urls_map_.find(host);
61 if (iter == host_to_urls_map_.end() || iter->second.empty())
64 // Because we have to happily tolerate duplicates in TemplateURLService now,
65 /// return the best TemplateURL for `host`, just like
66 // `GetTemplateURLForKeyword` returns the best TemplateURL for a keyword.
67 return *std::min_element(
68 iter->second.begin(), iter->second.end(),
69 [](const auto& a, const auto& b) {
70 return a->IsBetterThanEngineWithConflictingKeyword(b);
74 SearchHostToURLsMap::TemplateURLSet* SearchHostToURLsMap::GetURLsForHost(
75 base::StringPiece host) {
78 auto urls_for_host = host_to_urls_map_.find(host);
79 if (urls_for_host == host_to_urls_map_.end() || urls_for_host->second.empty())
81 return &urls_for_host->second;
84 void SearchHostToURLsMap::Add(
85 const TemplateURL::OwnedTemplateURLVector& template_urls,
86 const SearchTermsData& search_terms_data) {
87 for (const auto& turl : template_urls)
88 Add(turl.get(), search_terms_data);