| 70 | } |
| 71 | |
| 72 | std::optional<value_type> get(const key_type& key) { |
| 73 | // lookup value in the cache |
| 74 | typename map_type::iterator value_for_key = map_.find(key); |
| 75 | if (value_for_key == map_.end()) { |
| 76 | // value not in cache |
| 77 | return std::nullopt; |
| 78 | } |
| 79 | |
| 80 | // return the value, but first update its place in the most |
| 81 | // recently used list |
| 82 | typename list_type::iterator position_in_lru_list = value_for_key->second.second; |
| 83 | if (position_in_lru_list != lru_list_.begin()) { |
| 84 | // move item to the front of the most recently used list |
| 85 | lru_list_.erase(position_in_lru_list); |
| 86 | lru_list_.push_front(key); |
| 87 | |
| 88 | // update iterator in map |
| 89 | position_in_lru_list = lru_list_.begin(); |
| 90 | const value_type& value = value_for_key->second.first; |
| 91 | map_[key] = std::make_pair(value, position_in_lru_list); |
| 92 | |
| 93 | // return the value |
| 94 | return value; |
| 95 | } else { |
| 96 | // the item is already at the front of the most recently |
| 97 | // used list so just return it |
| 98 | return value_for_key->second.first; |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | void clear() { |
| 103 | map_.clear(); |