-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathTimestampRegistry.cs
More file actions
97 lines (86 loc) · 2.35 KB
/
Copy pathTimestampRegistry.cs
File metadata and controls
97 lines (86 loc) · 2.35 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
85
86
87
88
89
90
91
92
93
94
95
96
97
using EnumsNET;
namespace QuantumCore.API.Core.Timekeeping;
/// <summary>
/// Simple enum-indexed storage for optional server timestamps.
/// Made thread-safe using <see cref="System.Threading.Lock"/>.
/// </summary>
public sealed class TimestampRegistry<TKind> where TKind : struct, Enum
{
private static readonly int MaxEnumValue = Enums.GetValues<TKind>().Select(Enums.ToInt32).Max();
private readonly Lock _lock = new();
private readonly ServerTimestamp?[] _slots = new ServerTimestamp?[MaxEnumValue + 1];
public ServerTimestamp? this[TKind kind]
{
get => Get(kind);
set
{
if (value.HasValue)
{
Mark(kind, value.Value);
}
else
{
Clear(kind);
}
}
}
public void Mark(TKind kind, ServerTimestamp timestamp)
{
lock (_lock)
{
_slots[Enums.ToInt32(kind)] = timestamp;
}
}
public void Clear(TKind kind)
{
lock (_lock)
{
_slots[Enums.ToInt32(kind)] = null;
}
}
public bool UpdateIfElapsed(TickContext ctx, TKind kind, TimeSpan minimumElapsed)
{
// need lock for transactional update (check-then-act)
lock (_lock)
{
var ts = _slots[Enums.ToInt32(kind)];
if (ts.HasValue)
{
var tickTimestampOutsideGracePeriod = ctx.ElapsedSince(ts) > minimumElapsed;
if (tickTimestampOutsideGracePeriod)
{
_slots[Enums.ToInt32(kind)] = ctx.Timestamp;
return true;
}
}
else
{
_slots[Enums.ToInt32(kind)] = ctx.Timestamp;
}
return false;
}
}
public ServerTimestamp? Get(TKind kind)
{
lock (_lock)
{
return _slots[Enums.ToInt32(kind)];
}
}
public ServerTimestamp? LatestOf(params TKind[] kinds)
{
lock (_lock)
{
ServerTimestamp? latest = null;
foreach (var kind in kinds)
{
var ts = _slots[Enums.ToInt32(kind)];
if (ts > latest)
{
latest = ts;
}
}
return latest;
}
}
}