1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.ComponentModel;
|
---|
4 | using System.Linq;
|
---|
5 | using System.Text;
|
---|
6 | using System.Threading.Tasks;
|
---|
7 |
|
---|
8 | namespace HeuristicLab.Common {
|
---|
9 | public class MostRecentlyUsedCache<TKey, TValue> {
|
---|
10 |
|
---|
11 | private LinkedList<KeyValuePair<TKey, TValue>> lruList;
|
---|
12 | private Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> dictionary;
|
---|
13 | private int maxCapacity;
|
---|
14 |
|
---|
15 | public MostRecentlyUsedCache(int maxCapacity) {
|
---|
16 | this.maxCapacity = maxCapacity;
|
---|
17 | lruList = new LinkedList<KeyValuePair<TKey, TValue>>();
|
---|
18 | dictionary = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(maxCapacity);
|
---|
19 | }
|
---|
20 |
|
---|
21 | // drops the least-recently used element if necessary
|
---|
22 | public void Add(TKey key, TValue value) {
|
---|
23 | if (lruList.Count >= maxCapacity) {
|
---|
24 | dictionary.Remove(lruList.Last.Value.Key);
|
---|
25 | lruList.RemoveLast();
|
---|
26 | }
|
---|
27 | lruList.AddFirst(new KeyValuePair<TKey, TValue>(key, value));
|
---|
28 | dictionary.Add(key, lruList.First);
|
---|
29 | }
|
---|
30 |
|
---|
31 | public bool TryGetValue(TKey key, out TValue value) {
|
---|
32 | // find matching element
|
---|
33 | LinkedListNode<KeyValuePair<TKey, TValue>> node = null;
|
---|
34 | if (!dictionary.TryGetValue(key, out node)) {
|
---|
35 | value = default(TValue);
|
---|
36 | return false;
|
---|
37 | } else {
|
---|
38 | lruList.Remove(node);
|
---|
39 | lruList.AddFirst(node);
|
---|
40 | value = node.Value.Value;
|
---|
41 | return true;
|
---|
42 | }
|
---|
43 | }
|
---|
44 | }
|
---|
45 | }
|
---|