Files
FlClash/lib/common/fixed.dart
T

74 lines
1.3 KiB
Dart
Raw Normal View History

import 'iterable.dart';
2025-06-07 01:48:34 +08:00
typedef ValueCallback<T> = T Function();
class FixedList<T> {
final int maxLength;
final List<T> _list;
FixedList(this.maxLength, {List<T>? list})
2026-05-27 15:16:51 +08:00
: _list = (list ?? [])..truncate(maxLength);
2025-06-07 01:48:34 +08:00
void add(T item) {
_list.add(item);
_list.truncate(maxLength);
}
2025-06-07 01:48:34 +08:00
void clear() {
_list.clear();
}
List<T> get list => List.unmodifiable(_list);
int get length => _list.length;
T operator [](int index) => _list[index];
FixedList<T> copyWith() {
2026-05-27 15:16:51 +08:00
return FixedList(maxLength, list: List.of(_list));
}
}
class FixedMap<K, V> {
int maxLength;
late Map<K, V> _map;
FixedMap(this.maxLength, {Map<K, V>? map}) {
_map = map ?? {};
}
2025-06-07 01:48:34 +08:00
V updateCacheValue(K key, ValueCallback<V> callback) {
2026-05-27 15:16:51 +08:00
final realValue = _map.updateCacheValue(key, callback);
_adjustMap();
return realValue;
}
2025-06-07 01:48:34 +08:00
void clear() {
_map.clear();
}
2025-06-07 01:48:34 +08:00
void updateMaxLength(int size) {
maxLength = size;
_adjustMap();
}
2025-06-07 01:48:34 +08:00
void updateMap(Map<K, V> map) {
_map = map;
_adjustMap();
}
2025-06-07 01:48:34 +08:00
void _adjustMap() {
if (_map.length > maxLength) {
2026-05-27 15:16:51 +08:00
_map = Map.fromEntries(map.entries.toList()..truncate(maxLength));
}
}
V? get(K key) => _map[key];
bool containsKey(K key) => _map.containsKey(key);
int get length => _map.length;
Map<K, V> get map => Map.unmodifiable(_map);
}