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

Side by Side Diff: pkg/front_end/lib/src/byte_store/cache.dart

Issue 2998363002: Generalize LRU Cache to any objects. (Closed)
Patch Set: Created 3 years, 3 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
OLDNEW
(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 }
OLDNEW
« no previous file with comments | « pkg/front_end/lib/src/byte_store/byte_store.dart ('k') | pkg/front_end/test/src/byte_store/byte_store_test.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698