teditor  1.8.0@@fee5e94
Terminal based editor written in C++
lrucache.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <unordered_map>
4 
5 namespace teditor {
6 
12 template <typename K, typename V>
13 class LRUCache {
14 public:
19  LRUCache(size_t c) : objs(), cap(c), head(nullptr), tail(nullptr) {}
20 
21  bool exists(const K& k) const { return objs.find(k) != objs.end(); }
22  size_t capacity() const { return cap; }
23  size_t size() const { return objs.size(); }
24 
29  V& get(const K& k) {
30  auto itr = objs.find(k);
31  if (itr == objs.end()) {
32  put(k, V());
33  itr = objs.find(k);
34  }
35  auto& node = itr->second;
36  make_recent(&node);
37  return node.value;
38  }
39 
41  void put(const K& k, const V& v) {
42  if (objs.size() >= cap) remove_tail();
43  auto itr = objs.find(k);
44  if (itr == objs.end()) {
45  Node n;
46  n.key = k;
47  n.prev = n.next = nullptr;
48  objs[k] = n;
49  itr = objs.find(k);
50  }
51  auto& node = itr->second;
52  node.value = v;
53  make_recent(&node);
54  }
55 
56 private:
57  struct Node {
58  K key;
59  V value;
60  Node *prev, *next;
61  Node() {}
62  }; // struct Node
63 
64  std::unordered_map<K, Node> objs;
65  size_t cap;
66  // together represent a non-allocating doubly linked list
67  Node *head, *tail;
68 
69  void make_recent(Node* val) {
70  if (head == val) return;
71  if (tail == val) {
72  tail = tail->prev;
73  tail->next = nullptr;
74  } else {
75  if (val->prev != nullptr) val->prev->next = val->next;
76  if (val->next != nullptr) val->next->prev = val->prev;
77  }
78  val->prev = nullptr;
79  val->next = head;
80  if (head != nullptr) head->prev = val;
81  head = val;
82  if (tail == nullptr) tail = head;
83  }
84 
85  void remove_tail() {
86  if (tail == nullptr) return;
87  const K& key = tail->key;
88  objs.erase(key);
89  tail = tail->prev;
90  tail->next = nullptr;
91  }
92 }; // class LRUCache
93 
94 } // namespace teditor
teditor::LRUCache
LRU Cache implementation.
Definition: lrucache.hpp:13
teditor::LRUCache::get
V & get(const K &k)
Gets value at the given key and if the key does not exist it returns a default value object.
Definition: lrucache.hpp:29
teditor::LRUCache::LRUCache
LRUCache(size_t c)
ctor
Definition: lrucache.hpp:19
teditor::LRUCache::capacity
size_t capacity() const
Definition: lrucache.hpp:22
teditor::LRUCache::put
void put(const K &k, const V &v)
Definition: lrucache.hpp:41
teditor::LRUCache::size
size_t size() const
Definition: lrucache.hpp:23
teditor::Node
Definition: trie.h:10
teditor::LRUCache::exists
bool exists(const K &k) const
Definition: lrucache.hpp:21
teditor
Definition: any.hpp:10