This commit is contained in:
Marek Lemańczyk committed 2025-07-14 17:09:03 +02:00
commit 35f1124d6f
9 files changed
+1070 -399

No files matched your search

@@ -0,0 +1,287 @@
using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using System.Runtime.CompilerServices;
using Recyclable.Collections.Pools;
namespace Recyclable.Collections
{
internal sealed class RecyclableSortedDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>, IDisposable
where TKey : notnull
{
private static readonly bool _needsClearing = !typeof(TKey).IsValueType || !typeof(TValue).IsValueType;
private readonly IComparer<TKey> _comparer;
private TKey[] _keys;
private TValue[] _values;
private int _count;
private bool _disposed;
public RecyclableSortedDictionary(int initialCapacity = RecyclableDefaults.InitialCapacity, IComparer<TKey>? comparer = null)
{
if (initialCapacity < 1)
{
initialCapacity = 1;
}
if (!BitOperations.IsPow2((uint)initialCapacity))
{
initialCapacity = (int)BitOperations.RoundUpToPowerOf2((uint)initialCapacity);
}
_keys = initialCapacity >= RecyclableDefaults.MinPooledArrayLength
? RecyclableArrayPool<TKey>.RentShared(initialCapacity)
: new TKey[initialCapacity];
_values = initialCapacity >= RecyclableDefaults.MinPooledArrayLength
? RecyclableArrayPool<TValue>.RentShared(initialCapacity)
: new TValue[initialCapacity];
_count = 0;
_comparer = comparer ?? Comparer<TKey>.Default;
}
public int Count => _count;
public TValue this[TKey key]
{
get
{
int index = BinarySearch(key);
if (index < _count && _comparer.Compare(_keys[index], key) == 0)
{
return _values[index];
}
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(key), "Key not found");
return default!;
}
set
{
int index = BinarySearch(key);
if (index < _count && _comparer.Compare(_keys[index], key) == 0)
{
_values[index] = value;
return;
}
InsertAt(index, key, value);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(TKey key, TValue value)
{
int index = BinarySearch(key);
if (index < _count && _comparer.Compare(_keys[index], key) == 0)
{
throw new ArgumentException("An element with the same key already exists.", nameof(key));
}
InsertAt(index, key, value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ContainsKey(TKey key)
{
int index = BinarySearch(key);
return index < _count && _comparer.Compare(_keys[index], key) == 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Remove(TKey key)
{
int index = BinarySearch(key);
if (index >= _count || _comparer.Compare(_keys[index], key) != 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;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryGetValue(TKey key, out TValue value)
{
int index = BinarySearch(key);
if (index < _count && _comparer.Compare(_keys[index], key) == 0)
{
value = _values[index];
return true;
}
value = default!;
return false;
}
public void Clear()
{
if (_needsClearing)
{
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<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() => new Enumerator(this);
IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this);
private void InsertAt(int index, TKey key, TValue value)
{
if (_count == _keys.Length)
{
Grow();
}
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 newSize;
if (_keys.Length >= RecyclableDefaults.MaxPooledBlockSize)
{
newSize = RecyclableDefaults.MaxPooledBlockSize;
}
else
{
int doubled = _keys.Length << 1;
newSize = (int)Math.Min(doubled, RecyclableDefaults.MaxPooledBlockSize);
}
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 void Dispose()
{
if (_disposed)
{
return;
}
Clear();
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>();
_disposed = true;
GC.SuppressFinalize(this);
}
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
{
private readonly RecyclableSortedDictionary<TKey, TValue> _dictionary;
private int _index;
private KeyValuePair<TKey, TValue> _current;
internal Enumerator(RecyclableSortedDictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_index = 0;
_current = default;
}
public KeyValuePair<TKey, TValue> Current => _current;
object IEnumerator.Current => _current;
public bool MoveNext()
{
if (_index >= _dictionary._count)
{
return false;
}
_current = new KeyValuePair<TKey, TValue>(_dictionary._keys[_index], _dictionary._values[_index]);
_index++;
return true;
}
public void Reset()
{
_index = 0;
_current = default;
}
public void Dispose()
{
}
}
}
}
+265 -66
View File
@@ -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()
{
}
}
}
} }
@@ -9,20 +9,22 @@ namespace Recyclable.CollectionsTests
{ {
private static readonly (int, string)[] _testData = new[] { (1, "a"), (2, "b"), (3, "c"), (4, "d"), (5, "e") }; private static readonly (int, string)[] _testData = new[] { (1, "a"), (2, "b"), (3, "c"), (4, "d"), (5, "e") };
[Fact] [Theory]
public void AddShouldStoreItems() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
public void AddShouldStoreItems(int itemsCount)
{ {
using var dict = new RecyclableDictionary<int, string>(); using var dict = new RecyclableDictionary<long, long>();
foreach (var (key, value) in _testData) foreach (var key in RecyclableLongListTestData.CreateTestData(itemsCount))
{ {
dict.Add(key, value); dict.Add(key, -key);
} }
_ = dict.Should().HaveCount(_testData.Length); _ = dict.Should().HaveCount(itemsCount);
for (var i = 0; i < _testData.Length; i++) for (var i = 0; i < itemsCount; i++)
{ {
dict.GetKey(i).Should().Be(_testData[i].Item1); long expectedKey = i + 1;
dict.GetValue(i).Should().Be(_testData[i].Item2); dict.GetKey(i).Should().Be(expectedKey);
dict.GetValue(i).Should().Be(-expectedKey);
} }
} }
@@ -37,18 +39,28 @@ namespace Recyclable.CollectionsTests
_ = dict[1].Should().Be("b"); _ = dict[1].Should().Be("b");
} }
[Fact] [Theory]
public void RemoveShouldSwapWithLast() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
public void RemoveShouldSwapWithLast(int itemsCount)
{ {
using var dict = new RecyclableDictionary<int, string>(); using var dict = new RecyclableDictionary<long, long>();
foreach (var (key, value) in _testData) foreach (var key in RecyclableLongListTestData.CreateTestData(itemsCount))
{ {
dict.Add(key, value); dict.Add(key, key);
} }
dict.Remove(3).Should().BeTrue(); if (itemsCount > 0)
_ = dict.ContainsKey(3).Should().BeFalse(); {
_ = dict.Should().HaveCount(_testData.Length - 1); long keyToRemove = (itemsCount + 1) / 2;
dict.Remove(keyToRemove).Should().BeTrue();
_ = dict.ContainsKey(keyToRemove).Should().BeFalse();
_ = dict.Should().HaveCount(itemsCount - 1);
}
else
{
dict.Remove(0).Should().BeFalse();
_ = dict.Should().BeEmpty();
}
} }
[Fact] [Fact]
@@ -63,23 +75,25 @@ namespace Recyclable.CollectionsTests
_ = value.Should().Be("a"); _ = value.Should().Be("a");
} }
[Fact] [Theory]
public void EnumeratorShouldYieldItems() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
public void EnumeratorShouldYieldItems(int itemsCount)
{ {
using var dict = new RecyclableDictionary<int, string>(); using var dict = new RecyclableDictionary<long, long>();
foreach (var (key, value) in _testData) foreach (var key in RecyclableLongListTestData.CreateTestData(itemsCount))
{ {
dict.Add(key, value); dict.Add(key, key);
} }
var actual = new List<KeyValuePair<int, string>>(); var actual = new List<long>();
var enumerator = dict.GetEnumerator(); var enumerator = dict.GetEnumerator();
while (enumerator.MoveNext()) while (enumerator.MoveNext())
{ {
actual.Add(enumerator.Current); actual.Add(enumerator.Current.Key);
} }
_ = actual.Should().ContainInConsecutiveOrder(_testData.Select(x => new KeyValuePair<int, string>(x.Item1, x.Item2))); var expected = RecyclableLongListTestData.CreateTestData(itemsCount).ToList();
_ = actual.Should().ContainInConsecutiveOrder(expected);
} }
} }
} }
@@ -7,49 +7,74 @@ namespace Recyclable.CollectionsTests
{ {
public class RecyclableHashSetTests public class RecyclableHashSetTests
{ {
[Fact] [Theory]
public void AddShouldStoreUniqueItems() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
public void AddShouldStoreUniqueItems(int itemsCount)
{ {
using var set = new RecyclableHashSet<string>(); using var set = new RecyclableHashSet<long>();
set.Add("a").Should().BeTrue(); foreach (var item in RecyclableLongListTestData.CreateTestData(itemsCount))
set.Add("b").Should().BeTrue();
set.Add("a").Should().BeFalse();
_ = set.Should().HaveCount(2);
_ = set.Contains("a").Should().BeTrue();
_ = set.Contains("b").Should().BeTrue();
}
[Fact]
public void RemoveShouldDeleteItem()
{
using var set = new RecyclableHashSet<int>();
set.Add(1);
set.Add(2);
set.Remove(1).Should().BeTrue();
_ = set.Contains(1).Should().BeFalse();
_ = set.Should().HaveCount(1);
}
[Fact]
public void EnumeratorShouldYieldItems()
{
using var set = new RecyclableHashSet<int>();
for (int i = 0; i < 5; i++)
{ {
set.Add(i); set.Add(item).Should().BeTrue();
} }
var actual = new List<int>(); foreach (var item in RecyclableLongListTestData.CreateTestData(itemsCount))
{
set.Add(item).Should().BeFalse();
}
_ = set.Should().HaveCount(itemsCount);
}
[Theory]
[MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
public void RemoveShouldDeleteItem(int itemsCount)
{
using var set = new RecyclableHashSet<long>();
foreach (var item in RecyclableLongListTestData.CreateTestData(itemsCount))
{
set.Add(item);
}
if (itemsCount > 0)
{
long value = (itemsCount + 1) / 2;
set.Remove(value).Should().BeTrue();
_ = set.Contains(value).Should().BeFalse();
_ = set.Should().HaveCount(itemsCount - 1);
}
else
{
set.Remove(0).Should().BeFalse();
_ = set.Should().BeEmpty();
}
}
[Theory]
[MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
public void EnumeratorShouldYieldItems(int itemsCount)
{
using var set = new RecyclableHashSet<long>();
foreach (var item in RecyclableLongListTestData.CreateTestData(itemsCount))
{
set.Add(item);
}
var actual = new List<long>();
var enumerator = set.GetEnumerator(); var enumerator = set.GetEnumerator();
while (enumerator.MoveNext()) while (enumerator.MoveNext())
{ {
actual.Add(enumerator.Current); actual.Add(enumerator.Current);
} }
_ = actual.Should().Contain(Enumerable.Range(0, 5)).And.HaveCount(5); var expected = RecyclableLongListTestData.CreateTestData(itemsCount).ToList();
if (itemsCount == 0)
{
_ = actual.Should().BeEmpty();
}
else
{
_ = actual.Should().Contain(expected).And.HaveCount(itemsCount);
}
} }
} }
} }
@@ -8,36 +8,40 @@ namespace Recyclable.CollectionsTests
{ {
private static readonly string[] _testData = new[] { "a", "d", "c", "b", "a" }; private static readonly string[] _testData = new[] { "a", "d", "c", "b", "a" };
[Fact] [Theory]
public void AddLastShouldPreserveOrder() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
public void AddLastShouldPreserveOrder(int itemsCount)
{ {
using var list = new RecyclableLinkedList<string>(); using var list = new RecyclableLinkedList<long>();
foreach (var item in _testData) var expected = RecyclableLongListTestData.CreateTestData(itemsCount).ToArray();
foreach (var item in expected)
{ {
list.AddLast(item); list.AddLast(item);
} }
var actual = new RecyclableLongList<string>(); var actual = new RecyclableLongList<long>();
foreach (var item in list) foreach (var item in list)
{ {
actual.Add(item); actual.Add(item);
} }
_ = actual.Should().ContainInConsecutiveOrder(_testData) _ = actual.Should().ContainInConsecutiveOrder(expected)
.And.BeEquivalentTo(_testData); .And.BeEquivalentTo(expected);
} }
[Fact] [Theory]
public void AddFirstShouldReverseOrder() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
public void AddFirstShouldReverseOrder(int itemsCount)
{ {
using var list = new RecyclableLinkedList<string>(); using var list = new RecyclableLinkedList<long>();
foreach (var item in _testData) var source = RecyclableLongListTestData.CreateTestData(itemsCount).ToArray();
foreach (var item in source)
{ {
list.AddFirst(item); list.AddFirst(item);
} }
var expected = _testData.Reverse().ToArray(); var expected = source.Reverse().ToArray();
var actual = new RecyclableLongList<string>(); var actual = new RecyclableLongList<long>();
foreach (var item in list) foreach (var item in list)
{ {
actual.Add(item); actual.Add(item);
@@ -46,30 +50,34 @@ namespace Recyclable.CollectionsTests
_ = actual.Should().ContainInConsecutiveOrder(expected); _ = actual.Should().ContainInConsecutiveOrder(expected);
} }
[Fact] [Theory]
public void RemoveFirstShouldReturnItemsInOrder() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
public void RemoveFirstShouldReturnItemsInOrder(int itemsCount)
{ {
using var list = new RecyclableLinkedList<string>(_testData); var source = RecyclableLongListTestData.CreateTestData(itemsCount).ToArray();
var actual = new RecyclableLongList<string>(); using var list = new RecyclableLinkedList<long>(source);
var actual = new RecyclableLongList<long>();
while (list.LongCount > 0) while (list.LongCount > 0)
{ {
actual.Add(list.RemoveFirst()); actual.Add(list.RemoveFirst());
} }
_ = actual.Should().ContainInConsecutiveOrder(_testData); _ = actual.Should().ContainInConsecutiveOrder(source);
} }
[Fact] [Theory]
public void RemoveLastShouldReturnItemsInReverseOrder() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
public void RemoveLastShouldReturnItemsInReverseOrder(int itemsCount)
{ {
using var list = new RecyclableLinkedList<string>(_testData); var source = RecyclableLongListTestData.CreateTestData(itemsCount).ToArray();
var actual = new RecyclableLongList<string>(); using var list = new RecyclableLinkedList<long>(source);
var actual = new RecyclableLongList<long>();
while (list.LongCount > 0) while (list.LongCount > 0)
{ {
actual.Add(list.RemoveLast()); actual.Add(list.RemoveLast());
} }
_ = actual.Should().ContainInConsecutiveOrder(_testData.Reverse()); _ = actual.Should().ContainInConsecutiveOrder(source.Reverse());
} }
} }
} }
@@ -7,117 +7,134 @@ namespace Recyclable.CollectionsTests
{ {
private static readonly string[] _testData = new[] { "a", "d", "c", "b", "a" }; private static readonly string[] _testData = new[] { "a", "d", "c", "b", "a" };
[Fact] [Theory]
public void ShouldNotBeSortedWhenCreated() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
{ public void ShouldNotBeSortedWhenCreated(int itemsCount)
// Act {
using var list = new RecyclableQueue<string>(_testData, 2); // Act
var data = RecyclableLongListTestData.CreateTestData(itemsCount).Select(i => i.ToString()).ToArray();
using var list = new RecyclableQueue<string>(data, 2);
// Validate // Validate
_ = list.Should().HaveCount(_testData.Length) _ = list.Should().HaveCount(itemsCount)
.And.ContainInConsecutiveOrder(_testData); .And.ContainInConsecutiveOrder(data);
_ = list.LongCount.Should().Be(_testData.Length); _ = list.LongCount.Should().Be(itemsCount);
} }
[Fact] [Fact]
public void ShouldBeEmptyWhenNotInitialized() public void ShouldBeEmptyWhenNotInitialized()
{ {
// Act // Act
using var list = new RecyclableQueue<string>(2); using var list = new RecyclableQueue<string>(2);
// Validate // Validate
_ = list.Should().BeEmpty(); _ = list.Should().BeEmpty();
_ = list.LongCount.Should().Be(0); _ = list.LongCount.Should().Be(0);
} }
[Fact] [Theory]
public void ShouldNotBeSortedWhenInitialized() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
{ public void ShouldNotBeSortedWhenInitialized(int itemsCount)
// Act {
using var list = new RecyclableQueue<string>(2) // Act
{ var data = RecyclableLongListTestData.CreateTestData(itemsCount).Select(i => i.ToString()).ToArray();
_testData[0], using var list = new RecyclableQueue<string>(2)
_testData[1], {
_testData[2], // populate via collection initializer
_testData[3], };
_testData[4] foreach (var item in data)
}; {
list.Enqueue(item);
}
// Validate // Validate
_ = list.Should().NotBeEmpty() if (itemsCount == 0)
.And.ContainInConsecutiveOrder(_testData) {
.And.BeEquivalentTo(_testData); _ = list.Should().BeEmpty();
} }
else
{
_ = list.Should().NotBeEmpty()
.And.ContainInConsecutiveOrder(data)
.And.BeEquivalentTo(data);
}
}
[Fact] [Theory]
public void ShouldBeEmptyAfterClear() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
{ public void ShouldBeEmptyAfterClear(int itemsCount)
// Prepare {
using var list = new RecyclableQueue<string>(_testData); // Prepare
var data = RecyclableLongListTestData.CreateTestData(itemsCount).Select(i => i.ToString());
using var list = new RecyclableQueue<string>(data);
// Act // Act
list.Clear(); list.Clear();
// Validate // Validate
_ = list.Should().BeEmpty(); _ = list.Should().BeEmpty();
} }
[Fact] [Theory]
public void DequeueShouldReturnItemsInTheSameOrder() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
{ public void DequeueShouldReturnItemsInTheSameOrder(int itemsCount)
// Prepare {
using var list = new RecyclableQueue<string>(); // Prepare
var data = RecyclableLongListTestData.CreateTestData(itemsCount).Select(i => i.ToString()).ToArray();
using var list = new RecyclableQueue<string>();
// Act // Act
for (var itemIdx = 0; itemIdx < _testData.Length; itemIdx++) for (var itemIdx = 0; itemIdx < data.Length; itemIdx++)
{ {
list.Enqueue(_testData[itemIdx]); list.Enqueue(data[itemIdx]);
} }
var dequeuedItems = new RecyclableLongList<string>(); var dequeuedItems = new RecyclableLongList<string>();
while (list.LongCount > 0) while (list.LongCount > 0)
{ {
dequeuedItems.Add(list.Dequeue()); dequeuedItems.Add(list.Dequeue());
} }
// Validate // Validate
_ = dequeuedItems.Should().ContainInConsecutiveOrder(_testData) _ = dequeuedItems.Should().ContainInConsecutiveOrder(data)
.And.BeEquivalentTo(_testData); .And.BeEquivalentTo(data);
} }
[Fact] [Fact]
public void DequeueShoudRaiseArgumentOutOfRangeWhenNoMoreElementsFound() public void DequeueShoudRaiseArgumentOutOfRangeWhenNoMoreElementsFound()
{ {
// Prepare // Prepare
using var list = new RecyclableQueue<string>(_testData); using var list = new RecyclableQueue<string>(_testData);
// Act // Act
while (list.LongCount > 0) while (list.LongCount > 0)
{ {
_ = list.Dequeue(); _ = list.Dequeue();
} }
_ = Assert.Throws<ArgumentOutOfRangeException>(() => list.Dequeue()); _ = Assert.Throws<ArgumentOutOfRangeException>(() => list.Dequeue());
_ = list.LongCount.Should().Be(0); _ = list.LongCount.Should().Be(0);
} }
[Fact] [Theory]
public void GetEnumeratorShouldYieldAllItemsInTheSameOrder() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
{ public void GetEnumeratorShouldYieldAllItemsInTheSameOrder(int itemsCount)
// Prepare {
using var list = new RecyclableQueue<string>(_testData); // Prepare
var data = RecyclableLongListTestData.CreateTestData(itemsCount).Select(i => i.ToString()).ToArray();
using var list = new RecyclableQueue<string>(data);
// Act // Act
var actual = new RecyclableLongList<string>(); var actual = new RecyclableLongList<string>();
using var enumerator = list.GetEnumerator(); using var enumerator = list.GetEnumerator();
while (enumerator.MoveNext()) while (enumerator.MoveNext())
{ {
actual.Add(enumerator.Current); actual.Add(enumerator.Current);
} }
// Validate // Validate
_ = actual.Should().ContainInConsecutiveOrder(_testData) _ = actual.Should().ContainInConsecutiveOrder(data)
.And.BeEquivalentTo(_testData); .And.BeEquivalentTo(data);
} }
} }
} }
@@ -0,0 +1,96 @@
using FluentAssertions;
using Recyclable.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Recyclable.CollectionsTests
{
public class RecyclableSortedDictionaryTests
{
[Fact]
public void AddShouldStoreUniqueItemsInOrder()
{
using var dict = new RecyclableSortedDictionary<int, int>();
var values = new[] { 4, 1, 3, 2, 5 };
foreach (var v in values)
{
dict.Add(v, v);
}
var result = new List<int>();
foreach (var kv in dict)
{
result.Add(kv.Key);
}
_ = result.Should().Equal(values.OrderBy(x => x));
}
[Fact]
public void IndexerShouldUpdateValue()
{
using var dict = new RecyclableSortedDictionary<int, string>();
dict.Add(1, "a");
dict[1] = "b";
_ = dict[1].Should().Be("b");
}
[Fact]
public void RemoveShouldDeleteItem()
{
using var dict = new RecyclableSortedDictionary<int, string>();
var values = new[] { 4, 1, 3, 2, 5 };
foreach (var v in values)
{
dict.Add(v, v.ToString());
}
dict.Remove(3).Should().BeTrue();
_ = dict.ContainsKey(3).Should().BeFalse();
_ = dict.Count.Should().Be(values.Length - 1);
}
[Fact]
public void EnumeratorShouldYieldItemsInOrder()
{
using var dict = new RecyclableSortedDictionary<int, int>();
foreach (var v in new[] { 3, 1, 4, 2 })
{
dict.Add(v, v);
}
var result = new List<int>();
foreach (var item in dict)
{
result.Add(item.Key);
}
_ = result.Should().Equal(new[] { 1, 2, 3, 4 });
}
[Fact]
public void TryGetValueShouldReturnValue()
{
using var dict = new RecyclableSortedDictionary<int, string>();
dict.Add(1, "a");
var found = dict.TryGetValue(1, out var value);
_ = found.Should().BeTrue();
_ = value.Should().Be("a");
}
[Fact]
public void ShouldBeEmptyAfterClear()
{
using var dict = new RecyclableSortedDictionary<int, int>();
dict.Add(1, 1);
dict.Add(2, 2);
dict.Clear();
_ = dict.Should().BeEmpty();
}
}
}
@@ -1,86 +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);
}
[Fact] _ = list.Should().HaveCount(itemsCount)
public void ShouldBeSortedWhenCreated() .And.BeInAscendingOrder(x => x.Key);
{ for (int i = 0; i < itemsCount; i++)
// Act {
using var sortedList = new RecyclableSortedList<int, string>(_testData, 2); long expectedKey = i + 1;
list.GetKey(i).Should().Be(expectedKey);
list.GetValue(i).Should().Be(-expectedKey);
}
}
// Validate [Fact]
_ = sortedList.Should().HaveCount(_testData.Length) public void IndexerShouldUpdateValue()
.And.BeEquivalentTo(_testData) {
.And.BeInAscendingOrder((item) => item.Key); using var list = new RecyclableSortedList<int, string>();
} list.Add(1, "a");
[Fact] list[1] = "b";
public void ShouldBeEmptyWhenNotInitialized()
{
// Act
using var sortedList = new RecyclableSortedList<int, string>(2);
// Validate _ = list[1].Should().Be("b");
_ = sortedList.Should().BeEmpty(); }
}
[Fact] [Theory]
public void ShouldNotBeSortedWhenInitialized() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
{ public void RemoveShouldDeleteItem(int itemsCount)
// Act {
using var sortedList = new RecyclableSortedList<int, string>(2) using var list = new RecyclableSortedList<long, long>();
{ foreach (var key in RecyclableLongListTestData.CreateTestData(itemsCount))
_testData[0], {
_testData[1], list.Add(key, key);
_testData[2], }
_testData[3],
_testData[4]
};
// Validate if (itemsCount > 0)
_ = sortedList.Should().NotBeEmpty() {
.And.ContainInConsecutiveOrder(_testData); 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] [Fact]
public void ShouldBeSortedWhenUpdateEnds() public void TryGetValueShouldReturnValue()
{ {
// Prepare using var list = new RecyclableSortedList<int, string>();
using var sortedList = new RecyclableSortedList<int, string>(2); list.Add(1, "a");
// Act var found = list.TryGetValue(1, out var value);
sortedList.BeginUpdate();
foreach (var testItem in _testData)
{
sortedList.Add(testItem);
}
// Validate _ = found.Should().BeTrue();
_ = sortedList.Should().BeInDescendingOrder(x => x.Key); _ = value.Should().Be("a");
}
// Act [Theory]
sortedList.EndUpdate(); [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);
}
// Validate var actual = new List<long>();
_ = sortedList.Should().BeInAscendingOrder(x => x.Key); var enumerator = list.GetEnumerator();
} while (enumerator.MoveNext())
{
actual.Add(enumerator.Current.Key);
}
[Fact] var expected = RecyclableLongListTestData.CreateTestData(itemsCount).ToList();
public void ShouldBeEmptyAfterClear() _ = actual.Should().ContainInConsecutiveOrder(expected);
{ }
// Prepare }
using var sortedList = new RecyclableSortedList<int, string>(_testData);
// Act
sortedList.Clear();
// Validate
_ = sortedList.Should().BeEmpty();
}
}
} }
@@ -7,112 +7,126 @@ namespace Recyclable.CollectionsTests
{ {
private static readonly string[] _testData = new[] { "a", "d", "c", "b", "a" }; private static readonly string[] _testData = new[] { "a", "d", "c", "b", "a" };
[Fact] [Theory]
public void GetEnumeratorShouldYieldAllItemsInReversedOrder() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
{ public void GetEnumeratorShouldYieldAllItemsInReversedOrder(int itemsCount)
// Prepare {
using var list = new RecyclableStack<string>(_testData); // Prepare
var data = RecyclableLongListTestData.CreateTestData(itemsCount).Select(i => i.ToString()).ToArray();
using var list = new RecyclableStack<string>(data);
// Act // Act
var actual = new RecyclableLongList<string>(); var actual = new RecyclableLongList<string>();
using var enumerator = list.GetEnumerator(); using var enumerator = list.GetEnumerator();
while (enumerator.MoveNext()) while (enumerator.MoveNext())
{ {
actual.Add(enumerator.Current); actual.Add(enumerator.Current);
} }
// Validate // Validate
_ = actual.Should().ContainInConsecutiveOrder(_testData.Reverse()); _ = actual.Should().ContainInConsecutiveOrder(data.Reverse());
} }
[Fact] [Theory]
public void ShouldNotBeSortedWhenCreated() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
{ public void ShouldNotBeSortedWhenCreated(int itemsCount)
// Act {
using var sortedList = new RecyclableStack<string>(_testData, 2); // Act
var data = RecyclableLongListTestData.CreateTestData(itemsCount).Select(i => i.ToString()).ToArray();
using var sortedList = new RecyclableStack<string>(data, 2);
// Validate // Validate
_ = sortedList.Should().HaveCount(_testData.Length) _ = sortedList.Should().HaveCount(itemsCount)
.And.ContainInConsecutiveOrder(_testData.Reverse()); .And.ContainInConsecutiveOrder(data.Reverse());
} }
[Fact] [Fact]
public void ShouldBeEmptyWhenNotInitialized() public void ShouldBeEmptyWhenNotInitialized()
{ {
// Act // Act
using var sortedList = new RecyclableStack<string>(2); using var sortedList = new RecyclableStack<string>(2);
// Validate // Validate
_ = sortedList.Should().BeEmpty(); _ = sortedList.Should().BeEmpty();
} }
[Fact] [Theory]
public void ShouldNotBeSortedWhenInitialized() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
{ public void ShouldNotBeSortedWhenInitialized(int itemsCount)
// Act {
using var sortedList = new RecyclableStack<string>(2) // Act
{ var data = RecyclableLongListTestData.CreateTestData(itemsCount).Select(i => i.ToString()).ToArray();
_testData[0], using var sortedList = new RecyclableStack<string>(2);
_testData[1], foreach (var item in data)
_testData[2], {
_testData[3], sortedList.Push(item);
_testData[4] }
};
// Validate // Validate
_ = sortedList.Should().NotBeEmpty() if (itemsCount == 0)
.And.ContainInConsecutiveOrder(_testData.Reverse()) {
.And.BeEquivalentTo(_testData); _ = sortedList.Should().BeEmpty();
} }
else
{
_ = sortedList.Should().NotBeEmpty()
.And.ContainInConsecutiveOrder(data.Reverse())
.And.BeEquivalentTo(data);
}
}
[Fact] [Theory]
public void ShouldBeEmptyAfterClear() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
{ public void ShouldBeEmptyAfterClear(int itemsCount)
// Prepare {
using var sortedList = new RecyclableStack<string>(_testData); // Prepare
var data = RecyclableLongListTestData.CreateTestData(itemsCount).Select(i => i.ToString()).ToArray();
using var sortedList = new RecyclableStack<string>(data);
// Act // Act
sortedList.Clear(); sortedList.Clear();
// Validate // Validate
_ = sortedList.Should().BeEmpty(); _ = sortedList.Should().BeEmpty();
} }
[Fact] [Theory]
public void PopShouldReturnItemsInReversedOrder() [MemberData(nameof(RecyclableLongListTestData.ItemsCountTestCases), MemberType = typeof(RecyclableLongListTestData))]
{ public void PopShouldReturnItemsInReversedOrder(int itemsCount)
// Prepare {
using var list = new RecyclableStack<string>(); // Prepare
using var list = new RecyclableStack<string>();
// Act // Act
for (var itemIdx = 0; itemIdx < _testData.Length; itemIdx++) var data = RecyclableLongListTestData.CreateTestData(itemsCount).Select(i => i.ToString()).ToArray();
{ for (var itemIdx = 0; itemIdx < data.Length; itemIdx++)
list.Push(_testData[itemIdx]); {
} list.Push(data[itemIdx]);
}
var dequeuedItems = new RecyclableLongList<string>(); var dequeuedItems = new RecyclableLongList<string>();
while (list.LongCount > 0) while (list.LongCount > 0)
{ {
dequeuedItems.Add(list.Pop()); dequeuedItems.Add(list.Pop());
} }
// Validate // Validate
_ = dequeuedItems.Should().ContainInConsecutiveOrder(_testData.Reverse()); _ = dequeuedItems.Should().ContainInConsecutiveOrder(data.Reverse());
} }
[Fact] [Fact]
public void PopShoudRaiseArgumentOutOfRangeWhenNoMoreElementsFound() public void PopShouldRaiseArgumentOutOfRangeWhenNoMoreElementsFound()
{ {
// Prepare // Prepare
using var list = new RecyclableQueue<string>(_testData); using var list = new RecyclableStack<string>(_testData);
// Act // Act
while (list.LongCount > 0) while (list.LongCount > 0)
{ {
_ = list.Dequeue(); _ = list.Pop();
} }
_ = Assert.Throws<ArgumentOutOfRangeException>(() => list.Dequeue()); _ = Assert.Throws<ArgumentOutOfRangeException>(() => list.Pop());
} }
} }
} }