diff --git a/Recyclable.Collections/RecyclableLongList.cs b/Recyclable.Collections/RecyclableLongList.cs index b316a72..2989c32 100644 --- a/Recyclable.Collections/RecyclableLongList.cs +++ b/Recyclable.Collections/RecyclableLongList.cs @@ -837,24 +837,60 @@ namespace Recyclable.Collections public void Insert(int index, T item) { - if (index > _longCount++ || index < 0) + if (index > _longCount || index < 0) { - _longCount--; Helpers.ThrowIndexOutOfRangeException($"Argument \"{nameof(index)}\" = {index} is out of range. Expected value between 0 and {_longCount}"); } - if (_capacity < _longCount) + if (_capacity < ++_longCount) { _capacity = Helpers.Resize(this, _blockSize, _blockSizePow2BitShift, checked((long)BitOperations.RoundUpToPowerOf2((ulong)_longCount))); } - if (_longCount > 1) + if (index + 1 < _longCount) { Helpers.MakeRoomAndSet(this, index, item); } else { - new Span(_memoryBlocks[0])[0] = item; + new Span(_memoryBlocks[_nextItemBlockIndex])[_nextItemIndex] = item; + } + + if (_nextItemIndex < _blockSizeMinus1) + { + if (++_nextItemIndex == 1) + { + _lastBlockWithData++; + } + } + else + { + _nextItemIndex = 0; + _nextItemBlockIndex++; + } + + _version++; + } + + public void Insert(long index, T item) + { + if (index > _longCount || index < 0) + { + Helpers.ThrowIndexOutOfRangeException($"Argument \"{nameof(index)}\" = {index} is out of range. Expected value between 0 and {_longCount}"); + } + + if (_capacity < ++_longCount) + { + _capacity = Helpers.Resize(this, _blockSize, _blockSizePow2BitShift, checked((long)BitOperations.RoundUpToPowerOf2((ulong)_longCount))); + } + + if (index + 1 < _longCount) + { + Helpers.MakeRoomAndSet(this, index, item); + } + else + { + new Span(_memoryBlocks[_nextItemBlockIndex])[_nextItemIndex] = item; } if (_nextItemIndex < _blockSizeMinus1) diff --git a/Recyclable.CollectionsTests/RecyclableLongListTests.cs b/Recyclable.CollectionsTests/RecyclableLongListTests.cs index 7720fde..2def464 100644 --- a/Recyclable.CollectionsTests/RecyclableLongListTests.cs +++ b/Recyclable.CollectionsTests/RecyclableLongListTests.cs @@ -530,13 +530,19 @@ namespace Recyclable.CollectionsTests [Theory] [MemberData(nameof(RecyclableLongListTestData.SourceTargetDataVariants), MemberType = typeof(RecyclableLongListTestData))] - public void InsertShouldRaiseNotSupportedException(string testCase, IEnumerable testData, long itemsCount, int targetBlockSize) + public void InsertAtTheEndShouldAppend(string testCase, IEnumerable testData, long itemsCount, int targetBlockSize) { // Prepare using var list = new RecyclableLongList(testData, minBlockSize: targetBlockSize); // Act - _ = Assert.Throws(() => list.Insert(0, -1)); + list.Insert(itemsCount, -1); + + // Assert + list.LongCount.Should().Be(itemsCount + 1); + list.LongCount.Should().Be(list.Count); + list[list.LongCount - 1].Should().Be(-1); + } [Fact]