22 #ifndef SIRIUS_UTILS_LRU_CACHE_H_ 23 #define SIRIUS_UTILS_LRU_CACHE_H_ 37 template <
typename Key,
typename Value, std::
size_t CacheSize = 5>
58 Value
Get(
const Key& key) {
59 std::lock_guard<std::mutex> lock(cache_mutex_);
60 if (elements_.count(key) > 0) {
61 ordered_keys_.remove(key);
62 ordered_keys_.push_front(key);
63 return elements_[key];
77 void Insert(
const Key& key, Value element) {
78 std::lock_guard<std::mutex> lock(cache_mutex_);
79 if (elements_.count(key) > 0) {
81 ordered_keys_.remove(key);
86 ordered_keys_.push_front(key);
87 elements_[key] = element;
89 if (elements_.size() > CacheSize) {
91 auto lru_key = ordered_keys_.back();
92 ordered_keys_.pop_back();
93 elements_.erase(lru_key);
102 std::lock_guard<std::mutex> lock(cache_mutex_);
103 if (elements_.count(key) == 0) {
106 ordered_keys_.remove(key);
107 elements_.erase(key);
114 std::lock_guard<std::mutex> lock(cache_mutex_);
115 ordered_keys_.clear();
124 bool Contains(
const Key& key)
const {
return elements_.count(key) > 0; }
130 std::size_t
Size() {
return elements_.size(); }
133 std::mutex cache_mutex_;
134 std::list<Key> ordered_keys_;
135 std::map<Key, Value> elements_;
141 #endif // SIRIUS_UTILS_LRU_CACHE_H_
Definition: exception.h:27
LRU cache.
Definition: lru_cache.h:38
Value Get(const Key &key)
Get a cache element.
Definition: lru_cache.h:58
bool Contains(const Key &key) const
Check that a particular key is present in cache.
Definition: lru_cache.h:124
void Clear()
Clear all the cache elements.
Definition: lru_cache.h:113
LRUCache & operator=(const LRUCache &)=delete
void Remove(const Key &key)
Remove an element from the cache.
Definition: lru_cache.h:101
void Insert(const Key &key, Value element)
Insert an element in the cache.
Definition: lru_cache.h:77
std::size_t Size()
Get the current size of the cache.
Definition: lru_cache.h:130