Coverage Report

Created: 2026-01-21 08:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/node/src/lru_cache-inl.h
Line
Count
Source
1
#ifndef SRC_LRU_CACHE_INL_H_
2
#define SRC_LRU_CACHE_INL_H_
3
4
#include <list>
5
#include <unordered_map>
6
#include <utility>
7
8
template <typename key_t, typename value_t>
9
class LRUCache {
10
 public:
11
  using key_value_pair_t = typename std::pair<key_t, value_t>;
12
  using iterator = typename std::list<key_value_pair_t>::iterator;
13
  using const_iterator = typename std::list<key_value_pair_t>::const_iterator;
14
15
0
  const_iterator begin() const { return lru_list_.begin(); }
16
0
  const_iterator end() const { return lru_list_.end(); }
17
18
0
  explicit LRUCache(size_t capacity) : capacity_(capacity) {}
19
20
0
  void Put(const key_t& key, const value_t& value) {
21
0
    auto it = lookup_map_.find(key);
22
0
    if (it != lookup_map_.end()) {
23
0
      lru_list_.erase(it->second);
24
0
      lookup_map_.erase(it);
25
0
    }
26
27
0
    lru_list_.push_front(std::make_pair(key, value));
28
0
    lookup_map_[key] = lru_list_.begin();
29
30
0
    if (lookup_map_.size() > capacity_) {
31
0
      auto last = lru_list_.end();
32
0
      last--;
33
0
      lookup_map_.erase(last->first);
34
0
      lru_list_.pop_back();
35
0
    }
36
0
  }
37
38
0
  value_t& Get(const key_t& key) {
39
0
    auto it = lookup_map_.find(key);
40
0
    lru_list_.splice(lru_list_.begin(), lru_list_, it->second);
41
0
    return it->second->second;
42
0
  }
43
44
0
  void Erase(const key_t& key) {
45
0
    auto it = lookup_map_.find(key);
46
0
    if (it != lookup_map_.end()) {
47
0
      lru_list_.erase(it->second);
48
0
      lookup_map_.erase(it);
49
0
    }
50
0
  }
51
52
0
  bool Exists(const key_t& key) const { return lookup_map_.count(key) > 0; }
53
54
0
  size_t Size() const { return lookup_map_.size(); }
55
56
0
  size_t Capacity() const { return capacity_; }
57
58
0
  void Clear() {
59
0
    lru_list_.clear();
60
0
    lookup_map_.clear();
61
0
  }
62
63
 private:
64
  std::list<key_value_pair_t> lru_list_;
65
  std::unordered_map<key_t, iterator> lookup_map_;
66
  size_t capacity_;
67
};
68
69
#endif  // SRC_LRU_CACHE_INL_H_