OLD | NEW |
| (Empty) |
1 // Copyright (c) 2015, 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 engine.utilities.lru_cache; | |
6 | |
7 import 'dart:collection'; | |
8 | |
9 /** | |
10 * This handler is notified when an item is evicted from the cache. | |
11 */ | |
12 typedef EvictionHandler<K, V>(K key, V value); | |
13 | |
14 /** | |
15 * A hash-table based cache implementation. | |
16 * | |
17 * When it reaches the specified number of items, the item that has not been | |
18 * accessed (both get and put) recently is evicted. | |
19 */ | |
20 class LRUMap<K, V> { | |
21 final LinkedHashMap<K, V> _map = new LinkedHashMap<K, V>(); | |
22 final int _maxSize; | |
23 final EvictionHandler _handler; | |
24 | |
25 LRUMap(this._maxSize, [this._handler]); | |
26 | |
27 /** | |
28 * Returns the value for the given [key] or null if [key] is not | |
29 * in the cache. | |
30 */ | |
31 V get(K key) { | |
32 V value = _map.remove(key); | |
33 if (value != null) { | |
34 _map[key] = value; | |
35 } | |
36 return value; | |
37 } | |
38 | |
39 /** | |
40 * Associates the [key] with the given [value]. | |
41 * | |
42 * If the cache is full, an item that has not been accessed recently is | |
43 * evicted. | |
44 */ | |
45 void put(K key, V value) { | |
46 _map.remove(key); | |
47 _map[key] = value; | |
48 if (_map.length > _maxSize) { | |
49 K evictedKey = _map.keys.first; | |
50 V evictedValue = _map.remove(evictedKey); | |
51 if (_handler != null) { | |
52 _handler(evictedKey, evictedValue); | |
53 } | |
54 } | |
55 } | |
56 | |
57 /** | |
58 * Removes the association for the given [key]. | |
59 */ | |
60 void remove(K key) { | |
61 _map.remove(key); | |
62 } | |
63 } | |
OLD | NEW |