Caches 0.1.0
LRU/LFU/FIFO Caches library
Loading...
Searching...
No Matches
lru_cache_policy.hpp
Go to the documentation of this file.
1
5#ifndef LRU_CACHE_POLICY_HPP
6#define LRU_CACHE_POLICY_HPP
7
8#include "cache_policy.hpp"
9#include <list>
10#include <unordered_map>
11
12namespace caches
13{
36template <typename Key>
37class LRUCachePolicy : public ICachePolicy<Key>
38{
39 public:
40 using lru_iterator = typename std::list<Key>::iterator;
41
42 LRUCachePolicy() = default;
43 ~LRUCachePolicy() = default;
44
45 void Insert(const Key &key) override
46 {
47 lru_queue.emplace_front(key);
48 key_finder[key] = lru_queue.begin();
49 }
50
51 void Touch(const Key &key) override
52 {
53 // move the touched element at the beginning of the lru_queue
54 lru_queue.splice(lru_queue.begin(), lru_queue, key_finder[key]);
55 }
56
57 void Erase(const Key &) noexcept override
58 {
59 // remove the least recently used element
60 key_finder.erase(lru_queue.back());
61 lru_queue.pop_back();
62 }
63
64 // return a key of a displacement candidate
65 const Key &ReplCandidate() const noexcept override
66 {
67 return lru_queue.back();
68 }
69
70 private:
71 std::list<Key> lru_queue;
72 std::unordered_map<Key, lru_iterator> key_finder;
73};
74} // namespace caches
75
76#endif // LRU_CACHE_POLICY_HPP
Cache policy interface declaration.
Cache policy abstract base class.
Definition: cache_policy.hpp:19
LRU (Least Recently Used) cache policy.
Definition: lru_cache_policy.hpp:38
void Touch(const Key &key) override
Handle request to the key-element in a cache.
Definition: lru_cache_policy.hpp:51
const Key & ReplCandidate() const noexcept override
Return a key of a replacement candidate.
Definition: lru_cache_policy.hpp:65
void Erase(const Key &) noexcept override
Handle element deletion from a cache.
Definition: lru_cache_policy.hpp:57
void Insert(const Key &key) override
Handle element insertion in a cache.
Definition: lru_cache_policy.hpp:45