ente/lib/core/cache/lru_map.dart

36 lines
761 B
Dart
Raw Normal View History

2020-03-24 19:59:36 +00:00
import 'dart:collection';
2021-07-22 18:41:58 +00:00
typedef EvictionHandler<K, V> = Function(K key, V value);
2020-03-24 19:59:36 +00:00
class LRUMap<K, V> {
2021-07-22 18:41:58 +00:00
final LinkedHashMap<K, V> _map = LinkedHashMap<K, V>();
2020-03-24 19:59:36 +00:00
final int _maxSize;
2022-09-21 11:39:39 +00:00
final EvictionHandler<K, V?>? _handler;
2020-03-24 19:59:36 +00:00
LRUMap(this._maxSize, [this._handler]);
2022-09-21 11:39:39 +00:00
V? get(K key) {
final V? value = _map.remove(key);
2020-03-24 19:59:36 +00:00
if (value != null) {
_map[key] = value;
}
return value;
}
void put(K key, V value) {
_map.remove(key);
_map[key] = value;
if (_map.length > _maxSize) {
2022-08-29 14:43:31 +00:00
final K evictedKey = _map.keys.first;
2022-09-21 11:39:39 +00:00
final V? evictedValue = _map.remove(evictedKey);
2020-03-24 19:59:36 +00:00
if (_handler != null) {
2022-09-21 11:39:39 +00:00
_handler!(evictedKey, evictedValue);
2020-03-24 19:59:36 +00:00
}
}
}
void remove(K key) {
_map.remove(key);
}
}