| | 1 | | using System.Collections.Generic; |
| | 2 | |
|
| | 3 | | namespace Itinero.Profiles.EdgeTypesMap; |
| | 4 | |
|
| | 5 | | internal class LruCache<K, V> |
| | 6 | | { |
| 0 | 7 | | private readonly Dictionary<K, LinkedListNode<LruCacheItem<K, V>>> _cacheMap = new(); |
| | 8 | | private readonly int _capacity; |
| 0 | 9 | | private readonly LinkedList<LruCacheItem<K, V>> _lruList = new(); |
| | 10 | |
|
| 0 | 11 | | public LruCache(int capacity) |
| 0 | 12 | | { |
| 0 | 13 | | _capacity = capacity; |
| 0 | 14 | | } |
| | 15 | |
|
| | 16 | | public bool TryGet(K key, out V? value) |
| 0 | 17 | | { |
| | 18 | | LinkedListNode<LruCacheItem<K, V>> node; |
| 0 | 19 | | if (!_cacheMap.TryGetValue(key, out node)) |
| 0 | 20 | | { |
| 0 | 21 | | value = default; |
| 0 | 22 | | return false; |
| | 23 | | } |
| | 24 | |
|
| 0 | 25 | | value = node.Value.value; |
| 0 | 26 | | _lruList.Remove(node); |
| 0 | 27 | | _lruList.AddLast(node); |
| 0 | 28 | | return true; |
| 0 | 29 | | } |
| | 30 | |
|
| | 31 | | public void Add(K key, V val) |
| 0 | 32 | | { |
| 0 | 33 | | if (_cacheMap.Count >= _capacity) |
| 0 | 34 | | { |
| 0 | 35 | | this.RemoveFirst(); |
| 0 | 36 | | } |
| | 37 | |
|
| 0 | 38 | | LruCacheItem<K, V> cacheItem = new(key, val); |
| 0 | 39 | | LinkedListNode<LruCacheItem<K, V>> node = new(cacheItem); |
| 0 | 40 | | _lruList.AddLast(node); |
| 0 | 41 | | _cacheMap.Add(key, node); |
| 0 | 42 | | } |
| | 43 | |
|
| | 44 | | private void RemoveFirst() |
| 0 | 45 | | { |
| | 46 | | // Remove from LRUPriority |
| 0 | 47 | | LinkedListNode<LruCacheItem<K, V>> node = _lruList.First; |
| 0 | 48 | | _lruList.RemoveFirst(); |
| | 49 | |
|
| | 50 | | // Remove from cache |
| 0 | 51 | | _cacheMap.Remove(node.Value.key); |
| 0 | 52 | | } |
| | 53 | |
|
| 0 | 54 | | public int Count => _cacheMap.Count; |
| | 55 | | } |
| | 56 | |
|
| | 57 | | internal class LruCacheItem<K, V> |
| | 58 | | { |
| | 59 | | public K key; |
| | 60 | | public V value; |
| | 61 | |
|
| | 62 | | public LruCacheItem(K k, V v) |
| | 63 | | { |
| | 64 | | key = k; |
| | 65 | | value = v; |
| | 66 | | } |
| | 67 | | } |