mru_cache.h 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. // Copyright (c) 2011 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. // This file contains a template for a Most Recently Used cache that allows
  5. // constant-time access to items using a key, but easy identification of the
  6. // least-recently-used items for removal. Each key can only be associated with
  7. // one payload item at a time.
  8. //
  9. // The key object will be stored twice, so it should support efficient copying.
  10. //
  11. // NOTE: While all operations are O(1), this code is written for
  12. // legibility rather than optimality. If future profiling identifies this as
  13. // a bottleneck, there is room for smaller values of 1 in the O(1). :]
  14. #ifndef BASE_CONTAINERS_MRU_CACHE_H_
  15. #define BASE_CONTAINERS_MRU_CACHE_H_
  16. #include <stddef.h>
  17. #include <algorithm>
  18. #include <functional>
  19. #include <list>
  20. #include <map>
  21. #include <unordered_map>
  22. #include <utility>
  23. #include "base/logging.h"
  24. #include "base/macros.h"
  25. namespace base {
  26. namespace trace_event {
  27. namespace internal {
  28. template <class MruCacheType>
  29. size_t DoEstimateMemoryUsageForMruCache(const MruCacheType&);
  30. } // namespace internal
  31. } // namespace trace_event
  32. // MRUCacheBase ----------------------------------------------------------------
  33. // This template is used to standardize map type containers that can be used
  34. // by MRUCacheBase. This level of indirection is necessary because of the way
  35. // that template template params and default template params interact.
  36. template <class KeyType, class ValueType, class CompareType>
  37. struct MRUCacheStandardMap {
  38. typedef std::map<KeyType, ValueType, CompareType> Type;
  39. };
  40. // Base class for the MRU cache specializations defined below.
  41. template <class KeyType,
  42. class PayloadType,
  43. class HashOrCompareType,
  44. template <typename, typename, typename> class MapType =
  45. MRUCacheStandardMap>
  46. class MRUCacheBase {
  47. public:
  48. // The payload of the list. This maintains a copy of the key so we can
  49. // efficiently delete things given an element of the list.
  50. typedef std::pair<KeyType, PayloadType> value_type;
  51. private:
  52. typedef std::list<value_type> PayloadList;
  53. typedef typename MapType<KeyType,
  54. typename PayloadList::iterator,
  55. HashOrCompareType>::Type KeyIndex;
  56. public:
  57. typedef typename PayloadList::size_type size_type;
  58. typedef typename PayloadList::iterator iterator;
  59. typedef typename PayloadList::const_iterator const_iterator;
  60. typedef typename PayloadList::reverse_iterator reverse_iterator;
  61. typedef typename PayloadList::const_reverse_iterator const_reverse_iterator;
  62. enum { NO_AUTO_EVICT = 0 };
  63. // The max_size is the size at which the cache will prune its members to when
  64. // a new item is inserted. If the caller wants to manager this itself (for
  65. // example, maybe it has special work to do when something is evicted), it
  66. // can pass NO_AUTO_EVICT to not restrict the cache size.
  67. explicit MRUCacheBase(size_type max_size) : max_size_(max_size) {}
  68. virtual ~MRUCacheBase() = default;
  69. size_type max_size() const { return max_size_; }
  70. // Inserts a payload item with the given key. If an existing item has
  71. // the same key, it is removed prior to insertion. An iterator indicating the
  72. // inserted item will be returned (this will always be the front of the list).
  73. //
  74. // The payload will be forwarded.
  75. template <typename Payload>
  76. iterator Put(const KeyType& key, Payload&& payload) {
  77. // Remove any existing payload with that key.
  78. typename KeyIndex::iterator index_iter = index_.find(key);
  79. if (index_iter != index_.end()) {
  80. // Erase the reference to it. The index reference will be replaced in the
  81. // code below.
  82. Erase(index_iter->second);
  83. } else if (max_size_ != NO_AUTO_EVICT) {
  84. // New item is being inserted which might make it larger than the maximum
  85. // size: kick the oldest thing out if necessary.
  86. ShrinkToSize(max_size_ - 1);
  87. }
  88. ordering_.emplace_front(key, std::forward<Payload>(payload));
  89. index_.emplace(key, ordering_.begin());
  90. return ordering_.begin();
  91. }
  92. // Retrieves the contents of the given key, or end() if not found. This method
  93. // has the side effect of moving the requested item to the front of the
  94. // recency list.
  95. iterator Get(const KeyType& key) {
  96. typename KeyIndex::iterator index_iter = index_.find(key);
  97. if (index_iter == index_.end())
  98. return end();
  99. typename PayloadList::iterator iter = index_iter->second;
  100. // Move the touched item to the front of the recency ordering.
  101. ordering_.splice(ordering_.begin(), ordering_, iter);
  102. return ordering_.begin();
  103. }
  104. // Retrieves the payload associated with a given key and returns it via
  105. // result without affecting the ordering (unlike Get).
  106. iterator Peek(const KeyType& key) {
  107. typename KeyIndex::const_iterator index_iter = index_.find(key);
  108. if (index_iter == index_.end())
  109. return end();
  110. return index_iter->second;
  111. }
  112. const_iterator Peek(const KeyType& key) const {
  113. typename KeyIndex::const_iterator index_iter = index_.find(key);
  114. if (index_iter == index_.end())
  115. return end();
  116. return index_iter->second;
  117. }
  118. // Exchanges the contents of |this| by the contents of the |other|.
  119. void Swap(MRUCacheBase& other) {
  120. ordering_.swap(other.ordering_);
  121. index_.swap(other.index_);
  122. std::swap(max_size_, other.max_size_);
  123. }
  124. // Erases the item referenced by the given iterator. An iterator to the item
  125. // following it will be returned. The iterator must be valid.
  126. iterator Erase(iterator pos) {
  127. index_.erase(pos->first);
  128. return ordering_.erase(pos);
  129. }
  130. // MRUCache entries are often processed in reverse order, so we add this
  131. // convenience function (not typically defined by STL containers).
  132. reverse_iterator Erase(reverse_iterator pos) {
  133. // We have to actually give it the incremented iterator to delete, since
  134. // the forward iterator that base() returns is actually one past the item
  135. // being iterated over.
  136. return reverse_iterator(Erase((++pos).base()));
  137. }
  138. // Shrinks the cache so it only holds |new_size| items. If |new_size| is
  139. // bigger or equal to the current number of items, this will do nothing.
  140. void ShrinkToSize(size_type new_size) {
  141. for (size_type i = size(); i > new_size; i--)
  142. Erase(rbegin());
  143. }
  144. // Deletes everything from the cache.
  145. void Clear() {
  146. index_.clear();
  147. ordering_.clear();
  148. }
  149. // Returns the number of elements in the cache.
  150. size_type size() const {
  151. // We don't use ordering_.size() for the return value because
  152. // (as a linked list) it can be O(n).
  153. DCHECK(index_.size() == ordering_.size());
  154. return index_.size();
  155. }
  156. // Allows iteration over the list. Forward iteration starts with the most
  157. // recent item and works backwards.
  158. //
  159. // Note that since these iterators are actually iterators over a list, you
  160. // can keep them as you insert or delete things (as long as you don't delete
  161. // the one you are pointing to) and they will still be valid.
  162. iterator begin() { return ordering_.begin(); }
  163. const_iterator begin() const { return ordering_.begin(); }
  164. iterator end() { return ordering_.end(); }
  165. const_iterator end() const { return ordering_.end(); }
  166. reverse_iterator rbegin() { return ordering_.rbegin(); }
  167. const_reverse_iterator rbegin() const { return ordering_.rbegin(); }
  168. reverse_iterator rend() { return ordering_.rend(); }
  169. const_reverse_iterator rend() const { return ordering_.rend(); }
  170. bool empty() const { return ordering_.empty(); }
  171. private:
  172. template <class MruCacheType>
  173. friend size_t trace_event::internal::DoEstimateMemoryUsageForMruCache(
  174. const MruCacheType&);
  175. PayloadList ordering_;
  176. KeyIndex index_;
  177. size_type max_size_;
  178. DISALLOW_COPY_AND_ASSIGN(MRUCacheBase);
  179. };
  180. // MRUCache --------------------------------------------------------------------
  181. // A container that does not do anything to free its data. Use this when storing
  182. // value types (as opposed to pointers) in the list.
  183. template <class KeyType,
  184. class PayloadType,
  185. class CompareType = std::less<KeyType>>
  186. class MRUCache : public MRUCacheBase<KeyType, PayloadType, CompareType> {
  187. private:
  188. using ParentType = MRUCacheBase<KeyType, PayloadType, CompareType>;
  189. public:
  190. // See MRUCacheBase, noting the possibility of using NO_AUTO_EVICT.
  191. explicit MRUCache(typename ParentType::size_type max_size)
  192. : ParentType(max_size) {}
  193. virtual ~MRUCache() = default;
  194. private:
  195. DISALLOW_COPY_AND_ASSIGN(MRUCache);
  196. };
  197. // HashingMRUCache ------------------------------------------------------------
  198. template <class KeyType, class ValueType, class HashType>
  199. struct MRUCacheHashMap {
  200. typedef std::unordered_map<KeyType, ValueType, HashType> Type;
  201. };
  202. // This class is similar to MRUCache, except that it uses std::unordered_map as
  203. // the map type instead of std::map. Note that your KeyType must be hashable to
  204. // use this cache or you need to provide a hashing class.
  205. template <class KeyType, class PayloadType, class HashType = std::hash<KeyType>>
  206. class HashingMRUCache
  207. : public MRUCacheBase<KeyType, PayloadType, HashType, MRUCacheHashMap> {
  208. private:
  209. using ParentType =
  210. MRUCacheBase<KeyType, PayloadType, HashType, MRUCacheHashMap>;
  211. public:
  212. // See MRUCacheBase, noting the possibility of using NO_AUTO_EVICT.
  213. explicit HashingMRUCache(typename ParentType::size_type max_size)
  214. : ParentType(max_size) {}
  215. virtual ~HashingMRUCache() = default;
  216. private:
  217. DISALLOW_COPY_AND_ASSIGN(HashingMRUCache);
  218. };
  219. } // namespace base
  220. #endif // BASE_CONTAINERS_MRU_CACHE_H_