10#include <unordered_map>
43template <
typename TKey,
typename TValue,
class TMutex = std::shared_mutex>
55 using TPair = std::pair<TKey, TValue>;
65 using Pointer = std::shared_ptr<LRUCache<TKey, TValue>>;
77 return std::make_shared<LRUCache<TKey, TValue>>();
83 return std::make_shared<LRUCache<TKey, TValue>>(
capacity);
93 throw std::invalid_argument(
94 "Cannot create cache with capacity <= 0");
104 auto size() const -> std::
size_t override {
return lookup_.size(); }
109 auto get(
const TKey& k) -> TValue
override
112 auto lookupIter =
lookup_.find(k);
113 if (lookupIter == std::end(
lookup_)) {
114 throw std::invalid_argument(
"Key not in cache");
118 return lookupIter->second->second;
122 void put(
const TKey& k,
const TValue& v)
override
126 auto lookupIter =
lookup_.find(k);
127 if (lookupIter != std::end(
lookup_)) {
128 auto& [key, val] = *lookupIter->second;
132 items_.erase(lookupIter->second);
161 void onEvict(std::function<
bool(TKey&, TValue&)> fn)
override
190 auto& [key, _] =
items_.back();
200 auto& [key, value] = *it;
206 it = std::reverse_iterator(
items_.erase(it.base()));
225 auto& [key, value] = *it;
247 std::unordered_map<TKey, TListIterator>
lookup_;
Abstract Base Class for Key-Value Caches.
std::function< bool(TKey &, TValue &)> on_eject_
std::shared_ptr< Cache > Pointer
Least Recently Used Cache.
auto size() const -> std::size_t override
Get the current number of elements in the cache.
void put(const TKey &k, const TValue &v) override
Put an item into the cache.
auto contains(const TKey &k) -> bool override
Check if an item is already in the cache.
void setCapacity(std::size_t capacity) override
Set the maximum number of elements in the cache.
std::list< TPair > items_
auto get(const TKey &k) -> TValue override
Get an item from the cache by key.
std::pair< TKey, TValue > TPair
Templated Key/Value pair.
std::shared_ptr< LRUCache< TKey, TValue > > Pointer
typename std::list< TPair >::iterator TListIterator
Templated Key/Value pair iterator.
auto capacity() const -> std::size_t override
Get the maximum number of elements in the cache.
LRUCache()
Default constructor.
void purge() override
Evict all items ignoring cache policy.
LRUCache(std::size_t capacity)
Constructor with cache capacity parameter.
std::unordered_map< TKey, TListIterator > lookup_
void onEvict(std::function< bool(TKey &, TValue &)> fn) override
Set a callback function for validating if an item can be evicted.
void resetOnEvict() override
Remove the validation callback function.
void evict() override
Evict items following the cache policy.
Volume Cartographer library