Chromium Code Reviews| 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 LinkedHashSet<K> _lastKeys = new LinkedHashSet<K>(); | |
|
Brian Wilkerson
2015/02/26 22:29:57
Remove this?
| |
| 22 final LinkedHashMap<K, V> _map = new LinkedHashMap<K, V>(); | |
| 23 final int _maxSize; | |
| 24 final EvictionHandler _handler; | |
| 25 | |
| 26 LRUMap(this._maxSize, [this._handler]); | |
| 27 | |
| 28 /** | |
| 29 * Returns the value for the given [key] or null if [key] is not | |
| 30 * in the cache. | |
| 31 */ | |
| 32 V get(K key) { | |
| 33 V value = _map.remove(key); | |
| 34 if (value != null) { | |
| 35 _map[key] = value; | |
| 36 } | |
| 37 return value; | |
| 38 } | |
| 39 | |
| 40 /** | |
| 41 * Associates the [key] with the given [value]. | |
| 42 * | |
| 43 * If the cache is full, an item that has not been accessed recently is | |
| 44 * evicted. | |
| 45 */ | |
| 46 void put(K key, V value) { | |
| 47 _map.remove(key); | |
| 48 _map[key] = value; | |
| 49 if (_map.length > _maxSize) { | |
| 50 K evictedKey = _map.keys.first; | |
| 51 V evictedValue = _map.remove(evictedKey); | |
| 52 if (_handler != null) { | |
| 53 _handler(evictedKey, evictedValue); | |
| 54 } | |
| 55 } | |
| 56 } | |
| 57 | |
| 58 /** | |
| 59 * Removes the association for the given [key]. | |
| 60 */ | |
| 61 void remove(K key) { | |
| 62 _map.remove(key); | |
| 63 } | |
| 64 } | |
| OLD | NEW |