From 2558f579342c4e28509b726e55c3d65a3111a54d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Lema=C5=84czyk?= Date: Sun, 5 Mar 2023 18:51:06 +0100 Subject: [PATCH] RecyclableList.Remove modified to allow removing the last item. --- Recyclable.Collections/RecyclableList.cs | 13 ++++++++++- .../RecyclableListTests.cs | 23 ++++++++++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/Recyclable.Collections/RecyclableList.cs b/Recyclable.Collections/RecyclableList.cs index 87ed1ea..cb8b308 100644 --- a/Recyclable.Collections/RecyclableList.cs +++ b/Recyclable.Collections/RecyclableList.cs @@ -569,7 +569,18 @@ namespace Recyclable.Collections ? Array.IndexOf(_memoryBlocks[0], item, 0, (int)_longCount) : DoIndexOf(item, _memoryBlocks, _lastBlockIndex, _blockSize, _nextItemIndex); - public bool Remove(T item) => throw new NotSupportedException(); + public bool Remove(T item) + { + var itemIndex = LongIndexOf(item); + if (itemIndex >= 0) + { + RemoveAt(this, itemIndex, _defaultBlockArrayPool); + return true; + } + + return false; + } + public void RemoveBlock(int index) { if (_blockSize < RecyclableDefaults.MinPooledArrayLength) diff --git a/Recyclable.CollectionsTests/RecyclableListTests.cs b/Recyclable.CollectionsTests/RecyclableListTests.cs index d0ced6d..3089573 100644 --- a/Recyclable.CollectionsTests/RecyclableListTests.cs +++ b/Recyclable.CollectionsTests/RecyclableListTests.cs @@ -186,6 +186,27 @@ namespace Recyclable.CollectionsTests _ = Assert.Throws(() => list.Insert(0, -1)); } + [Fact] + public void RemoveShouldRemoveLastItem() + { + // Prepare + using var list = NewRecyclableList; + + int removedCount = 0; + var testData = _testData.ToArray(); + foreach (var item in _testData.Reverse()) + { + // Act & Validate + _ = list.Remove(item).Should().BeTrue($"we search for {item} which should exist"); + removedCount++; + var expectedList = testData[0..(testData.Length - removedCount)]; + _ = list.LongCount.Should().Be(expectedList.Length); + _ = list.Should().ContainInConsecutiveOrder(expectedList); + } + + _ = list.Should().BeEmpty(); + } + [Fact] public void RemoveShouldRaiseNotSupportedException() { @@ -193,7 +214,7 @@ namespace Recyclable.CollectionsTests using var list = NewRecyclableList; // Act - _ = Assert.Throws(() => list.Remove(_testData.First())); + _ = Assert.Throws(() => list.Remove(_testData.First())); } [Fact]