1 /*
2  * Copyright 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <cstddef>
18 #include <map>
19 #include <mutex>
20 #include <unordered_map>
21 #include <vector>
22 
23 template <typename T>
24 class SyncMapCount {
25  public:
26   struct Item {
27     T item;
28     size_t count;
29   };
30 
31  private:
32   std::map<const T, std::size_t> map_;
33   size_t max_size_{SIZE_MAX};
34   mutable std::mutex mutex_;
35 
Vectorize()36   std::vector<Item> Vectorize() const {
37     std::vector<Item> vec;
38     for (auto& it : this->Get()) {
39       vec.push_back(Item{it.first, it.second});
40     }
41     return vec;
42   }
43 
GetSorted(std::function<bool (const Item & a,const Item & b)> sort_func)44   std::vector<Item> GetSorted(std::function<bool(const Item& a, const Item& b)> sort_func) const {
45     std::vector<Item> vec = Vectorize();
46     sort(vec.begin(), vec.end(), [=](const Item& a, const Item& b) -> bool { return sort_func(a, b); });
47     return vec;
48   }
49 
50  public:
SyncMapCount()51   SyncMapCount() : max_size_(SIZE_MAX) {}
SyncMapCount(size_t max_size)52   explicit SyncMapCount(size_t max_size) : max_size_(max_size) {}
53   ~SyncMapCount() = default;
54 
Put(const T item)55   void Put(const T item) {
56     std::unique_lock<std::mutex> lock(mutex_);
57     if (map_.size() == max_size_) return;
58     (map_.count(item) > 0) ? map_[item] += 1 : map_[item] = 1;
59   }
60 
Get()61   std::map<const T, std::size_t> Get() const {
62     std::unique_lock<std::mutex> lock(mutex_);
63     return map_;
64   }
65 
Size()66   std::size_t Size() const {
67     std::unique_lock<std::mutex> lock(mutex_);
68     return map_.size();
69   }
70 
Clear()71   void Clear() {
72     std::unique_lock<std::mutex> lock(mutex_);
73     map_.clear();
74   }
75 
GetSortedHighToLow()76   std::vector<Item> GetSortedHighToLow() const {
77     return GetSorted([](const Item& a, const Item& b) -> bool { return a.count > b.count; });
78   }
79 
GetSortedLowToHigh()80   std::vector<Item> GetSortedLowToHigh() const {
81     return GetSorted([](const Item& a, const Item& b) -> bool { return a.count < b.count; });
82   }
83 };
84