game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
lru_cache.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// lru_cache.h
4// ==============================================================================
5// Thread-safe LRU (Least Recently Used) cache with TTL support
6// ==============================================================================
7// Provides bounded caching with automatic eviction of oldest entries when
8// the cache reaches its maximum size. Optionally supports time-based expiration.
9//
10// ## Features
11// - O(1) get/put operations using hash map + doubly linked list
12// - Thread-safe with mutex protection
13// - Optional TTL (time-to-live) for entries
14// - Configurable maximum size
15// - Statistics tracking (hits, misses, evictions)
16//
17// ## Usage Example
18// @code
19// LRUCache<int, std::string> cache(100); // Max 100 entries
20// cache.put(42, "hello");
21// auto value = cache.get(42); // Returns std::optional<std::string>
22// if (value) {
23// std::cout << *value << std::endl;
24// }
25// @endcode
26// ==============================================================================
27
28#pragma once
29
30#include <chrono>
31#include <list>
32#include <mutex>
33#include <optional>
34#include <unordered_map>
35
36/**
37 * @class LRUCache
38 * @brief Thread-safe LRU cache with optional TTL support
39 *
40 * @tparam Key Type of cache keys (must be hashable)
41 * @tparam Value Type of cached values
42 */
43template <typename Key, typename Value> class LRUCache
44{
45 public:
46 using Clock = std::chrono::steady_clock;
47 using TimePoint = Clock::time_point;
48
49 /**
50 * @brief Construct an LRU cache
51 * @param maxSize Maximum number of entries (must be >= 1)
52 * @param ttlSeconds Time-to-live in seconds (0 = no expiration)
53 */
54 explicit LRUCache(size_t maxSize, int ttlSeconds = 0)
55 : maxSize_(maxSize > 0 ? maxSize : 1), ttlSeconds_(ttlSeconds)
56 {
57 }
58
59 // Non-copyable and non-movable (contains mutex)
60 LRUCache(const LRUCache&) = delete;
61 LRUCache& operator=(const LRUCache&) = delete;
62 LRUCache(LRUCache&&) = delete;
64
65 /**
66 * @brief Get a value from the cache
67 * @param key Key to look up
68 * @return Optional containing value if found and not expired, empty otherwise
69 *
70 * Moves the accessed entry to the front (most recently used).
71 */
72 std::optional<Value> get(const Key& key)
73 {
74 std::lock_guard<std::mutex> lock(mutex_);
75
76 auto it = cacheMap_.find(key);
77 if (it == cacheMap_.end())
78 {
79 ++misses_;
80 return std::nullopt;
81 }
82
83 // Check TTL if enabled
84 if (ttlSeconds_ > 0)
85 {
86 auto age = std::chrono::duration_cast<std::chrono::seconds>(Clock::now() -
87 it->second->timestamp)
88 .count();
89 if (age > ttlSeconds_)
90 {
91 // Entry expired - remove it
92 cacheList_.erase(it->second);
93 cacheMap_.erase(it);
94 ++misses_;
95 ++expirations_;
96 return std::nullopt;
97 }
98 }
99
100 // Move to front (most recently used)
101 cacheList_.splice(cacheList_.begin(), cacheList_, it->second);
102 ++hits_;
103
104 return it->second->value;
105 }
106
107 /**
108 * @brief Put a value in the cache
109 * @param key Key to store under
110 * @param value Value to cache
111 *
112 * If key exists, updates the value and moves to front.
113 * If cache is full, evicts the least recently used entry.
114 */
115 void put(const Key& key, const Value& value)
116 {
117 std::lock_guard<std::mutex> lock(mutex_);
118
119 auto it = cacheMap_.find(key);
120 if (it != cacheMap_.end())
121 {
122 // Update existing entry
123 it->second->value = value;
124 it->second->timestamp = Clock::now();
125 cacheList_.splice(cacheList_.begin(), cacheList_, it->second);
126 return;
127 }
128
129 // Evict if at capacity
130 while (cacheList_.size() >= maxSize_)
131 {
132 auto last = cacheList_.back();
133 cacheMap_.erase(last.key);
134 cacheList_.pop_back();
135 ++evictions_;
136 }
137
138 // Insert new entry at front
139 cacheList_.emplace_front(CacheEntry{key, value, Clock::now()});
140 cacheMap_[key] = cacheList_.begin();
141 }
142
143 /**
144 * @brief Put a value using move semantics
145 */
146 void put(const Key& key, Value&& value)
147 {
148 std::lock_guard<std::mutex> lock(mutex_);
149
150 auto it = cacheMap_.find(key);
151 if (it != cacheMap_.end())
152 {
153 it->second->value = std::move(value);
154 it->second->timestamp = Clock::now();
155 cacheList_.splice(cacheList_.begin(), cacheList_, it->second);
156 return;
157 }
158
159 while (cacheList_.size() >= maxSize_)
160 {
161 auto last = cacheList_.back();
162 cacheMap_.erase(last.key);
163 cacheList_.pop_back();
164 ++evictions_;
165 }
166
167 cacheList_.emplace_front(CacheEntry{key, std::move(value), Clock::now()});
168 cacheMap_[key] = cacheList_.begin();
169 }
170
171 /**
172 * @brief Check if key exists and is not expired (without updating LRU order)
173 */
174 bool contains(const Key& key) const
175 {
176 std::lock_guard<std::mutex> lock(mutex_);
177 auto it = cacheMap_.find(key);
178 if (it == cacheMap_.end())
179 return false;
180 if (ttlSeconds_ > 0)
181 {
182 auto age = std::chrono::duration_cast<std::chrono::seconds>(Clock::now() -
183 it->second->timestamp)
184 .count();
185 if (age > ttlSeconds_)
186 return false;
187 }
188 return true;
189 }
190
191 /**
192 * @brief Remove a specific key from cache
193 * @return true if key was found and removed
194 */
195 bool remove(const Key& key)
196 {
197 std::lock_guard<std::mutex> lock(mutex_);
198
199 auto it = cacheMap_.find(key);
200 if (it == cacheMap_.end())
201 return false;
202
203 cacheList_.erase(it->second);
204 cacheMap_.erase(it);
205 return true;
206 }
207
208 /**
209 * @brief Clear all entries
210 */
211 void clear()
212 {
213 std::lock_guard<std::mutex> lock(mutex_);
214 cacheList_.clear();
215 cacheMap_.clear();
216 }
217
218 /**
219 * @brief Get current number of entries
220 */
221 size_t size() const
222 {
223 std::lock_guard<std::mutex> lock(mutex_);
224 return cacheList_.size();
225 }
226
227 /**
228 * @brief Get maximum capacity
229 */
230 size_t maxSize() const
231 {
232 return maxSize_;
233 }
234
235 /**
236 * @brief Check if cache is empty
237 */
238 bool empty() const
239 {
240 std::lock_guard<std::mutex> lock(mutex_);
241 return cacheList_.empty();
242 }
243
244 // ==========================================================================
245 // Statistics
246 // ==========================================================================
247
248 struct Stats
249 {
250 size_t hits = 0;
251 size_t misses = 0;
252 size_t evictions = 0;
253 size_t expirations = 0;
254 size_t currentSize = 0;
255 size_t maxSize = 0;
256
257 float hitRate() const
258 {
259 size_t total = hits + misses;
260 return total > 0 ? static_cast<float>(hits) / static_cast<float>(total) : 0.0f;
261 }
262 };
263
264 /**
265 * @brief Get cache statistics
266 */
268 {
269 std::lock_guard<std::mutex> lock(mutex_);
270 return Stats{hits_, misses_, evictions_, expirations_, cacheList_.size(), maxSize_};
271 }
272
273 /**
274 * @brief Reset statistics counters
275 */
277 {
278 std::lock_guard<std::mutex> lock(mutex_);
279 hits_ = misses_ = evictions_ = expirations_ = 0;
280 }
281
282 /**
283 * @brief Remove expired entries (useful for periodic cleanup)
284 * @return Number of entries removed
285 */
287 {
288 if (ttlSeconds_ <= 0)
289 return 0;
290
291 std::lock_guard<std::mutex> lock(mutex_);
292 size_t removed = 0;
293 auto now = Clock::now();
294
295 auto it = cacheList_.begin();
296 while (it != cacheList_.end())
297 {
298 auto age =
299 std::chrono::duration_cast<std::chrono::seconds>(now - it->timestamp).count();
300 if (age > ttlSeconds_)
301 {
302 cacheMap_.erase(it->key);
303 it = cacheList_.erase(it);
304 ++removed;
305 ++expirations_;
306 }
307 else
308 {
309 ++it;
310 }
311 }
312
313 return removed;
314 }
315
316 private:
317 struct CacheEntry
318 {
319 Key key;
320 Value value;
321 TimePoint timestamp;
322 };
323
324 using CacheList = std::list<CacheEntry>;
325 using CacheMap = std::unordered_map<Key, typename CacheList::iterator>;
326
327 size_t maxSize_;
328 int ttlSeconds_;
329
330 mutable std::mutex mutex_;
331 CacheList cacheList_;
332 CacheMap cacheMap_;
333
334 // Statistics
335 size_t hits_ = 0;
336 size_t misses_ = 0;
337 size_t evictions_ = 0;
338 size_t expirations_ = 0;
339};
LRUCache & operator=(LRUCache &&)=delete
bool contains(const Key &key) const
Check if key exists and is not expired (without updating LRU order).
Definition lru_cache.h:174
LRUCache(LRUCache &&)=delete
LRUCache(size_t maxSize, int ttlSeconds=0)
Construct an LRU cache.
Definition lru_cache.h:54
bool remove(const Key &key)
Remove a specific key from cache.
Definition lru_cache.h:195
void put(const Key &key, const Value &value)
Put a value in the cache.
Definition lru_cache.h:115
std::chrono::steady_clock Clock
Definition lru_cache.h:46
void clear()
Clear all entries.
Definition lru_cache.h:211
LRUCache & operator=(const LRUCache &)=delete
std::optional< Value > get(const Key &key)
Get a value from the cache.
Definition lru_cache.h:72
size_t pruneExpired()
Remove expired entries (useful for periodic cleanup).
Definition lru_cache.h:286
size_t size() const
Get current number of entries.
Definition lru_cache.h:221
Stats getStats() const
Get cache statistics.
Definition lru_cache.h:267
size_t maxSize() const
Get maximum capacity.
Definition lru_cache.h:230
LRUCache(const LRUCache &)=delete
void put(const Key &key, Value &&value)
Put a value using move semantics.
Definition lru_cache.h:146
Clock::time_point TimePoint
Definition lru_cache.h:47
void resetStats()
Reset statistics counters.
Definition lru_cache.h:276
bool empty() const
Check if cache is empty.
Definition lru_cache.h:238
size_t expirations
Definition lru_cache.h:253
float hitRate() const
Definition lru_cache.h:257
size_t currentSize
Definition lru_cache.h:254