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

Unified Diff: pkg/analysis_server/lib/src/index/lru_cache.dart

Issue 326123002: Node cache, binary search. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 6 years, 6 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
Index: pkg/analysis_server/lib/src/index/lru_cache.dart
diff --git a/pkg/analysis_server/lib/src/index/lru_cache.dart b/pkg/analysis_server/lib/src/index/lru_cache.dart
new file mode 100644
index 0000000000000000000000000000000000000000..f0b4581213ec1f91f9940792df524bb77b43368b
--- /dev/null
+++ b/pkg/analysis_server/lib/src/index/lru_cache.dart
@@ -0,0 +1,68 @@
+// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library index.lru_cache;
+
+import 'dart:collection';
+
+
+/**
+ * This listener is notified when an item is evicted from the cache.
+ */
+typedef EvictionListener<K, V>(K key, V value);
+
+/**
+ * A hash-table based cache implementation.
+ *
+ * When it reaches the specified number of items, the item that has not been
+ * accessed recently is evicted.
+ */
+class LRUCache<K, V> {
Brian Wilkerson 2014/06/10 17:08:29 There is also an LruCache in angular. Perhaps we s
+ final LinkedHashSet<K> _lastKeys = new LinkedHashSet<K>();
+ final HashMap<K, V> _map = new HashMap<K, V>();
+ final int _maxSize;
+ final EvictionListener _listener;
+
+ LRUCache(this._maxSize, [this._listener]);
+
+ /**
+ * Returns the value for the given [key] or null if [key] is not
+ * in the cache.
+ */
+ V get(K key) {
+ V value = _map[key];
+ if (value != null) {
+ _lastKeys.remove(key);
+ _lastKeys.add(key);
+ }
+ return value;
+ }
+
+ /**
+ * Removes the association for the given [key].
+ */
+ void remove(K key) {
+ _lastKeys.remove(key);
+ _map.remove(key);
+ }
+
+ /**
+ * Associates the [key] with the given [value].
+ *
+ * If the cache is full, an item that has not been accessed recently is
+ * evicted.
+ */
+ void put(K key, V value) {
+ _lastKeys.add(key);
+ if (_lastKeys.length > _maxSize) {
+ K evictedKey = _lastKeys.first;
+ V evictedValue = _map.remove(evictedKey);
+ _lastKeys.remove(evictedKey);
+ if (_listener != null) {
+ _listener(evictedKey, evictedValue);
+ }
+ }
+ _map[key] = value;
+ }
+}

Powered by Google App Engine
This is Rietveld 408576698