Implement recyclable sorted list using pooled arrays
This commit is contained in:
1 parent
9aa96ccb19
commit
0d28f6515d
2 files changed
+357
-154
No files matched your search
@@ -1,81 +1,280 @@
|
|||||||
using Recyclable.Collections.Linq;
|
using System.Collections;
|
||||||
|
using System.Numerics;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using Recyclable.Collections.Pools;
|
||||||
|
|
||||||
namespace Recyclable.Collections
|
namespace Recyclable.Collections
|
||||||
{
|
{
|
||||||
internal class RecyclableSortedList<TKey, TValue> : RecyclableLongList<(TKey Key, TValue Value)>
|
internal sealed class RecyclableSortedList<TKey, TValue> : IEnumerable<(TKey Key, TValue Value)>, IDisposable
|
||||||
where TKey : notnull
|
where TKey : notnull
|
||||||
{
|
{
|
||||||
private static readonly IComparer<(TKey, TValue)> _comparer = new FrequencyTupleComparer<TKey, TValue>();
|
private static readonly bool _needsClearing = !typeof(TKey).IsValueType || !typeof(TValue).IsValueType;
|
||||||
private uint _isUpdating;
|
|
||||||
private readonly SystemRandomNumberGenerator _randomNumberGenerator = new();
|
|
||||||
|
|
||||||
protected void ListUpdated()
|
private TKey[] _keys;
|
||||||
{
|
private TValue[] _values;
|
||||||
QuickSort();
|
private int _count;
|
||||||
}
|
private readonly IComparer<TKey> _comparer;
|
||||||
|
private bool _disposed;
|
||||||
|
|
||||||
public RecyclableSortedList() : base()
|
public RecyclableSortedList(int initialCapacity = RecyclableDefaults.InitialCapacity, IComparer<TKey>? comparer = null)
|
||||||
{
|
{
|
||||||
}
|
if (initialCapacity < 1)
|
||||||
|
{
|
||||||
|
initialCapacity = 1;
|
||||||
|
}
|
||||||
|
|
||||||
public RecyclableSortedList(Dictionary<TKey, TValue> source, int blockSize = RecyclableDefaults.BlockSize)
|
if (!BitOperations.IsPow2((uint)initialCapacity))
|
||||||
: this(source.Select(x => (x.Key, x.Value)), blockSize)
|
{
|
||||||
{
|
initialCapacity = (int)BitOperations.RoundUpToPowerOf2((uint)initialCapacity);
|
||||||
}
|
}
|
||||||
|
|
||||||
public RecyclableSortedList(IEnumerable<(TKey Key, TValue Value)> source, int blockSize = RecyclableDefaults.BlockSize)
|
_keys = initialCapacity >= RecyclableDefaults.MinPooledArrayLength
|
||||||
: base(source, blockSize)
|
? RecyclableArrayPool<TKey>.RentShared(initialCapacity)
|
||||||
{
|
: new TKey[initialCapacity];
|
||||||
QuickSort();
|
_values = initialCapacity >= RecyclableDefaults.MinPooledArrayLength
|
||||||
}
|
? RecyclableArrayPool<TValue>.RentShared(initialCapacity)
|
||||||
|
: new TValue[initialCapacity];
|
||||||
|
_count = 0;
|
||||||
|
_comparer = comparer ?? Comparer<TKey>.Default;
|
||||||
|
}
|
||||||
|
|
||||||
public RecyclableSortedList(int blockSize = RecyclableDefaults.BlockSize)
|
public int Count => _count;
|
||||||
: base(blockSize)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool IsUpdating => _isUpdating > 0;
|
public TValue this[TKey key]
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
int index = BinarySearch(key);
|
||||||
|
if (index >= 0)
|
||||||
|
{
|
||||||
|
return _values[index];
|
||||||
|
}
|
||||||
|
|
||||||
public void Add(TKey key, TValue value) => Add((key, value));
|
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(key), "Key not found");
|
||||||
|
return default!;
|
||||||
|
}
|
||||||
|
set
|
||||||
|
{
|
||||||
|
int index = BinarySearch(key);
|
||||||
|
if (index >= 0)
|
||||||
|
{
|
||||||
|
_values[index] = value;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
public void BeginUpdate() => _isUpdating++;
|
Insert(~index, key, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public new void Clear()
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
{
|
public void Add(TKey key, TValue value)
|
||||||
BeginUpdate();
|
{
|
||||||
try
|
int index = BinarySearch(key);
|
||||||
{
|
if (index >= 0)
|
||||||
base.Clear();
|
{
|
||||||
}
|
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(key), "An element with the same key already exists.");
|
||||||
finally
|
}
|
||||||
{
|
|
||||||
EndUpdate();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void EndUpdate(bool raiseListUpdated = true)
|
Insert(~index, key, value);
|
||||||
{
|
}
|
||||||
if (_isUpdating > 0)
|
|
||||||
{
|
|
||||||
_isUpdating--;
|
|
||||||
if (raiseListUpdated && _isUpdating == 0)
|
|
||||||
{
|
|
||||||
ListUpdated();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void QuickSort()
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
{
|
public bool ContainsKey(TKey key) => BinarySearch(key) >= 0;
|
||||||
BeginUpdate();
|
|
||||||
try
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
{
|
public bool TryGetValue(TKey key, out TValue value)
|
||||||
QuickSortExtensions<(TKey, TValue)>.QuickSort(this, _comparer, _randomNumberGenerator);
|
{
|
||||||
}
|
int index = BinarySearch(key);
|
||||||
finally
|
if (index >= 0)
|
||||||
{
|
{
|
||||||
EndUpdate(false);
|
value = _values[index];
|
||||||
}
|
return true;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
value = default!;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public bool Remove(TKey key)
|
||||||
|
{
|
||||||
|
int index = BinarySearch(key);
|
||||||
|
if (index < 0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (index < _count - 1)
|
||||||
|
{
|
||||||
|
Array.Copy(_keys, index + 1, _keys, index, _count - index - 1);
|
||||||
|
Array.Copy(_values, index + 1, _values, index, _count - index - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
_count--;
|
||||||
|
if (_needsClearing)
|
||||||
|
{
|
||||||
|
_keys[_count] = default!;
|
||||||
|
_values[_count] = default!;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Clear()
|
||||||
|
{
|
||||||
|
if (_needsClearing && _count > 0)
|
||||||
|
{
|
||||||
|
Array.Clear(_keys, 0, _count);
|
||||||
|
Array.Clear(_values, 0, _count);
|
||||||
|
}
|
||||||
|
|
||||||
|
_count = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TKey GetKey(int index) => _keys[index];
|
||||||
|
public TValue GetValue(int index) => _values[index];
|
||||||
|
|
||||||
|
public Enumerator GetEnumerator() => new(this);
|
||||||
|
IEnumerator<(TKey Key, TValue Value)> IEnumerable<(TKey Key, TValue Value)>.GetEnumerator() => new Enumerator(this);
|
||||||
|
IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this);
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (_disposed)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_keys.Length >= RecyclableDefaults.MinPooledArrayLength)
|
||||||
|
{
|
||||||
|
RecyclableArrayPool<TKey>.ReturnShared(_keys, _needsClearing);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_values.Length >= RecyclableDefaults.MinPooledArrayLength)
|
||||||
|
{
|
||||||
|
RecyclableArrayPool<TValue>.ReturnShared(_values, _needsClearing);
|
||||||
|
}
|
||||||
|
|
||||||
|
_keys = Array.Empty<TKey>();
|
||||||
|
_values = Array.Empty<TValue>();
|
||||||
|
_count = 0;
|
||||||
|
_disposed = true;
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Insert(int index, TKey key, TValue value)
|
||||||
|
{
|
||||||
|
if (_count == _keys.Length)
|
||||||
|
{
|
||||||
|
Grow(_count + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (index < _count)
|
||||||
|
{
|
||||||
|
Array.Copy(_keys, index, _keys, index + 1, _count - index);
|
||||||
|
Array.Copy(_values, index, _values, index + 1, _count - index);
|
||||||
|
}
|
||||||
|
|
||||||
|
_keys[index] = key;
|
||||||
|
_values[index] = value;
|
||||||
|
_count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Grow(int min)
|
||||||
|
{
|
||||||
|
int newSize = _keys.Length << 1;
|
||||||
|
if (newSize < min)
|
||||||
|
{
|
||||||
|
newSize = min;
|
||||||
|
}
|
||||||
|
|
||||||
|
var newKeys = newSize >= RecyclableDefaults.MinPooledArrayLength
|
||||||
|
? RecyclableArrayPool<TKey>.RentShared(newSize)
|
||||||
|
: new TKey[newSize];
|
||||||
|
var newValues = newSize >= RecyclableDefaults.MinPooledArrayLength
|
||||||
|
? RecyclableArrayPool<TValue>.RentShared(newSize)
|
||||||
|
: new TValue[newSize];
|
||||||
|
|
||||||
|
Array.Copy(_keys, newKeys, _count);
|
||||||
|
Array.Copy(_values, newValues, _count);
|
||||||
|
|
||||||
|
if (_keys.Length >= RecyclableDefaults.MinPooledArrayLength)
|
||||||
|
{
|
||||||
|
RecyclableArrayPool<TKey>.ReturnShared(_keys, _needsClearing);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_values.Length >= RecyclableDefaults.MinPooledArrayLength)
|
||||||
|
{
|
||||||
|
RecyclableArrayPool<TValue>.ReturnShared(_values, _needsClearing);
|
||||||
|
}
|
||||||
|
|
||||||
|
_keys = newKeys;
|
||||||
|
_values = newValues;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int BinarySearch(TKey key)
|
||||||
|
{
|
||||||
|
int low = 0;
|
||||||
|
int high = _count - 1;
|
||||||
|
while (low <= high)
|
||||||
|
{
|
||||||
|
int mid = (low + high) >> 1;
|
||||||
|
int cmp = _comparer.Compare(_keys[mid], key);
|
||||||
|
if (cmp == 0)
|
||||||
|
{
|
||||||
|
return mid;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cmp < 0)
|
||||||
|
{
|
||||||
|
low = mid + 1;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
high = mid - 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ~low;
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct Enumerator : IEnumerator<(TKey Key, TValue Value)>
|
||||||
|
{
|
||||||
|
private readonly RecyclableSortedList<TKey, TValue> _list;
|
||||||
|
private int _index;
|
||||||
|
private (TKey, TValue) _current;
|
||||||
|
|
||||||
|
internal Enumerator(RecyclableSortedList<TKey, TValue> list)
|
||||||
|
{
|
||||||
|
_list = list;
|
||||||
|
_index = 0;
|
||||||
|
_current = default!;
|
||||||
|
}
|
||||||
|
|
||||||
|
public (TKey Key, TValue Value) Current => _current;
|
||||||
|
object IEnumerator.Current => _current;
|
||||||
|
|
||||||
|
public bool MoveNext()
|
||||||
|
{
|
||||||
|
if (_index >= _list._count)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_current = (_list._keys[_index], _list._values[_index]);
|
||||||
|
_index++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Reset()
|
||||||
|
{
|
||||||
|
_index = 0;
|
||||||
|
_current = default!;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,93 +1,97 @@
|
|||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Recyclable.Collections;
|
using Recyclable.Collections;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
namespace Recyclable.CollectionsTests
|
namespace Recyclable.CollectionsTests
|
||||||
{
|
{
|
||||||
public class RecyclableSortedListTests
|
public class RecyclableSortedListTests
|
||||||
{
|
{
|
||||||
private static readonly (int, string)[] _testData = new[] { (5, "a"), (4, "d"), (3, "c"), (2, "b"), (1, "a") };
|
[Theory]
|
||||||
|
[MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
|
||||||
|
public void AddShouldStoreItemsSorted(int itemsCount)
|
||||||
|
{
|
||||||
|
using var list = new RecyclableSortedList<long, long>();
|
||||||
|
foreach (var key in RecyclableLongListTestData.CreateTestData(itemsCount).Reverse())
|
||||||
|
{
|
||||||
|
list.Add(key, -key);
|
||||||
|
}
|
||||||
|
|
||||||
[Theory]
|
_ = list.Should().HaveCount(itemsCount)
|
||||||
[MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
|
.And.BeInAscendingOrder(x => x.Key);
|
||||||
public void ShouldBeSortedWhenCreated(int itemsCount)
|
for (int i = 0; i < itemsCount; i++)
|
||||||
{
|
{
|
||||||
// Act
|
long expectedKey = i + 1;
|
||||||
var data = RecyclableLongListTestData.CreateTestData(itemsCount)
|
list.GetKey(i).Should().Be(expectedKey);
|
||||||
.Select(x => (itemsCount - x + 1, x))
|
list.GetValue(i).Should().Be(-expectedKey);
|
||||||
.ToArray();
|
}
|
||||||
using var sortedList = new RecyclableSortedList<long, long>(data, 2);
|
|
||||||
|
|
||||||
// Validate
|
|
||||||
_ = sortedList.Should().HaveCount(itemsCount)
|
|
||||||
.And.BeInAscendingOrder(item => item.Key);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ShouldBeEmptyWhenNotInitialized()
|
|
||||||
{
|
|
||||||
// Act
|
|
||||||
using var sortedList = new RecyclableSortedList<int, string>(2);
|
|
||||||
|
|
||||||
// Validate
|
|
||||||
_ = sortedList.Should().BeEmpty();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ShouldNotBeSortedWhenInitialized()
|
|
||||||
{
|
|
||||||
// Act
|
|
||||||
using var sortedList = new RecyclableSortedList<int, string>(2)
|
|
||||||
{
|
|
||||||
_testData[0],
|
|
||||||
_testData[1],
|
|
||||||
_testData[2],
|
|
||||||
_testData[3],
|
|
||||||
_testData[4]
|
|
||||||
};
|
|
||||||
|
|
||||||
// Validate
|
|
||||||
_ = sortedList.Should().NotBeEmpty()
|
|
||||||
.And.ContainInConsecutiveOrder(_testData);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
|
|
||||||
public void ShouldBeSortedWhenUpdateEnds(int itemsCount)
|
|
||||||
{
|
|
||||||
// Prepare
|
|
||||||
using var sortedList = new RecyclableSortedList<long, long>(2);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
sortedList.BeginUpdate();
|
|
||||||
foreach (var value in RecyclableLongListTestData.CreateTestData(itemsCount))
|
|
||||||
{
|
|
||||||
sortedList.Add((itemsCount - value + 1, value));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate
|
|
||||||
_ = sortedList.Should().BeInDescendingOrder(x => x.Key);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
sortedList.EndUpdate();
|
|
||||||
|
|
||||||
// Validate
|
|
||||||
_ = sortedList.Should().BeInAscendingOrder(x => x.Key);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
|
|
||||||
public void ShouldBeEmptyAfterClear(int itemsCount)
|
|
||||||
{
|
|
||||||
// Prepare
|
|
||||||
var data = RecyclableLongListTestData.CreateTestData(itemsCount)
|
|
||||||
.Select(x => (x, x));
|
|
||||||
using var sortedList = new RecyclableSortedList<long, long>(data);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
sortedList.Clear();
|
|
||||||
|
|
||||||
// Validate
|
|
||||||
_ = sortedList.Should().BeEmpty();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
[Fact]
|
||||||
|
public void IndexerShouldUpdateValue()
|
||||||
|
{
|
||||||
|
using var list = new RecyclableSortedList<int, string>();
|
||||||
|
list.Add(1, "a");
|
||||||
|
|
||||||
|
list[1] = "b";
|
||||||
|
|
||||||
|
_ = list[1].Should().Be("b");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
|
||||||
|
public void RemoveShouldDeleteItem(int itemsCount)
|
||||||
|
{
|
||||||
|
using var list = new RecyclableSortedList<long, long>();
|
||||||
|
foreach (var key in RecyclableLongListTestData.CreateTestData(itemsCount))
|
||||||
|
{
|
||||||
|
list.Add(key, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (itemsCount > 0)
|
||||||
|
{
|
||||||
|
long keyToRemove = (itemsCount + 1) / 2;
|
||||||
|
list.Remove(keyToRemove).Should().BeTrue();
|
||||||
|
_ = list.ContainsKey(keyToRemove).Should().BeFalse();
|
||||||
|
_ = list.Should().HaveCount(itemsCount - 1);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
list.Remove(0).Should().BeFalse();
|
||||||
|
_ = list.Should().BeEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TryGetValueShouldReturnValue()
|
||||||
|
{
|
||||||
|
using var list = new RecyclableSortedList<int, string>();
|
||||||
|
list.Add(1, "a");
|
||||||
|
|
||||||
|
var found = list.TryGetValue(1, out var value);
|
||||||
|
|
||||||
|
_ = found.Should().BeTrue();
|
||||||
|
_ = value.Should().Be("a");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
|
||||||
|
public void EnumeratorShouldYieldItemsSorted(int itemsCount)
|
||||||
|
{
|
||||||
|
using var list = new RecyclableSortedList<long, long>();
|
||||||
|
foreach (var key in RecyclableLongListTestData.CreateTestData(itemsCount).Reverse())
|
||||||
|
{
|
||||||
|
list.Add(key, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
var actual = new List<long>();
|
||||||
|
var enumerator = list.GetEnumerator();
|
||||||
|
while (enumerator.MoveNext())
|
||||||
|
{
|
||||||
|
actual.Add(enumerator.Current.Key);
|
||||||
|
}
|
||||||
|
|
||||||
|
var expected = RecyclableLongListTestData.CreateTestData(itemsCount).ToList();
|
||||||
|
_ = actual.Should().ContainInConsecutiveOrder(expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user