Electroneum
lru_cache_policy.hpp
Go to the documentation of this file.
1 #ifndef LRU_CACHE_POLICY_HPP
2 #define LRU_CACHE_POLICY_HPP
3 
4 #include <list>
5 #include <unordered_map>
6 #include "cache_policy.hpp"
7 
8 namespace caches
9 {
10 template <typename Key>
11 class LRUCachePolicy : public ICachePolicy<Key>
12 {
13 
14  public:
15 
16  using lru_iterator = typename std::list<Key>::const_iterator;
17 
18  LRUCachePolicy() = default;
19  ~LRUCachePolicy() = default;
20 
21  void Insert(const Key& key) override
22  {
23  lru_queue.emplace_front(key);
24  key_finder[key] = lru_queue.cbegin();
25  }
26 
27  void Touch(const Key& key) override
28  {
29  // move the touched element at the beginning of the lru_queue
30  lru_queue.splice(lru_queue.cbegin(), lru_queue, key_finder[key]);
31  }
32 
33  void Erase(const Key& key) override
34  {
35  // remove the least recently used element
36  key_finder.erase(lru_queue.back());
37 
38  lru_queue.pop_back();
39  }
40 
41  // return a key of a displacement candidate
42  const Key& ReplCandidate() const override
43  {
44  return lru_queue.back();
45  }
46 
47  // return a key of a displacement candidate
48  void Clear() override
49  {
50  lru_queue.clear();
51  key_finder.clear();
52  }
53 
54  private:
55 
56  std::list<Key> lru_queue;
57 
58  std::unordered_map<Key, lru_iterator> key_finder;
59 };
60 
61 } // namespace caches
62 
63 #endif // LRU_CACHE_POLICY_HPP
void Touch(const Key &key) override
Definition: lru_cache_policy.hpp:27
typename std::list< Key >::const_iterator lru_iterator
Definition: lru_cache_policy.hpp:16
std::unordered_map< Key, lru_iterator > key_finder
Definition: lru_cache_policy.hpp:58
const Key & ReplCandidate() const override
Definition: lru_cache_policy.hpp:42
void Clear() override
Definition: lru_cache_policy.hpp:48
Definition: lru_cache_policy.hpp:11
Definition: cache_policy.hpp:11
std::list< Key > lru_queue
Definition: lru_cache_policy.hpp:56
Definition: cache.hpp:11
void Insert(const Key &key) override
Definition: lru_cache_policy.hpp:21
void Erase(const Key &key) override
Definition: lru_cache_policy.hpp:33