From 1db7fed92d709009215d0bf6bbefe4234e9d65a9 Mon Sep 17 00:00:00 2001 From: ikpil Date: Thu, 8 Feb 2024 00:22:32 +0900 Subject: [PATCH] fix: RcSortedQueue.Remove can not use binary-search --- .../Collections/RcSortedQueue.cs | 4 +-- test/DotRecast.Core.Test/RcSortedQueueTest.cs | 35 +++++++++++++++++-- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/DotRecast.Core/Collections/RcSortedQueue.cs b/src/DotRecast.Core/Collections/RcSortedQueue.cs index db6d4ab..3d35193 100644 --- a/src/DotRecast.Core/Collections/RcSortedQueue.cs +++ b/src/DotRecast.Core/Collections/RcSortedQueue.cs @@ -81,8 +81,8 @@ namespace DotRecast.Core.Collections public bool Remove(T item) { - Balance(); - int idx = _items.BinarySearch(item, _comparer); + //int idx = _items.BinarySearch(item, _comparer); // don't use this! Because reference types can be reused externally. + int idx = _items.FindLastIndex(x => item.Equals(x)); if (0 > idx) return false; diff --git a/test/DotRecast.Core.Test/RcSortedQueueTest.cs b/test/DotRecast.Core.Test/RcSortedQueueTest.cs index e08943b..537d711 100644 --- a/test/DotRecast.Core.Test/RcSortedQueueTest.cs +++ b/test/DotRecast.Core.Test/RcSortedQueueTest.cs @@ -1,7 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Linq; using DotRecast.Core.Collections; using NUnit.Framework; @@ -51,7 +50,7 @@ public class RcSortedQueueTest } [Test] - public void TestRemove() + public void TestRemoveForValueType() { var sortedQueue = new RcSortedQueue((a, b) => a.CompareTo(b)); @@ -80,4 +79,36 @@ public class RcSortedQueueTest Assert.That(sortedQueue.IsEmpty(), Is.True); } + + [Test] + public void TestRemoveForReferenceType() + { + var sortedQueue = new RcSortedQueue((a, b) => a.Read().CompareTo(b.Read())); + + var r = new RcRand(); + var expectedList = new List(); + for (int i = 0; i < 999; ++i) + { + expectedList.Add(new RcAtomicLong(r.NextInt32() % 300)); // allow duplication + } + + // ready + foreach (var expected in expectedList) + { + sortedQueue.Enqueue(expected); + } + + expectedList.Shuffle(); + + // check + Assert.That(sortedQueue.Count(), Is.EqualTo(expectedList.Count)); + + foreach (var expected in expectedList) + { + Assert.That(sortedQueue.Remove(expected), Is.True); + } + + Assert.That(sortedQueue.IsEmpty(), Is.True); + } + } \ No newline at end of file