typed_count_sorter.cc 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2016 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. #include "components/bookmarks/browser/typed_count_sorter.h"
  5. #include "components/bookmarks/browser/bookmark_client.h"
  6. namespace bookmarks {
  7. using UrlTypedCountMap = BookmarkClient::UrlTypedCountMap;
  8. namespace {
  9. using UrlNodeMap = std::map<const GURL*, const TitledUrlNode*>;
  10. using UrlTypedCountPair = std::pair<const GURL*, int>;
  11. using UrlTypedCountPairs = std::vector<UrlTypedCountPair>;
  12. // Sort functor for UrlTypedCountPairs. We sort in decreasing order of typed
  13. // count so that the best matches will always be added to the results.
  14. struct UrlTypedCountPairSortFunctor {
  15. bool operator()(const UrlTypedCountPair& a,
  16. const UrlTypedCountPair& b) const {
  17. return a.second > b.second;
  18. }
  19. };
  20. // Extract the GURL stored in an UrlTypedCountPair and use it to look up the
  21. // corresponding TitledUrlNode.
  22. class UrlTypedCountPairNodeLookupFunctor {
  23. public:
  24. UrlTypedCountPairNodeLookupFunctor(UrlNodeMap& url_node_map)
  25. : url_node_map_(url_node_map) {
  26. }
  27. const TitledUrlNode* operator()(const UrlTypedCountPair& pair) const {
  28. return url_node_map_[pair.first];
  29. }
  30. private:
  31. UrlNodeMap& url_node_map_;
  32. };
  33. } // namespace
  34. TypedCountSorter::TypedCountSorter(BookmarkClient* client)
  35. : client_(client) {
  36. DCHECK(client_);
  37. }
  38. TypedCountSorter::~TypedCountSorter() {}
  39. void TypedCountSorter::SortMatches(const TitledUrlNodeSet& matches,
  40. TitledUrlNodes* sorted_nodes) const {
  41. sorted_nodes->reserve(matches.size());
  42. if (client_->SupportsTypedCountForUrls()) {
  43. UrlNodeMap url_node_map;
  44. UrlTypedCountMap url_typed_count_map;
  45. for (auto* node : matches) {
  46. const GURL& url = node->GetTitledUrlNodeUrl();
  47. url_node_map.insert(std::make_pair(&url, node));
  48. url_typed_count_map.insert(std::make_pair(&url, 0));
  49. }
  50. client_->GetTypedCountForUrls(&url_typed_count_map);
  51. UrlTypedCountPairs url_typed_counts;
  52. std::copy(url_typed_count_map.begin(),
  53. url_typed_count_map.end(),
  54. std::back_inserter(url_typed_counts));
  55. std::sort(url_typed_counts.begin(),
  56. url_typed_counts.end(),
  57. UrlTypedCountPairSortFunctor());
  58. std::transform(url_typed_counts.begin(),
  59. url_typed_counts.end(),
  60. std::back_inserter(*sorted_nodes),
  61. UrlTypedCountPairNodeLookupFunctor(url_node_map));
  62. } else {
  63. sorted_nodes->insert(sorted_nodes->end(), matches.begin(), matches.end());
  64. }
  65. }
  66. } // namespace bookmarks