| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2017, 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 import 'dart:collection'; |
| 6 |
| 7 /** |
| 8 * LRU cache of objects. |
| 9 */ |
| 10 class Cache<K, V> { |
| 11 final int _maxSizeBytes; |
| 12 final int Function(V) _meter; |
| 13 |
| 14 final _map = new LinkedHashMap<K, V>(); |
| 15 int _currentSizeBytes = 0; |
| 16 |
| 17 Cache(this._maxSizeBytes, this._meter); |
| 18 |
| 19 V get(K key, V getNotCached()) { |
| 20 V value = _map.remove(key); |
| 21 if (value == null) { |
| 22 value = getNotCached(); |
| 23 if (value != null) { |
| 24 _map[key] = value; |
| 25 _currentSizeBytes += _meter(value); |
| 26 _evict(); |
| 27 } |
| 28 } else { |
| 29 _map[key] = value; |
| 30 } |
| 31 return value; |
| 32 } |
| 33 |
| 34 void put(K key, V value) { |
| 35 V oldValue = _map[key]; |
| 36 if (oldValue != null) { |
| 37 _currentSizeBytes -= _meter(oldValue); |
| 38 } |
| 39 _map[key] = value; |
| 40 _currentSizeBytes += _meter(value); |
| 41 _evict(); |
| 42 } |
| 43 |
| 44 void _evict() { |
| 45 while (_currentSizeBytes > _maxSizeBytes) { |
| 46 if (_map.isEmpty) { |
| 47 // Should be impossible, since _currentSizeBytes should always match |
| 48 // _map. But recover anyway. |
| 49 assert(false); |
| 50 _currentSizeBytes = 0; |
| 51 break; |
| 52 } |
| 53 K key = _map.keys.first; |
| 54 V value = _map.remove(key); |
| 55 _currentSizeBytes -= _meter(value); |
| 56 } |
| 57 } |
| 58 } |
| OLD | NEW |