-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathLruHashSet.cs
More file actions
84 lines (70 loc) · 2.09 KB
/
LruHashSet.cs
File metadata and controls
84 lines (70 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System.Collections.Generic;
namespace Blockcore.Utilities
{
public class LruHashSet<T>
{
private readonly LinkedList<T> lru;
private HashSet<T> items;
private long maxSize;
private long itemCount;
private readonly object lockObject = new object();
public LruHashSet(long maxSize = long.MaxValue)
{
this.lru = new LinkedList<T>();
this.items = new HashSet<T>();
this.maxSize = maxSize;
this.itemCount = 0;
}
public void AddOrUpdate(T item)
{
lock (this.lockObject)
{
// First check if we are performing the 'Update' case. No change to item count.
if (this.items.Contains(item))
{
this.lru.Remove(item);
this.lru.AddLast(item);
return;
}
// Otherwise it's 'Add'.
// First perform the size test.
if ((this.itemCount + 1) > this.maxSize)
{
LinkedListNode<T> tempItem = this.lru.First;
this.lru.RemoveFirst();
this.items.Remove(tempItem.Value);
this.itemCount--;
}
this.lru.AddLast(item);
this.items.Add(item);
this.itemCount++;
}
}
public void Clear()
{
lock (this.lockObject)
{
this.lru.Clear();
this.items.Clear();
this.itemCount = 0;
}
}
public bool Contains(T item)
{
lock (this.lockObject)
{
// Fastest to check the hashmap.
return this.items.Contains(item);
}
}
public void Remove(T item)
{
lock (this.lockObject)
{
this.lru.Remove(item);
this.items.Remove(item);
this.itemCount--;
}
}
}
}