namespace Titano.Ui.Visuals;
/// Fixed-capacity map that evicts the least recently used entry (decoded thumbnails).
public sealed class LruCache
where TKey : notnull
{
private readonly Dictionary>> _map;
private readonly LinkedList> _order = new();
private int _capacity;
public LruCache(int capacity)
{
ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1);
_capacity = capacity;
_map = new Dictionary>>(capacity);
}
public int Count => _map.Count;
/// Maximum entries; lowering it evicts the oldest entries at once.
public int Capacity
{
get => _capacity;
set
{
ArgumentOutOfRangeException.ThrowIfLessThan(value, 1);
_capacity = value;
Trim();
}
}
/// Looks up and marks it as the most recently used.
public bool TryGet(TKey key, out TValue value)
{
if (_map.TryGetValue(key, out var node))
{
_order.Remove(node);
_order.AddFirst(node);
value = node.Value.Value;
return true;
}
value = default!;
return false;
}
/// Inserts or replaces as the most recently used entry.
public void Set(TKey key, TValue value)
{
if (_map.TryGetValue(key, out var node))
{
_order.Remove(node);
node.Value = new KeyValuePair(key, value);
_order.AddFirst(node);
return;
}
_map[key] = _order.AddFirst(new KeyValuePair(key, value));
Trim();
}
public bool Remove(TKey key)
{
if (!_map.Remove(key, out var node)) return false;
_order.Remove(node);
return true;
}
public void Clear()
{
_map.Clear();
_order.Clear();
}
private void Trim()
{
while (_map.Count > _capacity && _order.Last is { } oldest)
{
_order.RemoveLast();
_map.Remove(oldest.Value.Key);
}
}
}