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

Side by Side 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 unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 library index.lru_cache;
6
7 import 'dart:collection';
8
9
10 /**
11 * This listener is notified when an item is evicted from the cache.
12 */
13 typedef EvictionListener<K, V>(K key, V value);
14
15 /**
16 * A hash-table based cache implementation.
17 *
18 * When it reaches the specified number of items, the item that has not been
19 * accessed recently is evicted.
20 */
21 class LRUCache<K, V> {
Brian Wilkerson 2014/06/10 17:08:29 There is also an LruCache in angular. Perhaps we s
22 final LinkedHashSet<K> _lastKeys = new LinkedHashSet<K>();
23 final HashMap<K, V> _map = new HashMap<K, V>();
24 final int _maxSize;
25 final EvictionListener _listener;
26
27 LRUCache(this._maxSize, [this._listener]);
28
29 /**
30 * Returns the value for the given [key] or null if [key] is not
31 * in the cache.
32 */
33 V get(K key) {
34 V value = _map[key];
35 if (value != null) {
36 _lastKeys.remove(key);
37 _lastKeys.add(key);
38 }
39 return value;
40 }
41
42 /**
43 * Removes the association for the given [key].
44 */
45 void remove(K key) {
46 _lastKeys.remove(key);
47 _map.remove(key);
48 }
49
50 /**
51 * Associates the [key] with the given [value].
52 *
53 * If the cache is full, an item that has not been accessed recently is
54 * evicted.
55 */
56 void put(K key, V value) {
57 _lastKeys.add(key);
58 if (_lastKeys.length > _maxSize) {
59 K evictedKey = _lastKeys.first;
60 V evictedValue = _map.remove(evictedKey);
61 _lastKeys.remove(evictedKey);
62 if (_listener != null) {
63 _listener(evictedKey, evictedValue);
64 }
65 }
66 _map[key] = value;
67 }
68 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698