diff --git a/Assets/Mirror/Runtime/Extensions.cs b/Assets/Mirror/Runtime/Extensions.cs index 0f6f62d70..2a5c3b94b 100644 --- a/Assets/Mirror/Runtime/Extensions.cs +++ b/Assets/Mirror/Runtime/Extensions.cs @@ -53,5 +53,16 @@ public static bool TryDequeue(this Queue source, out T element) return false; } #endif + + // helper function to trim a set to a max length + public static void Trim(this SortedSet set, int maxLength) + { + // make sure we don't deadlock for negative length + if (maxLength < 0) return; + + // remove while count > max + while (set.Count > maxLength) + set.Remove(set.Max); + } } } diff --git a/Assets/Mirror/Tests/Editor/ExtensionsTest.cs b/Assets/Mirror/Tests/Editor/ExtensionsTest.cs index ef1e0d8ab..85ac31542 100644 --- a/Assets/Mirror/Tests/Editor/ExtensionsTest.cs +++ b/Assets/Mirror/Tests/Editor/ExtensionsTest.cs @@ -22,5 +22,31 @@ public void CopyToList() source.CopyTo(destination); Assert.That(destination.SequenceEqual(source), Is.True); } + + [Test] + public void SortedSet_Trim() + { + SortedSet set = new SortedSet{1, 2, 3, 4, 5}; + + // larger than count + set.Trim(6); + Assert.That(set.SequenceEqual(new []{1, 2, 3, 4, 5})); + + // exactly count + set.Trim(5); + Assert.That(set.SequenceEqual(new []{1, 2, 3, 4, 5})); + + // smaller than count + set.Trim(3); + Assert.That(set.SequenceEqual(new []{1, 2, 3})); + + // negative should not deadlock + set.Trim(-1); + Assert.That(set.SequenceEqual(new []{1, 2, 3})); + + // zero + set.Trim(0); + Assert.That(set.SequenceEqual(new int[0])); + } } }