Electroneum
lfu_cache_policy.hpp
Go to the documentation of this file.
1 #ifndef LFU_CACHE_POLICY_HPP
2 #define LFU_CACHE_POLICY_HPP
3 
4 #include <cstddef>
5 #include <unordered_map>
6 #include <map>
7 #include <iostream>
8 #include "cache_policy.hpp"
9 
10 namespace caches
11 {
12 template <typename Key>
13 class LFUCachePolicy : public ICachePolicy<Key>
14 {
15  public:
16 
17  using lfu_iterator = typename std::multimap<std::size_t, Key>::iterator;
18 
19  LFUCachePolicy() = default;
20 
21  ~LFUCachePolicy() override = default;
22 
23  void Insert(const Key& key) override
24  {
25  constexpr std::size_t INIT_VAL = 1;
26 
27  // all new value initialized with the frequency 1
28  lfu_storage[key] = frequency_storage.emplace_hint(
29  frequency_storage.cbegin(), INIT_VAL, key);
30  }
31 
32  void Touch(const Key& key) override
33  {
34  // get the previous frequency value of a key
35  auto elem_for_update = lfu_storage[key];
36 
37  auto updated_elem = std::make_pair(
38  elem_for_update->first + 1, elem_for_update->second);
39 
40  // update the previous value
41  frequency_storage.erase(elem_for_update);
42 
43  lfu_storage[key] = frequency_storage.emplace_hint(
44  frequency_storage.cend(), std::move(updated_elem));
45  }
46 
47  void Erase(const Key& key) override
48  {
49  frequency_storage.erase(lfu_storage[key]);
50  lfu_storage.erase(key);
51  }
52 
53  const Key& ReplCandidate() const override
54  {
55  // at the beginning of the frequency_storage we have the
56  // least frequency used value
57  return frequency_storage.cbegin()->second;
58  }
59 
60  // return a key of a displacement candidate
61  void Clear() override
62  {
63  frequency_storage.clear();
64  lfu_storage.clear();
65  }
66 
67 
68  private:
69 
70  std::multimap<std::size_t, Key> frequency_storage;
71 
72  std::unordered_map<Key, lfu_iterator> lfu_storage;
73 };
74 } // namespace caches
75 
76 #endif // LFU_CACHE_POLICY_HPP
void Erase(const Key &key) override
Definition: lfu_cache_policy.hpp:47
void Touch(const Key &key) override
Definition: lfu_cache_policy.hpp:32
Definition: lfu_cache_policy.hpp:13
const Key & ReplCandidate() const override
Definition: lfu_cache_policy.hpp:53
Definition: cache_policy.hpp:11
std::unordered_map< Key, lfu_iterator > lfu_storage
Definition: lfu_cache_policy.hpp:72
void Insert(const Key &key) override
Definition: lfu_cache_policy.hpp:23
typename std::multimap< std::size_t, Key >::iterator lfu_iterator
Definition: lfu_cache_policy.hpp:17
~LFUCachePolicy() override=default
std::multimap< std::size_t, Key > frequency_storage
Definition: lfu_cache_policy.hpp:70
void Clear() override
Definition: lfu_cache_policy.hpp:61
Definition: cache.hpp:11