-
Notifications
You must be signed in to change notification settings - Fork 260
/
PruneIfNotUsedSinceLastPruneCache.cs
63 lines (51 loc) · 1.39 KB
/
PruneIfNotUsedSinceLastPruneCache.cs
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.Dafny.LanguageServer.Workspace;
namespace Microsoft.Dafny;
public class PruneIfNotUsedSinceLastPruneCache<TKey, TValue>
where TValue : class
where TKey : notnull {
class Item {
public Item(TValue value) {
Value = value;
Accessed = true;
}
public bool Accessed { get; set; }
public TValue Value { get; }
}
private readonly ConcurrentDictionary<TKey, Item> items;
public IEnumerable<TValue> Values => items.Select(i => i.Value.Value);
public int Count => items.Count;
public PruneIfNotUsedSinceLastPruneCache(IEqualityComparer<TKey> comparer) {
items = new(comparer);
}
public int Prune() {
var keys = items.Keys.ToList();
var removedCount = 0;
foreach (var key in keys) {
var item = items[key];
if (!item.Accessed) {
items.TryRemove(key, out _);
removedCount++;
}
item.Accessed = false;
}
return removedCount;
}
public void Set(TKey key, TValue value) {
items.TryAdd(key, new Item(value));
}
public bool TryGet(TKey key, out TValue? value) {
var result = items.TryGetValue(key, out var item);
if (result) {
value = item!.Value;
item.Accessed = true;
} else {
value = null;
}
return result;
}
}