OLD | NEW |
(Empty) | |
| 1 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #ifndef BASE_LRU_BOUNDED_CACHE_H_ |
| 6 #define BASE_LRU_BOUNDED_CACHE_H_ |
| 7 |
| 8 #include <list> |
| 9 #include <map> |
| 10 |
| 11 #include "base/base_export.h" |
| 12 |
| 13 namespace base { |
| 14 |
| 15 // A cache that stores a bounded number of elements. When the bound is reached, |
| 16 // the least-recently-used element is removed to make room for a new element. |
| 17 // Inserting an element makes it the most-recently-used element. |
| 18 template <typename T> |
| 19 class BASE_EXPORT LRUBoundedCache { |
| 20 private: |
| 21 typedef std::list<T> ListType; |
| 22 typedef std::map<T, typename ListType::iterator> MapType; |
| 23 |
| 24 public: |
| 25 LRUBoundedCache(size_t max_element_count) : |
| 26 max_element_count_(max_element_count) { |
| 27 } |
| 28 |
| 29 // Inserts |x| into the cache, and makes it the most recently used element. |
| 30 // Returns whether or not |x| was already in the cache. |
| 31 bool Insert(const T& x) { |
| 32 auto i = pos_.find(x); |
| 33 bool was_in_cache = pos_.end() != i; |
| 34 if (was_in_cache) { |
| 35 lru_.erase(pos_[x]); |
| 36 } else { |
| 37 if (pos_.size() == max_element_count_) { |
| 38 const T& back = lru_.back(); |
| 39 pos_.erase(back); |
| 40 lru_.pop_back(); |
| 41 } |
| 42 } |
| 43 lru_.push_front(x); |
| 44 pos_[x] = lru_.begin(); |
| 45 return was_in_cache; |
| 46 } |
| 47 |
| 48 size_t Size() const { |
| 49 return pos_.size(); |
| 50 } |
| 51 |
| 52 private: |
| 53 // List of elements, most recently used first. |
| 54 ListType lru_; |
| 55 |
| 56 // Maps element values to positions in the list so that we can quickly remove |
| 57 // elements. |
| 58 MapType pos_; |
| 59 |
| 60 const size_t max_element_count_; |
| 61 }; |
| 62 |
| 63 } // namespace base |
| 64 |
| 65 #endif // BASE_LRU_BOUNDED_CACHE_H_ |
OLD | NEW |