1 // Copyright 2014 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 "components/search_engines/search_host_to_urls_map.h"
7 #include "base/memory/scoped_ptr.h"
8 #include "components/search_engines/template_url.h"
10 SearchHostToURLsMap::SearchHostToURLsMap()
11 : initialized_(false) {
14 SearchHostToURLsMap::~SearchHostToURLsMap() {
17 void SearchHostToURLsMap::Init(
18 const TemplateURLService::TemplateURLVector
& template_urls
,
19 const SearchTermsData
& search_terms_data
) {
20 DCHECK(!initialized_
);
21 initialized_
= true; // Set here so Add doesn't assert.
22 Add(template_urls
, search_terms_data
);
25 void SearchHostToURLsMap::Add(TemplateURL
* template_url
,
26 const SearchTermsData
& search_terms_data
) {
30 const GURL
url(template_url
->GenerateSearchURL(search_terms_data
));
31 if (!url
.is_valid() || !url
.has_host())
34 host_to_urls_map_
[url
.host()].insert(template_url
);
37 void SearchHostToURLsMap::Remove(TemplateURL
* template_url
) {
41 for (HostToURLsMap::iterator i
= host_to_urls_map_
.begin();
42 i
!= host_to_urls_map_
.end(); ++i
) {
43 TemplateURLSet::iterator url_set_iterator
= i
->second
.find(template_url
);
44 if (url_set_iterator
!= i
->second
.end()) {
45 i
->second
.erase(url_set_iterator
);
46 if (i
->second
.empty())
47 host_to_urls_map_
.erase(i
);
48 // A given TemplateURL only occurs once in the map. As soon as we find the
55 TemplateURL
* SearchHostToURLsMap::GetTemplateURLForHost(
56 const std::string
& host
) {
59 HostToURLsMap::const_iterator iter
= host_to_urls_map_
.find(host
);
60 if (iter
== host_to_urls_map_
.end() || iter
->second
.empty())
62 return *(iter
->second
.begin()); // Return the 1st element.
65 SearchHostToURLsMap::TemplateURLSet
* SearchHostToURLsMap::GetURLsForHost(
66 const std::string
& host
) {
69 HostToURLsMap::iterator urls_for_host
= host_to_urls_map_
.find(host
);
70 if (urls_for_host
== host_to_urls_map_
.end() || urls_for_host
->second
.empty())
72 return &urls_for_host
->second
;
75 void SearchHostToURLsMap::Add(
76 const TemplateURLService::TemplateURLVector
& template_urls
,
77 const SearchTermsData
& search_terms_data
) {
78 for (TemplateURLService::TemplateURLVector::const_iterator
i(
79 template_urls
.begin()); i
!= template_urls
.end(); ++i
)
80 Add(*i
, search_terms_data
);