Sirius  0.0.0
lru_cache.h
Go to the documentation of this file.
1 
22 #ifndef SIRIUS_UTILS_LRU_CACHE_H_
23 #define SIRIUS_UTILS_LRU_CACHE_H_
24 
25 #include <list>
26 #include <map>
27 #include <mutex>
28 
29 #include "sirius/utils/log.h"
30 
31 namespace sirius {
32 namespace utils {
33 
37 template <typename Key, typename Value, std::size_t CacheSize = 5>
38 class LRUCache {
39  public:
40  LRUCache() = default;
41  ~LRUCache() = default;
42 
43  // non copyable
44  LRUCache(const LRUCache&) = delete;
45  LRUCache& operator=(const LRUCache&) = delete;
46  // non moveable
47  LRUCache(LRUCache&&) = delete;
48  LRUCache& operator=(LRUCache&&) = delete;
49 
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];
64  }
65  return {};
66  }
67 
77  void Insert(const Key& key, Value element) {
78  std::lock_guard<std::mutex> lock(cache_mutex_);
79  if (elements_.count(key) > 0) {
80  // entry already in cache, remove it
81  ordered_keys_.remove(key);
82  elements_.erase(key);
83  }
84 
85  // insert (key, value) in cache
86  ordered_keys_.push_front(key);
87  elements_[key] = element;
88 
89  if (elements_.size() > CacheSize) {
90  // too many entries, remove the last recently used value
91  auto lru_key = ordered_keys_.back();
92  ordered_keys_.pop_back();
93  elements_.erase(lru_key);
94  }
95  }
96 
101  void Remove(const Key& key) {
102  std::lock_guard<std::mutex> lock(cache_mutex_);
103  if (elements_.count(key) == 0) {
104  return;
105  }
106  ordered_keys_.remove(key);
107  elements_.erase(key);
108  }
109 
113  void Clear() {
114  std::lock_guard<std::mutex> lock(cache_mutex_);
115  ordered_keys_.clear();
116  elements_.clear();
117  }
118 
124  bool Contains(const Key& key) const { return elements_.count(key) > 0; }
125 
130  std::size_t Size() { return elements_.size(); }
131 
132  private:
133  std::mutex cache_mutex_;
134  std::list<Key> ordered_keys_;
135  std::map<Key, Value> elements_;
136 };
137 
138 } // namespace utils
139 } // namespace sirius
140 
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