Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(923)

Unified Diff: base/lru_bounded_cache.h

Issue 1868353003: Add an LRUBoundedCache class. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 4 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « base/base.gypi ('k') | base/lru_bounded_cache_unittest.cc » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: base/lru_bounded_cache.h
diff --git a/base/lru_bounded_cache.h b/base/lru_bounded_cache.h
new file mode 100644
index 0000000000000000000000000000000000000000..1420a16e54928d87ef8fcafea278634e964b9c4a
--- /dev/null
+++ b/base/lru_bounded_cache.h
@@ -0,0 +1,65 @@
+// Copyright 2016 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_LRU_BOUNDED_CACHE_H_
+#define BASE_LRU_BOUNDED_CACHE_H_
+
+#include <list>
+#include <map>
+
+#include "base/base_export.h"
+
+namespace base {
+
+// A cache that stores a bounded number of elements. When the bound is reached,
+// the least-recently-used element is removed to make room for a new element.
+// Inserting an element makes it the most-recently-used element.
+template <typename T>
+class BASE_EXPORT LRUBoundedCache {
+ private:
+ typedef std::list<T> ListType;
+ typedef std::map<T, typename ListType::iterator> MapType;
+
+ public:
+ LRUBoundedCache(size_t max_element_count) :
+ max_element_count_(max_element_count) {
+ }
+
+ // Inserts |x| into the cache, and makes it the most recently used element.
+ // Returns whether or not |x| was already in the cache.
+ bool Insert(const T& x) {
+ auto i = pos_.find(x);
+ bool was_in_cache = pos_.end() != i;
+ if (was_in_cache) {
+ lru_.erase(pos_[x]);
+ } else {
+ if (pos_.size() == max_element_count_) {
+ const T& back = lru_.back();
+ pos_.erase(back);
+ lru_.pop_back();
+ }
+ }
+ lru_.push_front(x);
+ pos_[x] = lru_.begin();
+ return was_in_cache;
+ }
+
+ size_t Size() const {
+ return pos_.size();
+ }
+
+ private:
+ // List of elements, most recently used first.
+ ListType lru_;
+
+ // Maps element values to positions in the list so that we can quickly remove
+ // elements.
+ MapType pos_;
+
+ const size_t max_element_count_;
+};
+
+} // namespace base
+
+#endif // BASE_LRU_BOUNDED_CACHE_H_
« no previous file with comments | « base/base.gypi ('k') | base/lru_bounded_cache_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698