TTK
Loading...
Searching...
No Matches
Cache.h
Go to the documentation of this file.
1#pragma once
2
3#include <list>
4#include <map>
5
6namespace ttk {
12 template <class KeyType, class ValueType>
13 class LRUCache {
14 public:
15 // default cache with at most 8 entries
16 LRUCache() : capacity_{8} {
17 }
18
19 LRUCache(const std::size_t capacity) : capacity_(capacity) {
20 }
21
22 inline bool empty() const {
23 return this->map_.empty();
24 }
25
26 inline std::size_t capacity() const {
27 return this->capacity_;
28 }
29
30 inline std::size_t size() const {
31 return this->map_.size();
32 }
33
34 inline bool contains(const KeyType &key) const {
35 return this->map_.find(key) != this->map_.end();
36 }
37
38 inline void clear() {
39 this->map_.clear();
40 this->queue_.clear();
41 }
42
48 inline void insert(const KeyType &key, const ValueType &value) {
49 if(this->contains(key)) {
50 return; // key already in use
51 }
52
53 if(this->size() >= this->capacity_) {
54 // cache is full, evict the least recently used entry
55 this->map_.erase(this->queue_.back());
56 this->queue_.pop_back();
57 }
58
59 // insert new entry
60 this->queue_.push_front(key);
61 this->map_.emplace(key, std::make_pair(value, this->queue_.begin()));
62 }
63
69 inline ValueType *get(const KeyType &key) {
70 const auto i = this->map_.find(key);
71 if(i == this->map_.end()) {
72 // cache miss, nullptr
73 return {};
74 }
75
76 // iterator to entry in LRU list
77 const auto oldIt = i->second.second;
78 if(oldIt != this->queue_.begin()) {
79 // update entry, now first in the LRU list
80 this->queue_.erase(oldIt);
81 this->queue_.push_front(key);
82
83 // update queue position in map
84 this->map_[key].second = this->queue_.begin();
85 }
86
87 // return value address
88 return &i->second.first;
89 }
90
91 private:
92 using ListType = std::list<KeyType>;
93 using MapType
94 = std::map<KeyType, std::pair<ValueType, typename ListType::iterator>>;
95
96 MapType map_;
97 ListType queue_;
98 std::size_t capacity_;
99 };
100
101} // namespace ttk
LRU cache implementation.
Definition Cache.h:13
std::size_t capacity() const
Definition Cache.h:26
bool empty() const
Definition Cache.h:22
ValueType * get(const KeyType &key)
Get value pointer from key.
Definition Cache.h:69
void clear()
Definition Cache.h:38
LRUCache(const std::size_t capacity)
Definition Cache.h:19
void insert(const KeyType &key, const ValueType &value)
Insert new (key, value) entry.
Definition Cache.h:48
std::size_t size() const
Definition Cache.h:30
bool contains(const KeyType &key) const
Definition Cache.h:34
The Topology ToolKit.