|
| 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 | + |
| 14 | + explicit LruCache(size_t capacity) : capacity_(capacity) {} |
| 15 | + |
| 16 | + void put(const key_t& key, const value_t& value) { |
| 17 | + auto it = lookup_map_.find(key); |
| 18 | + if (it != lookup_map_.end()) { |
| 19 | + lru_list_.erase(it->second); |
| 20 | + lookup_map_.erase(it); |
| 21 | + } |
| 22 | + |
| 23 | + lru_list_.push_front(std::make_pair(key, value)); |
| 24 | + lookup_map_[key] = lru_list_.begin(); |
| 25 | + |
| 26 | + if (lookup_map_.size() > capacity_) { |
| 27 | + auto last = lru_list_.end(); |
| 28 | + last--; |
| 29 | + lookup_map_.erase(last->first); |
| 30 | + lru_list_.pop_back(); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + value_t& get(const key_t& key) { |
| 35 | + auto it = lookup_map_.find(key); |
| 36 | + lru_list_.splice(lru_list_.begin(), lru_list_, |
| 37 | + it->second); |
| 38 | + return it->second->second; |
| 39 | + } |
| 40 | + |
| 41 | + void erase(const key_t& key) { |
| 42 | + auto it = lookup_map_.find(key); |
| 43 | + if (it != lookup_map_.end()) { |
| 44 | + lru_list_.erase(it->second); |
| 45 | + lookup_map_.erase(it); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + bool exists(const key_t& key) const { |
| 50 | + return lookup_map_.count(key) > 0; |
| 51 | + } |
| 52 | + |
| 53 | + size_t size() const { |
| 54 | + return lookup_map_.size(); |
| 55 | + } |
| 56 | + |
| 57 | + private: |
| 58 | + std::list<key_value_pair_t> lru_list_; |
| 59 | + std::unordered_map<key_t, iterator> lookup_map_; |
| 60 | + size_t capacity_; |
| 61 | +}; |
| 62 | + |
| 63 | +#endif // SRC_LRU_CACHE_INL_H_ |
| 64 | + |
0 commit comments