loon
High-performance header-only C++ library for low-latency applications
Loading...
Searching...
No Matches
lru.hpp
Go to the documentation of this file.
1#pragma once
2
5
6#include <list>
7#include <optional>
8#include <unordered_map>
9
10namespace loon {
11
28template <typename K, typename V>
29class LRU {
30 public:
33 explicit LRU(size_t size) : capacity(size) {}
34
41 std::optional<std::reference_wrapper<V>> get(const K& key) {
42 const auto it = map.find(key);
43 if (it == map.end())
44 return std::nullopt;
45
46 setMRU(key);
47 const auto store_entry_itr = it->second;
48 return store_entry_itr->second;
49 }
50
59 void put(const K& key, const V& value) {
60 const auto it = map.find(key);
61 if (it != map.end()) {
62 auto store_entry_itr = it->second;
63 store_entry_itr->second = value;
64 setMRU(key);
65 } else {
66 if (capacity == store.size()) {
67 map.erase(store.back().first);
68 store.pop_back();
69 }
70 store.emplace_front(std::pair{key, value});
71 map[key] = store.begin();
72 }
73 }
74
81 bool exists(const K& key) const { return map.find(key) != map.end(); }
82
88 void remove(const K& key) {
89 const auto it = map.find(key);
90 if (it == map.end())
91 return;
92 store.erase(it->second);
93 map.erase(it);
94 }
95
98 size_t size() const { return store.size(); }
99
100 private:
101 size_t capacity;
102 std::list<std::pair<K, V>> store;
103 std::unordered_map<K, typename std::list<std::pair<K, V>>::iterator> map;
104
107 void setMRU(const K& key) {
108 auto element_itr = map[key];
109 store.splice(store.begin(), store, element_itr);
110 }
111};
112
113} // namespace loon
A Least Recently Used (LRU) cache with O(1) access and eviction.
Definition lru.hpp:29
std::optional< std::reference_wrapper< V > > get(const K &key)
Retrieves a value from the cache.
Definition lru.hpp:41
bool exists(const K &key) const
Checks if a key exists in the cache.
Definition lru.hpp:81
void put(const K &key, const V &value)
Inserts or updates a key-value pair in the cache.
Definition lru.hpp:59
LRU(size_t size)
Constructs an LRU cache with the specified capacity.
Definition lru.hpp:33
size_t size() const
Returns the current number of entries in the cache.
Definition lru.hpp:98
void remove(const K &key)
Removes a key-value pair from the cache.
Definition lru.hpp:88