OLD | NEW |
| (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 handler is notified when an item is evicted from the cache. | |
12 */ | |
13 typedef EvictionHandler<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 (both get and put) recently is evicted. | |
20 */ | |
21 class LRUCache<K, V> { | |
22 final LinkedHashSet<K> _lastKeys = new LinkedHashSet<K>(); | |
23 final HashMap<K, V> _map = new HashMap<K, V>(); | |
24 final int _maxSize; | |
25 final EvictionHandler _handler; | |
26 | |
27 LRUCache(this._maxSize, [this._handler]); | |
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.remove(key); | |
58 _lastKeys.add(key); | |
59 if (_lastKeys.length > _maxSize) { | |
60 K evictedKey = _lastKeys.first; | |
61 V evictedValue = _map.remove(evictedKey); | |
62 _lastKeys.remove(evictedKey); | |
63 if (_handler != null) { | |
64 _handler(evictedKey, evictedValue); | |
65 } | |
66 } | |
67 _map[key] = value; | |
68 } | |
69 } | |
OLD | NEW |