OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 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 MEDIA_BLINK_LRU_H_ |
| 6 #define MEDIA_BLINK_LRU_H_ |
| 7 |
| 8 #include <list> |
| 9 #include "base/containers/hash_tables.h" |
| 10 |
| 11 namespace media { |
| 12 |
| 13 template <typename T> |
| 14 class LRU { |
| 15 public: |
| 16 // Adds |x| to LRU. |
| 17 // |x| must not already be in the LRU. |
| 18 void Insert(const T& x) { |
| 19 DCHECK(!Contains(x)); |
| 20 lru_.push_front(x); |
| 21 pos_[x] = lru_.begin(); |
| 22 } |
| 23 |
| 24 // Removes |x| from LRU. |
| 25 // |x| must be in the LRU. |
| 26 void Remove(const T& x) { |
| 27 DCHECK(Contains(x)); |
| 28 lru_.erase(pos_[x]); |
| 29 pos_.erase(x); |
| 30 } |
| 31 |
| 32 // Moves |x| to front of LRU. (most recently used) |
| 33 // If |x| is not in LRU, it is added. |
| 34 void Use(const T& x) { |
| 35 if (Contains(x)) |
| 36 Remove(x); |
| 37 Insert(x); |
| 38 } |
| 39 |
| 40 bool Empty() const { return lru_.empty(); } |
| 41 |
| 42 // Returns the Least Recently Used T. |
| 43 T Pop() { |
| 44 DCHECK(!Empty()); |
| 45 T ret = lru_.back(); |
| 46 lru_.pop_back(); |
| 47 pos_.erase(ret); |
| 48 return ret; |
| 49 } |
| 50 |
| 51 T Peek() const { |
| 52 DCHECK(!Empty()); |
| 53 return lru_.back(); |
| 54 } |
| 55 |
| 56 bool Contains(const T& x) const { return pos_.find(x) != pos_.end(); } |
| 57 |
| 58 size_t Size() const { return pos_.size(); } |
| 59 |
| 60 private: |
| 61 std::list<T> lru_; |
| 62 base::hash_map<T, typename std::list<T>::iterator> pos_; |
| 63 }; |
| 64 |
| 65 } // namespace media |
| 66 |
| 67 #endif // MEDIA_BLINK_LRU_H |
OLD | NEW |