Caches 0.1.0
LRU/LFU/FIFO Caches library
Loading...
Searching...
No Matches
lfu_cache_policy.hpp
Go to the documentation of this file.
1
5#ifndef LFU_CACHE_POLICY_HPP
6#define LFU_CACHE_POLICY_HPP
7
8#include "cache_policy.hpp"
9#include <cstddef>
10#include <iostream>
11#include <map>
12#include <unordered_map>
13
14namespace caches
15{
29template <typename Key>
30class LFUCachePolicy : public ICachePolicy<Key>
31{
32 public:
33 using lfu_iterator = typename std::multimap<std::size_t, Key>::iterator;
34
35 LFUCachePolicy() = default;
36 ~LFUCachePolicy() override = default;
37
38 void Insert(const Key &key) override
39 {
40 constexpr std::size_t INIT_VAL = 1;
41 // all new value initialized with the frequency 1
42 lfu_storage[key] =
43 frequency_storage.emplace_hint(frequency_storage.cbegin(), INIT_VAL, key);
44 }
45
46 void Touch(const Key &key) override
47 {
48 // get the previous frequency value of a key
49 auto elem_for_update = lfu_storage[key];
50 auto updated_elem = std::make_pair(elem_for_update->first + 1, elem_for_update->second);
51 // update the previous value
52 frequency_storage.erase(elem_for_update);
53 lfu_storage[key] =
54 frequency_storage.emplace_hint(frequency_storage.cend(), std::move(updated_elem));
55 }
56
57 void Erase(const Key &key) noexcept override
58 {
59 frequency_storage.erase(lfu_storage[key]);
60 lfu_storage.erase(key);
61 }
62
63 const Key &ReplCandidate() const noexcept override
64 {
65 // at the beginning of the frequency_storage we have the
66 // least frequency used value
67 return frequency_storage.cbegin()->second;
68 }
69
70 private:
71 std::multimap<std::size_t, Key> frequency_storage;
72 std::unordered_map<Key, lfu_iterator> lfu_storage;
73};
74} // namespace caches
75
76#endif // LFU_CACHE_POLICY_HPP
Cache policy interface declaration.
Cache policy abstract base class.
Definition: cache_policy.hpp:19
LFU (Least frequently used) cache policy.
Definition: lfu_cache_policy.hpp:31
void Touch(const Key &key) override
Handle request to the key-element in a cache.
Definition: lfu_cache_policy.hpp:46
const Key & ReplCandidate() const noexcept override
Return a key of a replacement candidate.
Definition: lfu_cache_policy.hpp:63
void Erase(const Key &key) noexcept override
Handle element deletion from a cache.
Definition: lfu_cache_policy.hpp:57
void Insert(const Key &key) override
Handle element insertion in a cache.
Definition: lfu_cache_policy.hpp:38