#pragma once #include #include #include #include #include #include namespace Void::LRU { // ── LruCache ──────────────────────────────────────────────────────────── // Fixed-capacity LRU cache. get() promotes to MRU; put() evicts LRU when full. // All operations are O(1) amortized via a doubly-linked list + hash map. template class LruCache { using List = std::list>; using Map = std::unordered_map; public: explicit LruCache(std::size_t capacity) : capacity_{capacity} { if (capacity == 0) throw std::invalid_argument{"capacity must be > 0"}; } [[nodiscard]] std::size_t capacity() const noexcept { return capacity_; } [[nodiscard]] std::size_t size() const noexcept { return map_.size(); } [[nodiscard]] bool empty() const noexcept { return map_.empty(); } [[nodiscard]] bool full() const noexcept { return map_.size() == capacity_; } // Retrieve a value. Returns nullopt on miss; promotes the entry on hit. [[nodiscard]] std::optional get(const K& key) { auto it = map_.find(key); if (it == map_.end()) return std::nullopt; list_.splice(list_.begin(), list_, it->second); return it->second->second; } // Peek without changing recency order. [[nodiscard]] const V* peek(const K& key) const { auto it = map_.find(key); if (it == map_.end()) return nullptr; return &it->second->second; } // Insert or update. If the key already exists its recency is updated. // If the cache is full the least-recently-used entry is evicted. void put(const K& key, V value) { auto it = map_.find(key); if (it != map_.end()) { it->second->second = std::move(value); list_.splice(list_.begin(), list_, it->second); return; } if (map_.size() == capacity_) { map_.erase(list_.back().first); list_.pop_back(); } list_.emplace_front(key, std::move(value)); map_[key] = list_.begin(); } bool erase(const K& key) { auto it = map_.find(key); if (it == map_.end()) return false; list_.erase(it->second); map_.erase(it); return true; } void clear() noexcept { list_.clear(); map_.clear(); } [[nodiscard]] bool contains(const K& key) const { return map_.contains(key); } // Iterate entries in MRU→LRU order (const). [[nodiscard]] const List& entries() const noexcept { return list_; } private: std::size_t capacity_; List list_; Map map_; }; } // namespace Void::LRU