2 using System.Diagnostics;
9 static class NetIdUtils
14 public static bool IdMoreRecent(ushort newID, ushort oldID)
20 (id1 > id2) && (id1 - id2 <= ushort.MaxValue / 2)
22 (id2 > id1) && (id2 - id1 > ushort.MaxValue / 2);
28 public static bool IdMoreRecentOrMatches(ushort newId, ushort oldId)
29 => !IdMoreRecent(oldId, newId);
35 public static ushort GetIdOlderThan(ushort
id)
38 => unchecked((ushort)(
id - 1 - Rand.Int(500, sync: Rand.RandSync.Unsynced)));
41 => unchecked((ushort)(
id - 1));
44 public static ushort Difference(ushort id1, ushort id2)
46 int diff = id2 > id1 ? id2 - id1 : id1 - id2;
47 return (ushort)(diff > ushort.MaxValue / 2 ? ushort.MaxValue - diff : diff);
50 public static ushort Clamp(ushort
id, ushort min, ushort max)
52 if (IdMoreRecent(min, max))
54 throw new ArgumentException($
"Min cannot be larger than max ({min}, {max})");
57 if (!IdMoreRecent(
id, min))
61 else if (IdMoreRecent(
id, max))
72 public static bool IsValidId(ushort currentId, ushort previousId, ushort latestPossibleId)
75 if (IdMoreRecent(currentId, latestPossibleId)) {
return false; }
81 return IdMoreRecent(currentId, previousId) || (previousId == 0 && currentId > ushort.MaxValue / 2);
85 public static void Test()
87 Debug.Assert(IdMoreRecent((ushort)2, (ushort)1));
88 Debug.Assert(IdMoreRecent((ushort)2, (ushort)(ushort.MaxValue - 5)));
89 Debug.Assert(!IdMoreRecent((ushort)ushort.MaxValue, (ushort)5));
91 Debug.Assert(Clamp((ushort)5, (ushort)1, (ushort)10) == 5);
92 Debug.Assert(Clamp((ushort)(ushort.MaxValue - 5), (ushort)(ushort.MaxValue - 2), (ushort)3) == (ushort)(ushort.MaxValue - 2));
94 Debug.Assert(IsValidId((ushort)10, (ushort)1, (ushort)10));
95 Debug.Assert(!IsValidId((ushort)11, (ushort)1, (ushort)10));
97 Debug.Assert(IsValidId((ushort)1, (ushort)(ushort.MaxValue - 5), (ushort)10));
98 Debug.Assert(!IsValidId((ushort)(ushort.MaxValue - 6), (ushort)(ushort.MaxValue - 5), (ushort)10));
100 Debug.Assert(IsValidId((ushort)0, (ushort)(ushort.MaxValue - 100), (ushort)5));
101 Debug.Assert(!IsValidId((ushort)(ushort.MaxValue - 101), (ushort)(ushort.MaxValue - 100), (ushort)ushort.MaxValue));
103 Debug.Assert(Difference((ushort)0, (ushort)56) == 56);
104 Debug.Assert(Difference((ushort)56, (ushort)0) == 56);
105 Debug.Assert(Difference((ushort)5, (ushort)(ushort.MaxValue - 101)) == 106);
106 Debug.Assert(Difference((ushort)(ushort.MaxValue - 101), (ushort)5) == 106);