#pragma once #include #include #include #include #include #include #include #include #include namespace Void::Cache { // ── Cache // ─────────────────────────────────────────────────────────────── A // fixed-capacity cache with per-entry TTL, a selectable eviction policy, // and hit/miss/eviction/expiration counters. Built on the same // doubly-linked-list + hash-map structure as Containers/LRU.hpp (which // stays the minimal primitive). // // Not thread-safe — guard externally if shared, like LruCache. // // Expiry is lazy: an entry past its TTL is treated as a miss and dropped on // the next access (or in bulk via sweep()). The clock is injectable for // tests. enum class Policy { LRU, // evict the least-recently-used entry (default) LFU, // evict the least-frequently-used entry FIFO // evict the oldest inserted entry }; template class Cache { public: using Clock = std::function; using Duration = std::chrono::steady_clock::duration; using TimePoint = std::chrono::steady_clock::time_point; struct Stats { std::uint64_t hits = 0; std::uint64_t misses = 0; std::uint64_t evictions = 0; // dropped to make room (capacity) std::uint64_t expirations = 0; // dropped because the TTL elapsed std::size_t size = 0; }; explicit Cache(std::size_t capacity, Policy policy = Policy::LRU, std::optional default_ttl = std::nullopt, Clock clock = default_clock()) : capacity_{capacity}, policy_{policy}, default_ttl_{default_ttl}, clock_{std::move(clock)} { 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_; } [[nodiscard]] Policy policy() const noexcept { return policy_; } // Retrieve a value. nullopt on miss or expiry; updates recency / // frequency and the hit/miss counters on every call. [[nodiscard]] std::optional get(const K& key) { auto it = map_.find(key); if (it == map_.end()) { ++misses_; return std::nullopt; } const auto now = clock_(); if (expired(*it->second, now)) { drop(it); ++expirations_; ++misses_; return std::nullopt; } ++hits_; touch(it->second); return it->second->value; } // Peek without recency promotion and without touching hit/miss // stats. Still respects expiry (an expired entry is invisible and // dropped). [[nodiscard]] const V* peek(const K& key) { auto it = map_.find(key); if (it == map_.end()) { return nullptr; } if (expired(*it->second, clock_())) { drop(it); ++expirations_; return nullptr; } return &it->second->value; } // Insert or update with the cache's default TTL. void put(const K& key, V value) { put(key, std::move(value), default_ttl_); } // Insert or update with an explicit TTL (nullopt = never expires). void put(const K& key, V value, std::optional ttl) { const auto now = clock_(); if (auto it = map_.find(key); it != map_.end()) { it->second->value = std::move(value); set_expiry(*it->second, ttl, now); touch(it->second); return; } if (map_.size() == capacity_) { evict_one(); } list_.push_front(Node{key, std::move(value), 1, {}, false}); set_expiry(list_.front(), ttl, now); map_[key] = list_.begin(); } bool erase(const K& key) { auto it = map_.find(key); if (it == map_.end()) { return false; } drop(it); return true; } void clear() noexcept { list_.clear(); map_.clear(); } // Present and not expired. Const: does not drop the expired entry. [[nodiscard]] bool contains(const K& key) const { auto it = map_.find(key); return it != map_.end() && !expired(*it->second, clock_()); } // Purge every expired entry; returns how many were removed. std::size_t sweep() { const auto now = clock_(); std::size_t purged = 0; for (auto it = list_.begin(); it != list_.end();) { if (expired(*it, now)) { map_.erase(it->key); it = list_.erase(it); ++purged; ++expirations_; } else { ++it; } } return purged; } [[nodiscard]] Stats stats() const { return Stats{hits_, misses_, evictions_, expirations_, map_.size()}; } private: struct Node { K key; V value; std::uint64_t freq = 0; TimePoint expiry{}; bool has_expiry = false; }; using List = std::list; using Map = std::unordered_map; static Clock default_clock() { return [] { return std::chrono::steady_clock::now(); }; } static bool expired(const Node& n, TimePoint now) { return n.has_expiry && now >= n.expiry; } void set_expiry(Node& n, std::optional ttl, TimePoint now) { n.has_expiry = ttl.has_value(); if (ttl) { n.expiry = now + *ttl; } } // Record a use: bump frequency and (for LRU) promote to // most-recent. void touch(typename List::iterator lit) { ++lit->freq; if (policy_ == Policy::LRU) { list_.splice(list_.begin(), list_, lit); } } void drop(typename Map::iterator it) { list_.erase(it->second); map_.erase(it); } void evict_one() { typename List::iterator victim; if (policy_ == Policy::LFU) { victim = list_.begin(); for (auto i = list_.begin(); i != list_.end(); ++i) { if (i->freq < victim->freq) { victim = i; } } } else { // LRU and FIFO both evict from the back: LRU keeps the list // in recency order via touch(); FIFO never reorders, so the // back is the oldest insertion. victim = std::prev(list_.end()); } map_.erase(victim->key); list_.erase(victim); ++evictions_; } std::size_t capacity_; Policy policy_; std::optional default_ttl_; Clock clock_; List list_; Map map_; std::uint64_t hits_ = 0; std::uint64_t misses_ = 0; std::uint64_t evictions_ = 0; std::uint64_t expirations_ = 0; }; } // namespace Void::Cache