14#include <unordered_map>
21template <
class Tkey,
class Tdata>
24 typedef std::pair<Tkey, std::unique_ptr<Tdata>> Tpair;
25 typedef typename std::list<Tpair>::iterator Titer;
28 std::unordered_map<Tkey, Titer>
lookup;
46 return this->lookup.find(key) != this->lookup.end();
54 void Insert(
const Tkey key, std::unique_ptr<Tdata> &&item)
58 this->lookup[key]->second = std::move(item);
63 if (this->data.size() >= this->capacity) {
64 this->lookup.erase(
data.back().first);
65 this->data.pop_back();
69 this->data.emplace_front(key, std::move(item));
70 this->lookup.emplace(key, this->data.begin());
88 inline Tdata *
Get(
const Tkey key)
90 if (this->lookup.find(key) == this->lookup.end())
throw std::out_of_range(
"item not found");
92 this->data.splice(this->data.begin(), this->data, this->lookup[key]);
94 return this->data.front().second.get();
Size limited cache with a least recently used eviction strategy.
Tdata * Get(const Tkey key)
Get an item from the cache.
LRUCache(size_t max_items)
Construct new LRU cache map.
bool Contains(const Tkey key)
Test if a key is already contained in the cache.
void Insert(const Tkey key, std::unique_ptr< Tdata > &&item)
Insert a new data item with a specified key.
std::list< Tpair > data
Ordered list of all items.
void Clear()
Clear the cache.
const size_t capacity
Number of items to cache.
std::unordered_map< Tkey, Titer > lookup
Map of keys to items.