namespace System.Collections.Concurrent.Tests
{
- public partial class ConcurrentBagTests : ProducerConsumerCollectionTests
+ public class ConcurrentBagTests : ProducerConsumerCollectionTests
{
protected override IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>() => new ConcurrentBag<T>();
protected override IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection) => new ConcurrentBag<int>(collection);
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
+
+ [Theory]
+ [InlineData(false, 0)]
+ [InlineData(false, 1)]
+ [InlineData(false, 20)]
+ [InlineData(true, 0)]
+ [InlineData(true, 1)]
+ [InlineData(true, 20)]
+ public static void Clear_AddItemsToThisAndOtherThreads_EmptyAfterClear(bool addToLocalThread, int otherThreads)
+ {
+ var bag = new ConcurrentBag<int>();
+
+ const int ItemsPerThread = 100;
+
+ for (int repeat = 0; repeat < 2; repeat++)
+ {
+ // If desired, add items on other threads
+ if (addToLocalThread)
+ {
+ for (int i = 0; i < ItemsPerThread; i++) bag.Add(i);
+ }
+
+ // If desired, add items on other threads
+ int origThreadId = Environment.CurrentManagedThreadId;
+ Task.WaitAll((from _ in Enumerable.Range(0, otherThreads)
+ select Task.Factory.StartNew(() =>
+ {
+ Assert.NotEqual(origThreadId, Environment.CurrentManagedThreadId);
+ for (int i = 0; i < ItemsPerThread; i++) bag.Add(i);
+ }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray());
+
+ // Make sure we got the expected number of items, then clear, and make sure it's empty
+ Assert.Equal((ItemsPerThread * otherThreads) + (addToLocalThread ? ItemsPerThread : 0), bag.Count);
+ bag.Clear();
+ Assert.Equal(0, bag.Count);
+ }
+ }
+
+ [Fact]
+ public static void Clear_DuringEnumeration_DoesntAffectEnumeration()
+ {
+ const int ExpectedCount = 100;
+ var bag = new ConcurrentBag<int>(Enumerable.Range(0, ExpectedCount));
+ using (IEnumerator<int> e = bag.GetEnumerator())
+ {
+ bag.Clear();
+ int count = 0;
+ while (e.MoveNext()) count++;
+ Assert.Equal(ExpectedCount, count);
+ }
+ }
+
+ [Theory]
+ [InlineData(1, 10)]
+ [InlineData(3, 100)]
+ [InlineData(8, 1000)]
+ public static void Clear_ConcurrentUsage_NoExceptions(int threadsCount, int itemsPerThread)
+ {
+ var bag = new ConcurrentBag<int>();
+ Task.WaitAll((from i in Enumerable.Range(0, threadsCount) select Task.Factory.StartNew(() =>
+ {
+ var random = new Random();
+ for (int j = 0; j < itemsPerThread; j++)
+ {
+ int item;
+ switch (random.Next(5))
+ {
+ case 0: bag.Add(j); break;
+ case 1: bag.TryPeek(out item); break;
+ case 2: bag.TryTake(out item); break;
+ case 3: bag.Clear(); break;
+ case 4: bag.ToArray(); break;
+ }
+ }
+ }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray());
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Linq;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Collections.Concurrent.Tests
-{
- public partial class ConcurrentBagTests
- {
- [Theory]
- [InlineData(false, 0)]
- [InlineData(false, 1)]
- [InlineData(false, 20)]
- [InlineData(true, 0)]
- [InlineData(true, 1)]
- [InlineData(true, 20)]
- public static void Clear_AddItemsToThisAndOtherThreads_EmptyAfterClear(bool addToLocalThread, int otherThreads)
- {
- var bag = new ConcurrentBag<int>();
-
- const int ItemsPerThread = 100;
-
- for (int repeat = 0; repeat < 2; repeat++)
- {
- // If desired, add items on other threads
- if (addToLocalThread)
- {
- for (int i = 0; i < ItemsPerThread; i++) bag.Add(i);
- }
-
- // If desired, add items on other threads
- int origThreadId = Environment.CurrentManagedThreadId;
- Task.WaitAll((from _ in Enumerable.Range(0, otherThreads)
- select Task.Factory.StartNew(() =>
- {
- Assert.NotEqual(origThreadId, Environment.CurrentManagedThreadId);
- for (int i = 0; i < ItemsPerThread; i++) bag.Add(i);
- }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray());
-
- // Make sure we got the expected number of items, then clear, and make sure it's empty
- Assert.Equal((ItemsPerThread * otherThreads) + (addToLocalThread ? ItemsPerThread : 0), bag.Count);
- bag.Clear();
- Assert.Equal(0, bag.Count);
- }
- }
-
- [Fact]
- public static void Clear_DuringEnumeration_DoesntAffectEnumeration()
- {
- const int ExpectedCount = 100;
- var bag = new ConcurrentBag<int>(Enumerable.Range(0, ExpectedCount));
- using (IEnumerator<int> e = bag.GetEnumerator())
- {
- bag.Clear();
- int count = 0;
- while (e.MoveNext()) count++;
- Assert.Equal(ExpectedCount, count);
- }
- }
-
- [Theory]
- [InlineData(1, 10)]
- [InlineData(3, 100)]
- [InlineData(8, 1000)]
- public static void Clear_ConcurrentUsage_NoExceptions(int threadsCount, int itemsPerThread)
- {
- var bag = new ConcurrentBag<int>();
- Task.WaitAll((from i in Enumerable.Range(0, threadsCount) select Task.Factory.StartNew(() =>
- {
- var random = new Random();
- for (int j = 0; j < itemsPerThread; j++)
- {
- int item;
- switch (random.Next(5))
- {
- case 0: bag.Add(j); break;
- case 1: bag.TryPeek(out item); break;
- case 2: bag.TryTake(out item); break;
- case 3: bag.Clear(); break;
- case 4: bag.ToArray(); break;
- }
- }
- }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray());
- }
- }
-}
namespace System.Collections.Concurrent.Tests
{
- public partial class ConcurrentQueueTests : ProducerConsumerCollectionTests
+ public class ConcurrentQueueTests : ProducerConsumerCollectionTests
{
protected override IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>() => new ConcurrentQueue<T>();
protected override IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection) => new ConcurrentQueue<int>(collection);
Assert.Equal(Enumerable.Range(0, ItemsPerThread * threads), cq.OrderBy(i => i));
}
+ [Theory]
+ [InlineData(0)]
+ [InlineData(1)]
+ [InlineData(1000)]
+ public void Clear_CountMatch(int count)
+ {
+ var q = new ConcurrentQueue<int>(Enumerable.Range(1, count));
+ Assert.Equal(count, q.Count);
+
+ // Clear initial items
+ q.Clear();
+ Assert.Equal(0, q.Count);
+ Assert.True(q.IsEmpty);
+ Assert.Equal(Enumerable.Empty<int>(), q);
+
+ // Clear again has no effect
+ q.Clear();
+ Assert.True(q.IsEmpty);
+
+ // Add more items then clear and verify
+ for (int i = 0; i < count; i++)
+ {
+ q.Enqueue(i);
+ }
+ Assert.Equal(Enumerable.Range(0, count), q);
+ q.Clear();
+ Assert.Equal(0, q.Count);
+ Assert.True(q.IsEmpty);
+ Assert.Equal(Enumerable.Empty<int>(), q);
+
+ // Add items and clear after each item
+ for (int i = 0; i < count; i++)
+ {
+ q.Enqueue(i);
+ Assert.Equal(1, q.Count);
+ q.Clear();
+ Assert.Equal(0, q.Count);
+ }
+ }
+
+ [Fact]
+ public static void Clear_DuringEnumeration_DoesntAffectEnumeration()
+ {
+ const int ExpectedCount = 100;
+ var q = new ConcurrentQueue<int>(Enumerable.Range(0, ExpectedCount));
+ using (IEnumerator<int> beforeClear = q.GetEnumerator())
+ {
+ q.Clear();
+ using (IEnumerator<int> afterClear = q.GetEnumerator())
+ {
+ int count = 0;
+ while (beforeClear.MoveNext()) count++;
+ Assert.Equal(ExpectedCount, count);
+
+ count = 0;
+ while (afterClear.MoveNext()) count++;
+ Assert.Equal(0, count);
+ }
+ }
+ }
+
+ [Theory]
+ [InlineData(1, 10)]
+ [InlineData(3, 100)]
+ [InlineData(8, 1000)]
+ public void Concurrent_Clear_NoExceptions(int threadsCount, int itemsPerThread)
+ {
+ var q = new ConcurrentQueue<int>();
+ Task.WaitAll((from i in Enumerable.Range(0, threadsCount) select Task.Run(() =>
+ {
+ var random = new Random();
+ for (int j = 0; j < itemsPerThread; j++)
+ {
+ switch (random.Next(7))
+ {
+ case 0:
+ int c = q.Count;
+ break;
+ case 1:
+ bool e = q.IsEmpty;
+ break;
+ case 2:
+ q.Enqueue(random.Next(int.MaxValue));
+ break;
+ case 3:
+ q.ToArray();
+ break;
+ case 4:
+ int d;
+ q.TryDequeue(out d);
+ break;
+ case 5:
+ int p;
+ q.TryPeek(out p);
+ break;
+ case 6:
+ q.Clear();
+ break;
+ }
+ }
+ })).ToArray());
+ }
+
/// <summary>Sets an event when finalized.</summary>
private sealed class Finalizable
{
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Collections.Concurrent.Tests
-{
- public partial class ConcurrentQueueTests
- {
- [Theory]
- [InlineData(0)]
- [InlineData(1)]
- [InlineData(1000)]
- public void Clear_CountMatch(int count)
- {
- var q = new ConcurrentQueue<int>(Enumerable.Range(1, count));
- Assert.Equal(count, q.Count);
-
- // Clear initial items
- q.Clear();
- Assert.Equal(0, q.Count);
- Assert.True(q.IsEmpty);
- Assert.Equal(Enumerable.Empty<int>(), q);
-
- // Clear again has no effect
- q.Clear();
- Assert.True(q.IsEmpty);
-
- // Add more items then clear and verify
- for (int i = 0; i < count; i++)
- {
- q.Enqueue(i);
- }
- Assert.Equal(Enumerable.Range(0, count), q);
- q.Clear();
- Assert.Equal(0, q.Count);
- Assert.True(q.IsEmpty);
- Assert.Equal(Enumerable.Empty<int>(), q);
-
- // Add items and clear after each item
- for (int i = 0; i < count; i++)
- {
- q.Enqueue(i);
- Assert.Equal(1, q.Count);
- q.Clear();
- Assert.Equal(0, q.Count);
- }
- }
-
- [Fact]
- public static void Clear_DuringEnumeration_DoesntAffectEnumeration()
- {
- const int ExpectedCount = 100;
- var q = new ConcurrentQueue<int>(Enumerable.Range(0, ExpectedCount));
- using (IEnumerator<int> beforeClear = q.GetEnumerator())
- {
- q.Clear();
- using (IEnumerator<int> afterClear = q.GetEnumerator())
- {
- int count = 0;
- while (beforeClear.MoveNext()) count++;
- Assert.Equal(ExpectedCount, count);
-
- count = 0;
- while (afterClear.MoveNext()) count++;
- Assert.Equal(0, count);
- }
- }
- }
-
- [Theory]
- [InlineData(1, 10)]
- [InlineData(3, 100)]
- [InlineData(8, 1000)]
- public void Concurrent_Clear_NoExceptions(int threadsCount, int itemsPerThread)
- {
- var q = new ConcurrentQueue<int>();
- Task.WaitAll((from i in Enumerable.Range(0, threadsCount) select Task.Run(() =>
- {
- var random = new Random();
- for (int j = 0; j < itemsPerThread; j++)
- {
- switch (random.Next(7))
- {
- case 0:
- int c = q.Count;
- break;
- case 1:
- bool e = q.IsEmpty;
- break;
- case 2:
- q.Enqueue(random.Next(int.MaxValue));
- break;
- case 3:
- q.ToArray();
- break;
- case 4:
- int d;
- q.TryDequeue(out d);
- break;
- case 5:
- int p;
- q.TryPeek(out p);
- break;
- case 6:
- q.Clear();
- break;
- }
- }
- })).ToArray());
- }
- }
-}
<Compile Include="ConcurrentBagTests.cs" />
<Compile Include="ConcurrentDictionary\ConcurrentDictionary.NonGeneric.Tests.cs" />
<Compile Include="ConcurrentDictionary\ConcurrentDictionary.Generic.Tests.cs" />
+ <Compile Include="ConcurrentDictionary\ConcurrentDictionaryExtensions.cs" />
<Compile Include="ConcurrentDictionary\ConcurrentDictionaryTests.cs" />
<Compile Include="ConcurrentQueueTests.cs" />
<Compile Include="ConcurrentStackTests.cs" />
<Link>Common\System\Diagnostics\DebuggerAttributes.cs</Link>
</Compile>
</ItemGroup>
- <ItemGroup Condition="'$(TargetsNetCoreApp)' != 'true'">
- <Compile Include="ConcurrentDictionary\ConcurrentDictionaryExtensions.cs" />
- </ItemGroup>
- <ItemGroup Condition="'$(TargetsNetCoreApp)' == 'true'">
- <Compile Include="ConcurrentBagTests.netcoreapp.cs" />
- <Compile Include="ConcurrentQueueTests.netcoreapp.cs" />
- </ItemGroup>
<ItemGroup>
<Compile Include="$(CommonTestPath)\System\Collections\IEnumerable.NonGeneric.Serialization.Tests.cs">
<Link>Common\System\Collections\IEnumerable.NonGeneric.Serialization.Tests.cs</Link>
namespace System.Collections.Tests
{
- public static partial class BitArray_OperatorsTests
+ public static class BitArray_OperatorsTests
{
private const int BitsPerByte = 8;
private const int BitsPerInt32 = 32;
left.Xor(right);
}
+
+ #region Shift Tests
+
+ public static IEnumerable<object[]> Shift_Data()
+ {
+ foreach (int size in new[] { 0, 1, BitsPerInt32 / 2, BitsPerInt32, BitsPerInt32 + 1, 2 * BitsPerInt32, 2 * BitsPerInt32 + 1 })
+ {
+ foreach (int shift in new[] { 0, 1, size / 2, size - 1, size }.Where(s => s >= 0).Distinct())
+ {
+ yield return new object[] { size, new int[] { /* deliberately empty */ }, shift };
+ yield return new object[] { size, Enumerable.Range(0, size), shift };
+
+ if (size > 1)
+ {
+ foreach (int position in new[] { 0, size / 2, size - 1 })
+ {
+ yield return new object[] { size, new[] { position }, shift };
+ }
+ yield return new object[] { size, new[] { 0, size / 2, size - 1 }, shift };
+ }
+ }
+ }
+ }
+
+ [Theory]
+ [MemberData(nameof(Shift_Data))]
+ public static void RightShift(int length, IEnumerable<int> set, int shift)
+ {
+ BitArray ba = new BitArray(GetBoolArray(length, set));
+ bool[] expected = GetBoolArray(length, set.Select(i => i - shift).Where(i => i >= 0));
+
+ BitArray returned = ba.RightShift(shift);
+ Assert.Same(ba, returned);
+
+ int index = 0;
+ Assert.All(ba.Cast<bool>(), bit => Assert.Equal(expected[index++], bit));
+ }
+
+ [Theory]
+ [MemberData(nameof(Shift_Data))]
+ public static void LeftShift(int length, IEnumerable<int> set, int shift)
+ {
+ BitArray ba = new BitArray(GetBoolArray(length, set));
+ bool[] expected = GetBoolArray(length, set.Select(i => i + shift).Where(i => i < length));
+
+ BitArray returned = ba.LeftShift(shift);
+ Assert.Same(ba, returned);
+
+ int index = 0;
+ Assert.All(ba.Cast<bool>(), bit => Assert.Equal(expected[index++], bit));
+ }
+
+ private static bool[] GetBoolArray(int length, IEnumerable<int> set)
+ {
+ bool[] b = new bool[length];
+ foreach (int position in set)
+ {
+ b[position] = true;
+ }
+ return b;
+ }
+
+ [Fact]
+ public static void LeftShift_Iterator()
+ {
+ BitArray ba = new BitArray(BitsPerInt32 / 2);
+ IEnumerator enumerator = ba.GetEnumerator();
+ Assert.True(enumerator.MoveNext());
+ ba.LeftShift(1);
+ Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
+ }
+
+ [Fact]
+ public static void LeftShift_NegativeCount_ThrowsArgumentOutOfRangeException()
+ {
+ BitArray bitArray = new BitArray(1);
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => bitArray.LeftShift(-1));
+ }
+
+ [Fact]
+ public static void RightShift_Iterator()
+ {
+ BitArray ba = new BitArray(BitsPerInt32 / 2);
+ IEnumerator enumerator = ba.GetEnumerator();
+ Assert.True(enumerator.MoveNext());
+ ba.RightShift(1);
+ Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
+ }
+
+ public static IEnumerable<object[]> RightShift_Hidden_Data()
+ {
+ yield return new object[] { "Constructor", Unset_Visible_Bits(new BitArray(BitsPerInt32 / 2, true)) };
+ yield return new object[] { "Not", Unset_Visible_Bits(new BitArray(BitsPerInt32 / 2, false).Not()) };
+ BitArray setAll = new BitArray(BitsPerInt32 / 2, false);
+ setAll.SetAll(true);
+ yield return new object[] { "SetAll", Unset_Visible_Bits(setAll) };
+ BitArray lengthShort = new BitArray(BitsPerInt32, true);
+ lengthShort.Length = BitsPerInt32 / 2;
+ yield return new object[] { "Length-Short", Unset_Visible_Bits(lengthShort) };
+ BitArray lengthLong = new BitArray(2 * BitsPerInt32, true);
+ lengthLong.Length = BitsPerInt32;
+ yield return new object[] { "Length-Long", Unset_Visible_Bits(lengthLong) };
+ BitArray leftShift = new BitArray(BitsPerInt32 / 2);
+ for (int i = 0; i < leftShift.Length; i++) leftShift[i] = true;
+ yield return new object[] { "LeftShift", leftShift.LeftShift(BitsPerInt32 / 2) };
+ }
+
+ private static BitArray Unset_Visible_Bits(BitArray ba)
+ {
+ for (int i = 0; i < ba.Length; i++) ba[i] = false;
+ return ba;
+ }
+
+ [Theory]
+ [MemberData(nameof(RightShift_Hidden_Data))]
+ public static void RightShift_Hidden(string label, BitArray bits)
+ {
+ _ = label;
+
+ Assert.All(bits.Cast<bool>(), bit => Assert.False(bit));
+ bits.RightShift(1);
+ Assert.All(bits.Cast<bool>(), bit => Assert.False(bit));
+ }
+
+ [Fact]
+ public static void RightShift_NegativeCount_ThrowsArgumentOutOfRangeException()
+ {
+ BitArray bitArray = new BitArray(1);
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => bitArray.RightShift(-1));
+ }
+
+ #endregion
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Xunit;
-
-namespace System.Collections.Tests
-{
- public static partial class BitArray_OperatorsTests
- {
- #region Shift Tests
-
- public static IEnumerable<object[]> Shift_Data()
- {
- foreach (int size in new[] { 0, 1, BitsPerInt32 / 2, BitsPerInt32, BitsPerInt32 + 1, 2 * BitsPerInt32, 2 * BitsPerInt32 + 1 })
- {
- foreach (int shift in new[] { 0, 1, size / 2, size - 1, size }.Where(s => s >= 0).Distinct())
- {
- yield return new object[] { size, new int[] { /* deliberately empty */ }, shift };
- yield return new object[] { size, Enumerable.Range(0, size), shift };
-
- if (size > 1)
- {
- foreach (int position in new[] { 0, size / 2, size - 1 })
- {
- yield return new object[] { size, new[] { position }, shift };
- }
- yield return new object[] { size, new[] { 0, size / 2, size - 1 }, shift };
- }
- }
- }
- }
-
- [Theory]
- [MemberData(nameof(Shift_Data))]
- public static void RightShift(int length, IEnumerable<int> set, int shift)
- {
- BitArray ba = new BitArray(GetBoolArray(length, set));
- bool[] expected = GetBoolArray(length, set.Select(i => i - shift).Where(i => i >= 0));
-
- BitArray returned = ba.RightShift(shift);
- Assert.Same(ba, returned);
-
- int index = 0;
- Assert.All(ba.Cast<bool>(), bit => Assert.Equal(expected[index++], bit));
- }
-
- [Theory]
- [MemberData(nameof(Shift_Data))]
- public static void LeftShift(int length, IEnumerable<int> set, int shift)
- {
- BitArray ba = new BitArray(GetBoolArray(length, set));
- bool[] expected = GetBoolArray(length, set.Select(i => i + shift).Where(i => i < length));
-
- BitArray returned = ba.LeftShift(shift);
- Assert.Same(ba, returned);
-
- int index = 0;
- Assert.All(ba.Cast<bool>(), bit => Assert.Equal(expected[index++], bit));
- }
-
- private static bool[] GetBoolArray(int length, IEnumerable<int> set)
- {
- bool[] b = new bool[length];
- foreach (int position in set)
- {
- b[position] = true;
- }
- return b;
- }
-
- [Fact]
- public static void LeftShift_Iterator()
- {
- BitArray ba = new BitArray(BitsPerInt32 / 2);
- IEnumerator enumerator = ba.GetEnumerator();
- Assert.True(enumerator.MoveNext());
- ba.LeftShift(1);
- Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
- }
-
- [Fact]
- public static void LeftShift_NegativeCount_ThrowsArgumentOutOfRangeException()
- {
- BitArray bitArray = new BitArray(1);
- AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => bitArray.LeftShift(-1));
- }
-
- [Fact]
- public static void RightShift_Iterator()
- {
- BitArray ba = new BitArray(BitsPerInt32 / 2);
- IEnumerator enumerator = ba.GetEnumerator();
- Assert.True(enumerator.MoveNext());
- ba.RightShift(1);
- Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
- }
-
- public static IEnumerable<object[]> RightShift_Hidden_Data()
- {
- yield return new object[] { "Constructor", Unset_Visible_Bits(new BitArray(BitsPerInt32 / 2, true)) };
- yield return new object[] { "Not", Unset_Visible_Bits(new BitArray(BitsPerInt32 / 2, false).Not()) };
- BitArray setAll = new BitArray(BitsPerInt32 / 2, false);
- setAll.SetAll(true);
- yield return new object[] { "SetAll", Unset_Visible_Bits(setAll) };
- BitArray lengthShort = new BitArray(BitsPerInt32, true);
- lengthShort.Length = BitsPerInt32 / 2;
- yield return new object[] { "Length-Short", Unset_Visible_Bits(lengthShort) };
- BitArray lengthLong = new BitArray(2 * BitsPerInt32, true);
- lengthLong.Length = BitsPerInt32;
- yield return new object[] { "Length-Long", Unset_Visible_Bits(lengthLong) };
- BitArray leftShift = new BitArray(BitsPerInt32 / 2);
- for (int i = 0; i < leftShift.Length; i++) leftShift[i] = true;
- yield return new object[] { "LeftShift", leftShift.LeftShift(BitsPerInt32 / 2) };
- }
-
- private static BitArray Unset_Visible_Bits(BitArray ba)
- {
- for (int i = 0; i < ba.Length; i++) ba[i] = false;
- return ba;
- }
-
- [Theory]
- [MemberData(nameof(RightShift_Hidden_Data))]
- public static void RightShift_Hidden(string label, BitArray bits)
- {
- _ = label;
-
- Assert.All(bits.Cast<bool>(), bit => Assert.False(bit));
- bits.RightShift(1);
- Assert.All(bits.Cast<bool>(), bit => Assert.False(bit));
- }
-
- [Fact]
- public static void RightShift_NegativeCount_ThrowsArgumentOutOfRangeException()
- {
- BitArray bitArray = new BitArray(1);
- AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => bitArray.RightShift(-1));
- }
-
- #endregion
- }
-}
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Threading.Tasks;
+using Xunit;
+
+namespace Generic.Dictionary
+{
+ public class DictionaryConcurrentAccessDetectionTests
+ {
+ private async Task DictionaryConcurrentAccessDetection<TKey, TValue>(Dictionary<TKey, TValue> dictionary, bool isValueType, object comparer, Action<Dictionary<TKey, TValue>> add, Action<Dictionary<TKey, TValue>> get, Action<Dictionary<TKey, TValue>> remove, Action<Dictionary<TKey, TValue>> removeOutParam)
+ {
+ Task task = Task.Factory.StartNew(() =>
+ {
+ // Get the Dictionary into a corrupted state, as if it had been corrupted by concurrent access.
+ // We this deterministically by clearing the _entries array using reflection;
+ // this means that every Entry struct has a 'next' field of zero, which causes the infinite loop
+ // that we want Dictionary to break out of
+ FieldInfo entriesType = dictionary.GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance);
+ Array entriesInstance = (Array)entriesType.GetValue(dictionary);
+ Array entryArray = (Array)Activator.CreateInstance(entriesInstance.GetType(), new object[] { ((IDictionary)dictionary).Count });
+ entriesType.SetValue(dictionary, entryArray);
+
+ Assert.Equal(comparer, dictionary.GetType().GetField("_comparer", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(dictionary));
+ Assert.Equal(isValueType, dictionary.GetType().GetGenericArguments()[0].IsValueType);
+ Assert.Throws<InvalidOperationException>(() => add(dictionary));
+ Assert.Throws<InvalidOperationException>(() => get(dictionary));
+ Assert.Throws<InvalidOperationException>(() => remove(dictionary));
+ Assert.Throws<InvalidOperationException>(() => removeOutParam(dictionary));
+ }, TaskCreationOptions.LongRunning);
+
+ // If Dictionary regresses, we do not want to hang here indefinitely
+ Assert.True((await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(60))) == task) && task.IsCompletedSuccessfully);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData(typeof(CustomEqualityComparerInt32ValueType))]
+ public async Task DictionaryConcurrentAccessDetection_ValueTypeKey(Type comparerType)
+ {
+ IEqualityComparer<int> customComparer = null;
+
+ Dictionary<int, int> dic = comparerType == null ?
+ new Dictionary<int, int>() :
+ new Dictionary<int, int>((customComparer = (IEqualityComparer<int>)Activator.CreateInstance(comparerType)));
+
+ dic.Add(1, 1);
+
+ await DictionaryConcurrentAccessDetection(dic,
+ typeof(int).IsValueType,
+ customComparer,
+ d => d.Add(1, 1),
+ d => { var v = d[1]; },
+ d => d.Remove(1),
+ d => d.Remove(1, out int value));
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData(typeof(CustomEqualityComparerDummyRefType))]
+ public async Task DictionaryConcurrentAccessDetection_ReferenceTypeKey(Type comparerType)
+ {
+ IEqualityComparer<DummyRefType> customComparer = null;
+
+ Dictionary<DummyRefType, DummyRefType> dic = comparerType == null ?
+ new Dictionary<DummyRefType, DummyRefType>() :
+ new Dictionary<DummyRefType, DummyRefType>((customComparer = (IEqualityComparer<DummyRefType>)Activator.CreateInstance(comparerType)));
+
+ var keyValueSample = new DummyRefType() { Value = 1 };
+
+ dic.Add(keyValueSample, keyValueSample);
+
+ await DictionaryConcurrentAccessDetection(dic,
+ typeof(DummyRefType).IsValueType,
+ customComparer,
+ d => d.Add(keyValueSample, keyValueSample),
+ d => { var v = d[keyValueSample]; },
+ d => d.Remove(keyValueSample),
+ d => d.Remove(keyValueSample, out DummyRefType value));
+ }
+ }
+
+ // We use a custom type instead of string because string use optimized comparer https://github.com/dotnet/coreclr/blob/master/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs#L79
+ // We want to test case with _comparer = null
+ public class DummyRefType
+ {
+ public int Value { get; set; }
+ public override bool Equals(object obj)
+ {
+ return ((DummyRefType)obj).Equals(this.Value);
+ }
+
+ public override int GetHashCode()
+ {
+ return Value.GetHashCode();
+ }
+ }
+
+ public class CustomEqualityComparerDummyRefType : EqualityComparer<DummyRefType>
+ {
+ public override bool Equals(DummyRefType x, DummyRefType y)
+ {
+ return x.Value == y.Value;
+ }
+
+ public override int GetHashCode(DummyRefType obj)
+ {
+ return obj.GetHashCode();
+ }
+ }
+
+ public class CustomEqualityComparerInt32ValueType : EqualityComparer<int>
+ {
+ public override bool Equals(int x, int y)
+ {
+ return EqualityComparer<int>.Default.Equals(x, y);
+ }
+
+ public override int GetHashCode(int obj)
+ {
+ return EqualityComparer<int>.Default.GetHashCode(obj);
+ }
+ }
+}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Generic.Dictionary
-{
- public class DictionaryConcurrentAccessDetectionTests
- {
- private async Task DictionaryConcurrentAccessDetection<TKey, TValue>(Dictionary<TKey, TValue> dictionary, bool isValueType, object comparer, Action<Dictionary<TKey, TValue>> add, Action<Dictionary<TKey, TValue>> get, Action<Dictionary<TKey, TValue>> remove, Action<Dictionary<TKey, TValue>> removeOutParam)
- {
- Task task = Task.Factory.StartNew(() =>
- {
- // Get the Dictionary into a corrupted state, as if it had been corrupted by concurrent access.
- // We this deterministically by clearing the _entries array using reflection;
- // this means that every Entry struct has a 'next' field of zero, which causes the infinite loop
- // that we want Dictionary to break out of
- FieldInfo entriesType = dictionary.GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance);
- Array entriesInstance = (Array)entriesType.GetValue(dictionary);
- Array entryArray = (Array)Activator.CreateInstance(entriesInstance.GetType(), new object[] { ((IDictionary)dictionary).Count });
- entriesType.SetValue(dictionary, entryArray);
-
- Assert.Equal(comparer, dictionary.GetType().GetField("_comparer", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(dictionary));
- Assert.Equal(isValueType, dictionary.GetType().GetGenericArguments()[0].IsValueType);
- Assert.Throws<InvalidOperationException>(() => add(dictionary));
- Assert.Throws<InvalidOperationException>(() => get(dictionary));
- Assert.Throws<InvalidOperationException>(() => remove(dictionary));
- Assert.Throws<InvalidOperationException>(() => removeOutParam(dictionary));
- }, TaskCreationOptions.LongRunning);
-
- // If Dictionary regresses, we do not want to hang here indefinitely
- Assert.True((await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(60))) == task) && task.IsCompletedSuccessfully);
- }
-
- [Theory]
- [InlineData(null)]
- [InlineData(typeof(CustomEqualityComparerInt32ValueType))]
- public async Task DictionaryConcurrentAccessDetection_ValueTypeKey(Type comparerType)
- {
- IEqualityComparer<int> customComparer = null;
-
- Dictionary<int, int> dic = comparerType == null ?
- new Dictionary<int, int>() :
- new Dictionary<int, int>((customComparer = (IEqualityComparer<int>)Activator.CreateInstance(comparerType)));
-
- dic.Add(1, 1);
-
- await DictionaryConcurrentAccessDetection(dic,
- typeof(int).IsValueType,
- customComparer,
- d => d.Add(1, 1),
- d => { var v = d[1]; },
- d => d.Remove(1),
- d => d.Remove(1, out int value));
- }
-
- [Theory]
- [InlineData(null)]
- [InlineData(typeof(CustomEqualityComparerDummyRefType))]
- public async Task DictionaryConcurrentAccessDetection_ReferenceTypeKey(Type comparerType)
- {
- IEqualityComparer<DummyRefType> customComparer = null;
-
- Dictionary<DummyRefType, DummyRefType> dic = comparerType == null ?
- new Dictionary<DummyRefType, DummyRefType>() :
- new Dictionary<DummyRefType, DummyRefType>((customComparer = (IEqualityComparer<DummyRefType>)Activator.CreateInstance(comparerType)));
-
- var keyValueSample = new DummyRefType() { Value = 1 };
-
- dic.Add(keyValueSample, keyValueSample);
-
- await DictionaryConcurrentAccessDetection(dic,
- typeof(DummyRefType).IsValueType,
- customComparer,
- d => d.Add(keyValueSample, keyValueSample),
- d => { var v = d[keyValueSample]; },
- d => d.Remove(keyValueSample),
- d => d.Remove(keyValueSample, out DummyRefType value));
- }
- }
-
- // We use a custom type instead of string because string use optimized comparer https://github.com/dotnet/coreclr/blob/master/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs#L79
- // We want to test case with _comparer = null
- public class DummyRefType
- {
- public int Value { get; set; }
- public override bool Equals(object obj)
- {
- return ((DummyRefType)obj).Equals(this.Value);
- }
-
- public override int GetHashCode()
- {
- return Value.GetHashCode();
- }
- }
-
- public class CustomEqualityComparerDummyRefType : EqualityComparer<DummyRefType>
- {
- public override bool Equals(DummyRefType x, DummyRefType y)
- {
- return x.Value == y.Value;
- }
-
- public override int GetHashCode(DummyRefType obj)
- {
- return obj.GetHashCode();
- }
- }
-
- public class CustomEqualityComparerInt32ValueType : EqualityComparer<int>
- {
- public override bool Equals(int x, int y)
- {
- return EqualityComparer<int>.Default.Equals(x, y);
- }
-
- public override int GetHashCode(int obj)
- {
- return EqualityComparer<int>.Default.GetHashCode(obj);
- }
- }
-}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using Common.System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
/// <summary>
/// Contains tests that ensure the correctness of the Dictionary class.
/// </summary>
- public abstract partial class Dictionary_Generic_Tests<TKey, TValue> : IDictionary_Generic_Tests<TKey, TValue>
+ public abstract class Dictionary_Generic_Tests<TKey, TValue> : IDictionary_Generic_Tests<TKey, TValue>
{
protected override ModifyOperation ModifyEnumeratorThrows => ModifyOperation.Add | ModifyOperation.Insert;
}
#endregion
+
+ #region Remove(TKey)
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void Dictionary_Generic_RemoveKey_ValidKeyNotContainedInDictionary(int count)
+ {
+ Dictionary<TKey, TValue> dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
+ TValue value;
+ TKey missingKey = GetNewKey(dictionary);
+
+ Assert.False(dictionary.Remove(missingKey, out value));
+ Assert.Equal(count, dictionary.Count);
+ Assert.Equal(default(TValue), value);
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void Dictionary_Generic_RemoveKey_ValidKeyContainedInDictionary(int count)
+ {
+ Dictionary<TKey, TValue> dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
+ TKey missingKey = GetNewKey(dictionary);
+ TValue outValue;
+ TValue inValue = CreateTValue(count);
+
+ dictionary.Add(missingKey, inValue);
+ Assert.True(dictionary.Remove(missingKey, out outValue));
+ Assert.Equal(count, dictionary.Count);
+ Assert.Equal(inValue, outValue);
+ Assert.False(dictionary.TryGetValue(missingKey, out outValue));
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void Dictionary_Generic_RemoveKey_DefaultKeyNotContainedInDictionary(int count)
+ {
+ Dictionary<TKey, TValue> dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
+ TValue outValue;
+
+ if (DefaultValueAllowed)
+ {
+ TKey missingKey = default(TKey);
+ while (dictionary.ContainsKey(missingKey))
+ dictionary.Remove(missingKey);
+ Assert.False(dictionary.Remove(missingKey, out outValue));
+ Assert.Equal(default(TValue), outValue);
+ }
+ else
+ {
+ TValue initValue = CreateTValue(count);
+ outValue = initValue;
+ Assert.Throws<ArgumentNullException>(() => dictionary.Remove(default(TKey), out outValue));
+ Assert.Equal(initValue, outValue);
+ }
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void Dictionary_Generic_RemoveKey_DefaultKeyContainedInDictionary(int count)
+ {
+ if (DefaultValueAllowed)
+ {
+ Dictionary<TKey, TValue> dictionary = (Dictionary<TKey, TValue>)(GenericIDictionaryFactory(count));
+ TKey missingKey = default(TKey);
+ TValue value;
+
+ dictionary.TryAdd(missingKey, default(TValue));
+ Assert.True(dictionary.Remove(missingKey, out value));
+ }
+ }
+
+ [Fact]
+ public void Dictionary_Generic_Remove_RemoveFirstEnumerationContinues()
+ {
+ Dictionary<TKey,TValue> dict = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(3);
+ using (var enumerator = dict.GetEnumerator())
+ {
+ enumerator.MoveNext();
+ TKey key = enumerator.Current.Key;
+ enumerator.MoveNext();
+ dict.Remove(key);
+ Assert.True(enumerator.MoveNext());
+ Assert.False(enumerator.MoveNext());
+ }
+ }
+
+ [Fact]
+ public void Dictionary_Generic_Remove_RemoveCurrentEnumerationContinues()
+ {
+ Dictionary<TKey, TValue> dict = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(3);
+ using (var enumerator = dict.GetEnumerator())
+ {
+ enumerator.MoveNext();
+ enumerator.MoveNext();
+ dict.Remove(enumerator.Current.Key);
+ Assert.True(enumerator.MoveNext());
+ Assert.False(enumerator.MoveNext());
+ }
+ }
+
+ [Fact]
+ public void Dictionary_Generic_Remove_RemoveLastEnumerationFinishes()
+ {
+ Dictionary<TKey, TValue> dict = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(3);
+ TKey key = default;
+ using (var enumerator = dict.GetEnumerator())
+ {
+ while (enumerator.MoveNext())
+ {
+ key = enumerator.Current.Key;
+ }
+ }
+ using (var enumerator = dict.GetEnumerator())
+ {
+ enumerator.MoveNext();
+ enumerator.MoveNext();
+ dict.Remove(key);
+ Assert.False(enumerator.MoveNext());
+ }
+ }
+
+ #endregion
+
+ #region EnsureCapacity
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void EnsureCapacity_Generic_RequestingLargerCapacity_DoesInvalidateEnumeration(int count)
+ {
+ var dictionary = (Dictionary<TKey, TValue>)(GenericIDictionaryFactory(count));
+ var capacity = dictionary.EnsureCapacity(0);
+ var enumerator = dictionary.GetEnumerator();
+
+ dictionary.EnsureCapacity(capacity + 1); // Verify EnsureCapacity does invalidate enumeration
+
+ Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
+ }
+
+ [Fact]
+ public void EnsureCapacity_Generic_NegativeCapacityRequested_Throws()
+ {
+ var dictionary = new Dictionary<TKey, TValue>();
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => dictionary.EnsureCapacity(-1));
+ }
+
+ [Fact]
+ public void EnsureCapacity_Generic_DictionaryNotInitialized_RequestedZero_ReturnsZero()
+ {
+ var dictionary = new Dictionary<TKey, TValue>();
+ Assert.Equal(0, dictionary.EnsureCapacity(0));
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(4)]
+ public void EnsureCapacity_Generic_DictionaryNotInitialized_RequestedNonZero_CapacityIsSetToAtLeastTheRequested(int requestedCapacity)
+ {
+ var dictionary = new Dictionary<TKey, TValue>();
+ Assert.InRange(dictionary.EnsureCapacity(requestedCapacity), requestedCapacity, int.MaxValue);
+ }
+
+ [Theory]
+ [InlineData(3)]
+ [InlineData(7)]
+ public void EnsureCapacity_Generic_RequestedCapacitySmallerThanCurrent_CapacityUnchanged(int currentCapacity)
+ {
+ Dictionary<TKey, TValue> dictionary;
+
+ // assert capacity remains the same when ensuring a capacity smaller or equal than existing
+ for (int i = 0; i <= currentCapacity; i++)
+ {
+ dictionary = new Dictionary<TKey, TValue>(currentCapacity);
+ Assert.Equal(currentCapacity, dictionary.EnsureCapacity(i));
+ }
+ }
+
+ [Theory]
+ [InlineData(7)]
+ public void EnsureCapacity_Generic_ExistingCapacityRequested_SameValueReturned(int capacity)
+ {
+ var dictionary = new Dictionary<TKey, TValue>(capacity);
+ Assert.Equal(capacity, dictionary.EnsureCapacity(capacity));
+
+ dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(capacity);
+ Assert.Equal(capacity, dictionary.EnsureCapacity(capacity));
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(4)]
+ public void EnsureCapacity_Generic_EnsureCapacityCalledTwice_ReturnsSameValue(int count)
+ {
+ var dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
+ int capacity = dictionary.EnsureCapacity(0);
+ Assert.Equal(capacity, dictionary.EnsureCapacity(0));
+
+ dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
+ capacity = dictionary.EnsureCapacity(count);
+ Assert.Equal(capacity, dictionary.EnsureCapacity(count));
+
+ dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
+ capacity = dictionary.EnsureCapacity(count + 1);
+ Assert.Equal(capacity, dictionary.EnsureCapacity(count + 1));
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(5)]
+ [InlineData(7)]
+ public void EnsureCapacity_Generic_DictionaryNotEmpty_RequestedSmallerThanCount_ReturnsAtLeastSizeOfCount(int count)
+ {
+ var dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
+ Assert.InRange(dictionary.EnsureCapacity(count - 1), count, int.MaxValue);
+ }
+
+ [Theory]
+ [InlineData(7)]
+ [InlineData(20)]
+ public void EnsureCapacity_Generic_DictionaryNotEmpty_SetsToAtLeastTheRequested(int count)
+ {
+ var dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
+
+ // get current capacity
+ int currentCapacity = dictionary.EnsureCapacity(0);
+
+ // assert we can update to a larger capacity
+ int newCapacity = dictionary.EnsureCapacity(currentCapacity * 2);
+ Assert.InRange(newCapacity, currentCapacity * 2, int.MaxValue);
+ }
+
+ [Fact]
+ public void EnsureCapacity_Generic_CapacityIsSetToPrimeNumberLargerOrEqualToRequested()
+ {
+ var dictionary = new Dictionary<TKey, TValue>();
+ Assert.Equal(17, dictionary.EnsureCapacity(17));
+
+ dictionary = new Dictionary<TKey, TValue>();
+ Assert.Equal(17, dictionary.EnsureCapacity(15));
+
+ dictionary = new Dictionary<TKey, TValue>();
+ Assert.Equal(17, dictionary.EnsureCapacity(13));
+ }
+
+ #endregion
+
+ #region TrimExcess
+
+ [Fact]
+ public void TrimExcess_Generic_NegativeCapacity_Throw()
+ {
+ var dictionary = new Dictionary<TKey, TValue>();
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => dictionary.TrimExcess(-1));
+ }
+
+ [Theory]
+ [InlineData(20)]
+ [InlineData(23)]
+ public void TrimExcess_Generic_CapacitySmallerThanCount_Throws(int suggestedCapacity)
+ {
+ var dictionary = new Dictionary<TKey, TValue>();
+ dictionary.Add(GetNewKey(dictionary), CreateTValue(0));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => dictionary.TrimExcess(0));
+
+ dictionary = new Dictionary<TKey, TValue>(suggestedCapacity);
+ dictionary.Add(GetNewKey(dictionary), CreateTValue(0));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => dictionary.TrimExcess(0));
+ }
+
+ [Fact]
+ public void TrimExcess_Generic_LargeInitialCapacity_TrimReducesSize()
+ {
+ var dictionary = new Dictionary<TKey, TValue>(20);
+ dictionary.TrimExcess(7);
+ Assert.Equal(7, dictionary.EnsureCapacity(0));
+ }
+
+ [Theory]
+ [InlineData(20)]
+ [InlineData(23)]
+ public void TrimExcess_Generic_TrimToLargerThanExistingCapacity_DoesNothing(int suggestedCapacity)
+ {
+ var dictionary = new Dictionary<TKey, TValue>();
+ int capacity = dictionary.EnsureCapacity(0);
+ dictionary.TrimExcess(suggestedCapacity);
+ Assert.Equal(capacity, dictionary.EnsureCapacity(0));
+
+ dictionary = new Dictionary<TKey, TValue>(suggestedCapacity/2);
+ capacity = dictionary.EnsureCapacity(0);
+ dictionary.TrimExcess(suggestedCapacity);
+ Assert.Equal(capacity, dictionary.EnsureCapacity(0));
+ }
+
+ [Fact]
+ public void TrimExcess_Generic_DictionaryNotInitialized_CapacityRemainsAsMinPossible()
+ {
+ var dictionary = new Dictionary<TKey, TValue>();
+ Assert.Equal(0, dictionary.EnsureCapacity(0));
+ dictionary.TrimExcess();
+ Assert.Equal(0, dictionary.EnsureCapacity(0));
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(85)]
+ [InlineData(89)]
+ public void TrimExcess_Generic_ClearThenTrimNonEmptyDictionary_SetsCapacityTo3(int count)
+ {
+ Dictionary<TKey, TValue> dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
+ Assert.Equal(count, dictionary.Count);
+ // The smallest possible capacity size after clearing a dictionary is 3
+ dictionary.Clear();
+ dictionary.TrimExcess();
+ Assert.Equal(3, dictionary.EnsureCapacity(0));
+ }
+
+ [Theory]
+ [InlineData(85)]
+ [InlineData(89)]
+ public void TrimExcess_NoArguments_TrimsToAtLeastCount(int count)
+ {
+ var dictionary = new Dictionary<int, int>(20);
+ for (int i = 0; i < count; i++)
+ {
+ dictionary.Add(i, 0);
+ }
+ dictionary.TrimExcess();
+ Assert.InRange(dictionary.EnsureCapacity(0), count, int.MaxValue);
+ }
+
+ [Theory]
+ [InlineData(85)]
+ [InlineData(89)]
+ public void TrimExcess_WithArguments_OnDictionaryWithManyElementsRemoved_TrimsToAtLeastRequested(int finalCount)
+ {
+ const int InitToFinalRatio = 10;
+ int initialCount = InitToFinalRatio * finalCount;
+ var dictionary = new Dictionary<int, int>(initialCount);
+ Assert.InRange(dictionary.EnsureCapacity(0), initialCount, int.MaxValue);
+ for (int i = 0; i < initialCount; i++)
+ {
+ dictionary.Add(i, 0);
+ }
+ for (int i = 0; i < initialCount - finalCount; i++)
+ {
+ dictionary.Remove(i);
+ }
+ for (int i = InitToFinalRatio; i > 0; i--)
+ {
+ dictionary.TrimExcess(i * finalCount);
+ Assert.InRange(dictionary.EnsureCapacity(0), i * finalCount, int.MaxValue);
+ }
+ }
+
+ [Theory]
+ [InlineData(1000, 900, 5000, 85, 89)]
+ [InlineData(1000, 400, 5000, 85, 89)]
+ [InlineData(1000, 900, 500, 85, 89)]
+ [InlineData(1000, 400, 500, 85, 89)]
+ [InlineData(1000, 400, 500, 1, 3)]
+ public void TrimExcess_NoArgument_TrimAfterEachBulkAddOrRemove_TrimsToAtLeastCount(int initialCount, int numRemove, int numAdd, int newCount, int newCapacity)
+ {
+ Random random = new Random(32);
+ var dictionary = new Dictionary<int, int>();
+ dictionary.TrimExcess();
+ Assert.InRange(dictionary.EnsureCapacity(0), dictionary.Count, int.MaxValue);
+
+ var initialKeys = new int[initialCount];
+ for (int i = 0; i < initialCount; i++)
+ {
+ initialKeys[i] = i;
+ }
+ random.Shuffle(initialKeys);
+ foreach (var key in initialKeys)
+ {
+ dictionary.Add(key, 0);
+ }
+ dictionary.TrimExcess();
+ Assert.InRange(dictionary.EnsureCapacity(0), dictionary.Count, int.MaxValue);
+
+ random.Shuffle(initialKeys);
+ for (int i = 0; i < numRemove; i++)
+ {
+ dictionary.Remove(initialKeys[i]);
+ }
+ dictionary.TrimExcess();
+ Assert.InRange(dictionary.EnsureCapacity(0), dictionary.Count, int.MaxValue);
+
+ var moreKeys = new int[numAdd];
+ for (int i = 0; i < numAdd; i++)
+ {
+ moreKeys[i] = i + initialCount;
+ }
+ random.Shuffle(moreKeys);
+ foreach (var key in moreKeys)
+ {
+ dictionary.Add(key, 0);
+ }
+ int currentCount = dictionary.Count;
+ dictionary.TrimExcess();
+ Assert.InRange(dictionary.EnsureCapacity(0), currentCount, int.MaxValue);
+
+ int[] existingKeys = new int[currentCount];
+ Array.Copy(initialKeys, numRemove, existingKeys, 0, initialCount - numRemove);
+ Array.Copy(moreKeys, 0, existingKeys, initialCount - numRemove, numAdd);
+ random.Shuffle(existingKeys);
+ for (int i = 0; i < currentCount - newCount; i++)
+ {
+ dictionary.Remove(existingKeys[i]);
+ }
+ dictionary.TrimExcess();
+ int finalCapacity = dictionary.EnsureCapacity(0);
+ Assert.InRange(finalCapacity, newCount, initialCount);
+ Assert.Equal(newCapacity, finalCapacity);
+ }
+
+ [Fact]
+ public void TrimExcess_DictionaryHasElementsChainedWithSameHashcode_Success()
+ {
+ var dictionary = new Dictionary<string, int>(7);
+ for (int i = 0; i < 4; i++)
+ {
+ dictionary.Add(i.ToString(), 0);
+ }
+ var s_64bit = new string[] { "95e85f8e-67a3-4367-974f-dd24d8bb2ca2", "eb3d6fe9-de64-43a9-8f58-bddea727b1ca" };
+ var s_32bit = new string[] { "25b1f130-7517-48e3-96b0-9da44e8bfe0e", "ba5a3625-bc38-4bf1-a707-a3cfe2158bae" };
+ string[] chained = (Environment.Is64BitProcess ? s_64bit : s_32bit).ToArray();
+ dictionary.Add(chained[0], 0);
+ dictionary.Add(chained[1], 0);
+ for (int i = 0; i < 4; i++)
+ {
+ dictionary.Remove(i.ToString());
+ }
+ dictionary.TrimExcess(3);
+ Assert.Equal(2, dictionary.Count);
+ int val;
+ Assert.True(dictionary.TryGetValue(chained[0], out val));
+ Assert.True(dictionary.TryGetValue(chained[1], out val));
+ }
+
+ [Fact]
+ public void TrimExcess_Generic_DoesInvalidateEnumeration()
+ {
+ var dictionary = new Dictionary<TKey, TValue>(20);
+ var enumerator = dictionary.GetEnumerator();
+
+ dictionary.TrimExcess(7); // Verify TrimExcess does invalidate enumeration
+
+ Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
+ }
+
+ #endregion
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Common.System;
-using Xunit;
-
-namespace System.Collections.Tests
-{
- /// <summary>
- /// Contains tests that ensure the correctness of the Dictionary class.
- /// </summary>
- public abstract partial class Dictionary_Generic_Tests<TKey, TValue> : IDictionary_Generic_Tests<TKey, TValue>
- {
- #region Remove(TKey)
-
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void Dictionary_Generic_RemoveKey_ValidKeyNotContainedInDictionary(int count)
- {
- Dictionary<TKey, TValue> dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
- TValue value;
- TKey missingKey = GetNewKey(dictionary);
-
- Assert.False(dictionary.Remove(missingKey, out value));
- Assert.Equal(count, dictionary.Count);
- Assert.Equal(default(TValue), value);
- }
-
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void Dictionary_Generic_RemoveKey_ValidKeyContainedInDictionary(int count)
- {
- Dictionary<TKey, TValue> dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
- TKey missingKey = GetNewKey(dictionary);
- TValue outValue;
- TValue inValue = CreateTValue(count);
-
- dictionary.Add(missingKey, inValue);
- Assert.True(dictionary.Remove(missingKey, out outValue));
- Assert.Equal(count, dictionary.Count);
- Assert.Equal(inValue, outValue);
- Assert.False(dictionary.TryGetValue(missingKey, out outValue));
- }
-
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void Dictionary_Generic_RemoveKey_DefaultKeyNotContainedInDictionary(int count)
- {
- Dictionary<TKey, TValue> dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
- TValue outValue;
-
- if (DefaultValueAllowed)
- {
- TKey missingKey = default(TKey);
- while (dictionary.ContainsKey(missingKey))
- dictionary.Remove(missingKey);
- Assert.False(dictionary.Remove(missingKey, out outValue));
- Assert.Equal(default(TValue), outValue);
- }
- else
- {
- TValue initValue = CreateTValue(count);
- outValue = initValue;
- Assert.Throws<ArgumentNullException>(() => dictionary.Remove(default(TKey), out outValue));
- Assert.Equal(initValue, outValue);
- }
- }
-
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void Dictionary_Generic_RemoveKey_DefaultKeyContainedInDictionary(int count)
- {
- if (DefaultValueAllowed)
- {
- Dictionary<TKey, TValue> dictionary = (Dictionary<TKey, TValue>)(GenericIDictionaryFactory(count));
- TKey missingKey = default(TKey);
- TValue value;
-
- dictionary.TryAdd(missingKey, default(TValue));
- Assert.True(dictionary.Remove(missingKey, out value));
- }
- }
-
- [Fact]
- public void Dictionary_Generic_Remove_RemoveFirstEnumerationContinues()
- {
- Dictionary<TKey,TValue> dict = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(3);
- using (var enumerator = dict.GetEnumerator())
- {
- enumerator.MoveNext();
- TKey key = enumerator.Current.Key;
- enumerator.MoveNext();
- dict.Remove(key);
- Assert.True(enumerator.MoveNext());
- Assert.False(enumerator.MoveNext());
- }
- }
-
- [Fact]
- public void Dictionary_Generic_Remove_RemoveCurrentEnumerationContinues()
- {
- Dictionary<TKey, TValue> dict = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(3);
- using (var enumerator = dict.GetEnumerator())
- {
- enumerator.MoveNext();
- enumerator.MoveNext();
- dict.Remove(enumerator.Current.Key);
- Assert.True(enumerator.MoveNext());
- Assert.False(enumerator.MoveNext());
- }
- }
-
- [Fact]
- public void Dictionary_Generic_Remove_RemoveLastEnumerationFinishes()
- {
- Dictionary<TKey, TValue> dict = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(3);
- TKey key = default;
- using (var enumerator = dict.GetEnumerator())
- {
- while (enumerator.MoveNext())
- {
- key = enumerator.Current.Key;
- }
- }
- using (var enumerator = dict.GetEnumerator())
- {
- enumerator.MoveNext();
- enumerator.MoveNext();
- dict.Remove(key);
- Assert.False(enumerator.MoveNext());
- }
- }
-
- #endregion
-
- #region EnsureCapacity
-
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void EnsureCapacity_Generic_RequestingLargerCapacity_DoesInvalidateEnumeration(int count)
- {
- var dictionary = (Dictionary<TKey, TValue>)(GenericIDictionaryFactory(count));
- var capacity = dictionary.EnsureCapacity(0);
- var enumerator = dictionary.GetEnumerator();
-
- dictionary.EnsureCapacity(capacity + 1); // Verify EnsureCapacity does invalidate enumeration
-
- Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
- }
-
- [Fact]
- public void EnsureCapacity_Generic_NegativeCapacityRequested_Throws()
- {
- var dictionary = new Dictionary<TKey, TValue>();
- AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => dictionary.EnsureCapacity(-1));
- }
-
- [Fact]
- public void EnsureCapacity_Generic_DictionaryNotInitialized_RequestedZero_ReturnsZero()
- {
- var dictionary = new Dictionary<TKey, TValue>();
- Assert.Equal(0, dictionary.EnsureCapacity(0));
- }
-
- [Theory]
- [InlineData(1)]
- [InlineData(2)]
- [InlineData(3)]
- [InlineData(4)]
- public void EnsureCapacity_Generic_DictionaryNotInitialized_RequestedNonZero_CapacityIsSetToAtLeastTheRequested(int requestedCapacity)
- {
- var dictionary = new Dictionary<TKey, TValue>();
- Assert.InRange(dictionary.EnsureCapacity(requestedCapacity), requestedCapacity, int.MaxValue);
- }
-
- [Theory]
- [InlineData(3)]
- [InlineData(7)]
- public void EnsureCapacity_Generic_RequestedCapacitySmallerThanCurrent_CapacityUnchanged(int currentCapacity)
- {
- Dictionary<TKey, TValue> dictionary;
-
- // assert capacity remains the same when ensuring a capacity smaller or equal than existing
- for (int i = 0; i <= currentCapacity; i++)
- {
- dictionary = new Dictionary<TKey, TValue>(currentCapacity);
- Assert.Equal(currentCapacity, dictionary.EnsureCapacity(i));
- }
- }
-
- [Theory]
- [InlineData(7)]
- public void EnsureCapacity_Generic_ExistingCapacityRequested_SameValueReturned(int capacity)
- {
- var dictionary = new Dictionary<TKey, TValue>(capacity);
- Assert.Equal(capacity, dictionary.EnsureCapacity(capacity));
-
- dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(capacity);
- Assert.Equal(capacity, dictionary.EnsureCapacity(capacity));
- }
-
- [Theory]
- [InlineData(0)]
- [InlineData(1)]
- [InlineData(2)]
- [InlineData(3)]
- [InlineData(4)]
- public void EnsureCapacity_Generic_EnsureCapacityCalledTwice_ReturnsSameValue(int count)
- {
- var dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
- int capacity = dictionary.EnsureCapacity(0);
- Assert.Equal(capacity, dictionary.EnsureCapacity(0));
-
- dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
- capacity = dictionary.EnsureCapacity(count);
- Assert.Equal(capacity, dictionary.EnsureCapacity(count));
-
- dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
- capacity = dictionary.EnsureCapacity(count + 1);
- Assert.Equal(capacity, dictionary.EnsureCapacity(count + 1));
- }
-
- [Theory]
- [InlineData(1)]
- [InlineData(5)]
- [InlineData(7)]
- public void EnsureCapacity_Generic_DictionaryNotEmpty_RequestedSmallerThanCount_ReturnsAtLeastSizeOfCount(int count)
- {
- var dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
- Assert.InRange(dictionary.EnsureCapacity(count - 1), count, int.MaxValue);
- }
-
- [Theory]
- [InlineData(7)]
- [InlineData(20)]
- public void EnsureCapacity_Generic_DictionaryNotEmpty_SetsToAtLeastTheRequested(int count)
- {
- var dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
-
- // get current capacity
- int currentCapacity = dictionary.EnsureCapacity(0);
-
- // assert we can update to a larger capacity
- int newCapacity = dictionary.EnsureCapacity(currentCapacity * 2);
- Assert.InRange(newCapacity, currentCapacity * 2, int.MaxValue);
- }
-
- [Fact]
- public void EnsureCapacity_Generic_CapacityIsSetToPrimeNumberLargerOrEqualToRequested()
- {
- var dictionary = new Dictionary<TKey, TValue>();
- Assert.Equal(17, dictionary.EnsureCapacity(17));
-
- dictionary = new Dictionary<TKey, TValue>();
- Assert.Equal(17, dictionary.EnsureCapacity(15));
-
- dictionary = new Dictionary<TKey, TValue>();
- Assert.Equal(17, dictionary.EnsureCapacity(13));
- }
-
- #endregion
-
- #region TrimExcess
-
- [Fact]
- public void TrimExcess_Generic_NegativeCapacity_Throw()
- {
- var dictionary = new Dictionary<TKey, TValue>();
- AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => dictionary.TrimExcess(-1));
- }
-
- [Theory]
- [InlineData(20)]
- [InlineData(23)]
- public void TrimExcess_Generic_CapacitySmallerThanCount_Throws(int suggestedCapacity)
- {
- var dictionary = new Dictionary<TKey, TValue>();
- dictionary.Add(GetNewKey(dictionary), CreateTValue(0));
- AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => dictionary.TrimExcess(0));
-
- dictionary = new Dictionary<TKey, TValue>(suggestedCapacity);
- dictionary.Add(GetNewKey(dictionary), CreateTValue(0));
- AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => dictionary.TrimExcess(0));
- }
-
- [Fact]
- public void TrimExcess_Generic_LargeInitialCapacity_TrimReducesSize()
- {
- var dictionary = new Dictionary<TKey, TValue>(20);
- dictionary.TrimExcess(7);
- Assert.Equal(7, dictionary.EnsureCapacity(0));
- }
-
- [Theory]
- [InlineData(20)]
- [InlineData(23)]
- public void TrimExcess_Generic_TrimToLargerThanExistingCapacity_DoesNothing(int suggestedCapacity)
- {
- var dictionary = new Dictionary<TKey, TValue>();
- int capacity = dictionary.EnsureCapacity(0);
- dictionary.TrimExcess(suggestedCapacity);
- Assert.Equal(capacity, dictionary.EnsureCapacity(0));
-
- dictionary = new Dictionary<TKey, TValue>(suggestedCapacity/2);
- capacity = dictionary.EnsureCapacity(0);
- dictionary.TrimExcess(suggestedCapacity);
- Assert.Equal(capacity, dictionary.EnsureCapacity(0));
- }
-
- [Fact]
- public void TrimExcess_Generic_DictionaryNotInitialized_CapacityRemainsAsMinPossible()
- {
- var dictionary = new Dictionary<TKey, TValue>();
- Assert.Equal(0, dictionary.EnsureCapacity(0));
- dictionary.TrimExcess();
- Assert.Equal(0, dictionary.EnsureCapacity(0));
- }
-
- [Theory]
- [InlineData(1)]
- [InlineData(85)]
- [InlineData(89)]
- public void TrimExcess_Generic_ClearThenTrimNonEmptyDictionary_SetsCapacityTo3(int count)
- {
- Dictionary<TKey, TValue> dictionary = (Dictionary<TKey, TValue>)GenericIDictionaryFactory(count);
- Assert.Equal(count, dictionary.Count);
- // The smallest possible capacity size after clearing a dictionary is 3
- dictionary.Clear();
- dictionary.TrimExcess();
- Assert.Equal(3, dictionary.EnsureCapacity(0));
- }
-
- [Theory]
- [InlineData(85)]
- [InlineData(89)]
- public void TrimExcess_NoArguments_TrimsToAtLeastCount(int count)
- {
- var dictionary = new Dictionary<int, int>(20);
- for (int i = 0; i < count; i++)
- {
- dictionary.Add(i, 0);
- }
- dictionary.TrimExcess();
- Assert.InRange(dictionary.EnsureCapacity(0), count, int.MaxValue);
- }
-
- [Theory]
- [InlineData(85)]
- [InlineData(89)]
- public void TrimExcess_WithArguments_OnDictionaryWithManyElementsRemoved_TrimsToAtLeastRequested(int finalCount)
- {
- const int InitToFinalRatio = 10;
- int initialCount = InitToFinalRatio * finalCount;
- var dictionary = new Dictionary<int, int>(initialCount);
- Assert.InRange(dictionary.EnsureCapacity(0), initialCount, int.MaxValue);
- for (int i = 0; i < initialCount; i++)
- {
- dictionary.Add(i, 0);
- }
- for (int i = 0; i < initialCount - finalCount; i++)
- {
- dictionary.Remove(i);
- }
- for (int i = InitToFinalRatio; i > 0; i--)
- {
- dictionary.TrimExcess(i * finalCount);
- Assert.InRange(dictionary.EnsureCapacity(0), i * finalCount, int.MaxValue);
- }
- }
-
- [Theory]
- [InlineData(1000, 900, 5000, 85, 89)]
- [InlineData(1000, 400, 5000, 85, 89)]
- [InlineData(1000, 900, 500, 85, 89)]
- [InlineData(1000, 400, 500, 85, 89)]
- [InlineData(1000, 400, 500, 1, 3)]
- public void TrimExcess_NoArgument_TrimAfterEachBulkAddOrRemove_TrimsToAtLeastCount(int initialCount, int numRemove, int numAdd, int newCount, int newCapacity)
- {
- Random random = new Random(32);
- var dictionary = new Dictionary<int, int>();
- dictionary.TrimExcess();
- Assert.InRange(dictionary.EnsureCapacity(0), dictionary.Count, int.MaxValue);
-
- var initialKeys = new int[initialCount];
- for (int i = 0; i < initialCount; i++)
- {
- initialKeys[i] = i;
- }
- random.Shuffle(initialKeys);
- foreach (var key in initialKeys)
- {
- dictionary.Add(key, 0);
- }
- dictionary.TrimExcess();
- Assert.InRange(dictionary.EnsureCapacity(0), dictionary.Count, int.MaxValue);
-
- random.Shuffle(initialKeys);
- for (int i = 0; i < numRemove; i++)
- {
- dictionary.Remove(initialKeys[i]);
- }
- dictionary.TrimExcess();
- Assert.InRange(dictionary.EnsureCapacity(0), dictionary.Count, int.MaxValue);
-
- var moreKeys = new int[numAdd];
- for (int i = 0; i < numAdd; i++)
- {
- moreKeys[i] = i + initialCount;
- }
- random.Shuffle(moreKeys);
- foreach (var key in moreKeys)
- {
- dictionary.Add(key, 0);
- }
- int currentCount = dictionary.Count;
- dictionary.TrimExcess();
- Assert.InRange(dictionary.EnsureCapacity(0), currentCount, int.MaxValue);
-
- int[] existingKeys = new int[currentCount];
- Array.Copy(initialKeys, numRemove, existingKeys, 0, initialCount - numRemove);
- Array.Copy(moreKeys, 0, existingKeys, initialCount - numRemove, numAdd);
- random.Shuffle(existingKeys);
- for (int i = 0; i < currentCount - newCount; i++)
- {
- dictionary.Remove(existingKeys[i]);
- }
- dictionary.TrimExcess();
- int finalCapacity = dictionary.EnsureCapacity(0);
- Assert.InRange(finalCapacity, newCount, initialCount);
- Assert.Equal(newCapacity, finalCapacity);
- }
-
- [Fact]
- public void TrimExcess_DictionaryHasElementsChainedWithSameHashcode_Success()
- {
- var dictionary = new Dictionary<string, int>(7);
- for (int i = 0; i < 4; i++)
- {
- dictionary.Add(i.ToString(), 0);
- }
- var s_64bit = new string[] { "95e85f8e-67a3-4367-974f-dd24d8bb2ca2", "eb3d6fe9-de64-43a9-8f58-bddea727b1ca" };
- var s_32bit = new string[] { "25b1f130-7517-48e3-96b0-9da44e8bfe0e", "ba5a3625-bc38-4bf1-a707-a3cfe2158bae" };
- string[] chained = (Environment.Is64BitProcess ? s_64bit : s_32bit).ToArray();
- dictionary.Add(chained[0], 0);
- dictionary.Add(chained[1], 0);
- for (int i = 0; i < 4; i++)
- {
- dictionary.Remove(i.ToString());
- }
- dictionary.TrimExcess(3);
- Assert.Equal(2, dictionary.Count);
- int val;
- Assert.True(dictionary.TryGetValue(chained[0], out val));
- Assert.True(dictionary.TryGetValue(chained[1], out val));
- }
-
- [Fact]
- public void TrimExcess_Generic_DoesInvalidateEnumeration()
- {
- var dictionary = new Dictionary<TKey, TValue>(20);
- var enumerator = dictionary.GetEnumerator();
-
- dictionary.TrimExcess(7); // Verify TrimExcess does invalidate enumeration
-
- Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
- }
-
- #endregion
- }
-}
/// <summary>
/// Contains tests that ensure the correctness of the HashSet class.
/// </summary>
- public abstract partial class HashSet_Generic_Tests<T> : ISet_Generic_Tests<T>
+ public abstract class HashSet_Generic_Tests<T> : ISet_Generic_Tests<T>
{
#region ISet<T> Helper Methods
ISet<T> iset = (set as ISet<T>);
Assert.NotNull(iset);
}
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void HashSet_Generic_Constructor_int(int capacity)
+ {
+ HashSet<T> set = new HashSet<T>(capacity);
+ Assert.Equal(0, set.Count);
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void HashSet_Generic_Constructor_int_AddUpToAndBeyondCapacity(int capacity)
+ {
+ HashSet<T> set = new HashSet<T>(capacity);
+
+ AddToCollection(set, capacity);
+ Assert.Equal(capacity, set.Count);
+
+ AddToCollection(set, capacity + 1);
+ Assert.Equal(capacity + 1, set.Count);
+ }
+
+ [Fact]
+ public void HashSet_Generic_Constructor_Capacity_ToNextPrimeNumber()
+ {
+ // Highest pre-computed number + 1.
+ const int Capacity = 7199370;
+ var set = new HashSet<T>(Capacity);
+
+ // Assert that the HashTable's capacity is set to the descendant prime number of the given one.
+ const int NextPrime = 7199371;
+ Assert.Equal(NextPrime, set.EnsureCapacity(0));
+ }
+
+ [Fact]
+ public void HashSet_Generic_Constructor_int_Negative_ThrowsArgumentOutOfRangeException()
+ {
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(-1));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(int.MinValue));
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void HashSet_Generic_Constructor_int_IEqualityComparer(int capacity)
+ {
+ IEqualityComparer<T> comparer = GetIEqualityComparer();
+ HashSet<T> set = new HashSet<T>(capacity, comparer);
+ Assert.Equal(0, set.Count);
+ if (comparer == null)
+ Assert.Equal(EqualityComparer<T>.Default, set.Comparer);
+ else
+ Assert.Equal(comparer, set.Comparer);
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void HashSet_Generic_Constructor_int_IEqualityComparer_AddUpToAndBeyondCapacity(int capacity)
+ {
+ IEqualityComparer<T> comparer = GetIEqualityComparer();
+ HashSet<T> set = new HashSet<T>(capacity, comparer);
+
+ AddToCollection(set, capacity);
+ Assert.Equal(capacity, set.Count);
+
+ AddToCollection(set, capacity + 1);
+ Assert.Equal(capacity + 1, set.Count);
+ }
+
+ [Fact]
+ public void HashSet_Generic_Constructor_int_IEqualityComparer_Negative_ThrowsArgumentOutOfRangeException()
+ {
+ IEqualityComparer<T> comparer = GetIEqualityComparer();
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(-1, comparer));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(int.MinValue, comparer));
+ }
+
+ #region TryGetValue
+
+ [Fact]
+ public void HashSet_Generic_TryGetValue_Contains()
+ {
+ T value = CreateT(1);
+ HashSet<T> set = new HashSet<T> { value };
+ T equalValue = CreateT(1);
+ T actualValue;
+ Assert.True(set.TryGetValue(equalValue, out actualValue));
+ Assert.Equal(value, actualValue);
+ if (!typeof(T).IsValueType)
+ {
+ Assert.Same((object)value, (object)actualValue);
+ }
+ }
+
+ [Fact]
+ public void HashSet_Generic_TryGetValue_Contains_OverwriteOutputParam()
+ {
+ T value = CreateT(1);
+ HashSet<T> set = new HashSet<T> { value };
+ T equalValue = CreateT(1);
+ T actualValue = CreateT(2);
+ Assert.True(set.TryGetValue(equalValue, out actualValue));
+ Assert.Equal(value, actualValue);
+ if (!typeof(T).IsValueType)
+ {
+ Assert.Same((object)value, (object)actualValue);
+ }
+ }
+
+ [Fact]
+ public void HashSet_Generic_TryGetValue_NotContains()
+ {
+ T value = CreateT(1);
+ HashSet<T> set = new HashSet<T> { value };
+ T equalValue = CreateT(2);
+ T actualValue;
+ Assert.False(set.TryGetValue(equalValue, out actualValue));
+ Assert.Equal(default(T), actualValue);
+ }
+
+ [Fact]
+ public void HashSet_Generic_TryGetValue_NotContains_OverwriteOutputParam()
+ {
+ T value = CreateT(1);
+ HashSet<T> set = new HashSet<T> { value };
+ T equalValue = CreateT(2);
+ T actualValue = equalValue;
+ Assert.False(set.TryGetValue(equalValue, out actualValue));
+ Assert.Equal(default(T), actualValue);
+ }
+
+ #endregion
+
+ #region EnsureCapacity
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void EnsureCapacity_Generic_RequestingLargerCapacity_DoesNotInvalidateEnumeration(int setLength)
+ {
+ HashSet<T> set = (HashSet<T>)(GenericISetFactory(setLength));
+ var capacity = set.EnsureCapacity(0);
+ IEnumerator valuesEnum = set.GetEnumerator();
+ IEnumerator valuesListEnum = new List<T>(set).GetEnumerator();
+
+ set.EnsureCapacity(capacity + 1); // Verify EnsureCapacity does not invalidate enumeration
+
+ while (valuesEnum.MoveNext())
+ {
+ valuesListEnum.MoveNext();
+ Assert.Equal(valuesListEnum.Current, valuesEnum.Current);
+ }
+ }
+
+ [Fact]
+ public void EnsureCapacity_Generic_NegativeCapacityRequested_Throws()
+ {
+ var set = new HashSet<T>();
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => set.EnsureCapacity(-1));
+ }
+
+ [Fact]
+ public void EnsureCapacity_Generic_HashsetNotInitialized_RequestedZero_ReturnsZero()
+ {
+ var set = new HashSet<T>();
+ Assert.Equal(0, set.EnsureCapacity(0));
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(4)]
+ public void EnsureCapacity_Generic_HashsetNotInitialized_RequestedNonZero_CapacityIsSetToAtLeastTheRequested(int requestedCapacity)
+ {
+ var set = new HashSet<T>();
+ Assert.InRange(set.EnsureCapacity(requestedCapacity), requestedCapacity, int.MaxValue);
+ }
+
+ [Theory]
+ [InlineData(3)]
+ [InlineData(7)]
+ public void EnsureCapacity_Generic_RequestedCapacitySmallerThanCurrent_CapacityUnchanged(int currentCapacity)
+ {
+ HashSet<T> set;
+
+ // assert capacity remains the same when ensuring a capacity smaller or equal than existing
+ for (int i = 0; i <= currentCapacity; i++)
+ {
+ set = new HashSet<T>(currentCapacity);
+ Assert.Equal(currentCapacity, set.EnsureCapacity(i));
+ }
+ }
+
+ [Theory]
+ [InlineData(7)]
+ [InlineData(89)]
+ public void EnsureCapacity_Generic_ExistingCapacityRequested_SameValueReturned(int capacity)
+ {
+ var set = new HashSet<T>(capacity);
+ Assert.Equal(capacity, set.EnsureCapacity(capacity));
+
+ set = (HashSet<T>)GenericISetFactory(capacity);
+ Assert.Equal(capacity, set.EnsureCapacity(capacity));
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(4)]
+ public void EnsureCapacity_Generic_EnsureCapacityCalledTwice_ReturnsSameValue(int setLength)
+ {
+ HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
+ int capacity = set.EnsureCapacity(0);
+ Assert.Equal(capacity, set.EnsureCapacity(0));
+
+ set = (HashSet<T>)GenericISetFactory(setLength);
+ capacity = set.EnsureCapacity(setLength);
+ Assert.Equal(capacity, set.EnsureCapacity(setLength));
+
+ set = (HashSet<T>)GenericISetFactory(setLength);
+ capacity = set.EnsureCapacity(setLength + 1);
+ Assert.Equal(capacity, set.EnsureCapacity(setLength + 1));
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(5)]
+ [InlineData(7)]
+ [InlineData(8)]
+ public void EnsureCapacity_Generic_HashsetNotEmpty_RequestedSmallerThanCount_ReturnsAtLeastSizeOfCount(int setLength)
+ {
+ HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
+ Assert.InRange(set.EnsureCapacity(setLength - 1), setLength, int.MaxValue);
+ }
+
+ [Theory]
+ [InlineData(7)]
+ [InlineData(20)]
+ public void EnsureCapacity_Generic_HashsetNotEmpty_SetsToAtLeastTheRequested(int setLength)
+ {
+ HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
+
+ // get current capacity
+ int currentCapacity = set.EnsureCapacity(0);
+
+ // assert we can update to a larger capacity
+ int newCapacity = set.EnsureCapacity(currentCapacity * 2);
+ Assert.InRange(newCapacity, currentCapacity * 2, int.MaxValue);
+ }
+
+ [Fact]
+ public void EnsureCapacity_Generic_CapacityIsSetToPrimeNumberLargerOrEqualToRequested()
+ {
+ var set = new HashSet<T>();
+ Assert.Equal(17, set.EnsureCapacity(17));
+
+ set = new HashSet<T>();
+ Assert.Equal(17, set.EnsureCapacity(15));
+
+ set = new HashSet<T>();
+ Assert.Equal(17, set.EnsureCapacity(13));
+ }
+
+ [Theory]
+ [InlineData(2)]
+ [InlineData(10)]
+ public void EnsureCapacity_Generic_GrowCapacityWithFreeList(int setLength)
+ {
+ HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
+
+ // Remove the first element to ensure we have a free list.
+ Assert.True(set.Remove(set.ElementAt(0)));
+
+ int currentCapacity = set.EnsureCapacity(0);
+ Assert.True(currentCapacity > 0);
+
+ int newCapacity = set.EnsureCapacity(currentCapacity + 1);
+ Assert.True(newCapacity > currentCapacity);
+ }
+
+ #endregion
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Xunit;
-
-namespace System.Collections.Tests
-{
- public abstract partial class HashSet_Generic_Tests<T> : ISet_Generic_Tests<T>
- {
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void HashSet_Generic_Constructor_int(int capacity)
- {
- HashSet<T> set = new HashSet<T>(capacity);
- Assert.Equal(0, set.Count);
- }
-
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void HashSet_Generic_Constructor_int_AddUpToAndBeyondCapacity(int capacity)
- {
- HashSet<T> set = new HashSet<T>(capacity);
-
- AddToCollection(set, capacity);
- Assert.Equal(capacity, set.Count);
-
- AddToCollection(set, capacity + 1);
- Assert.Equal(capacity + 1, set.Count);
- }
-
- [Fact]
- public void HashSet_Generic_Constructor_Capacity_ToNextPrimeNumber()
- {
- // Highest pre-computed number + 1.
- const int Capacity = 7199370;
- var set = new HashSet<T>(Capacity);
-
- // Assert that the HashTable's capacity is set to the descendant prime number of the given one.
- const int NextPrime = 7199371;
- Assert.Equal(NextPrime, set.EnsureCapacity(0));
- }
-
- [Fact]
- public void HashSet_Generic_Constructor_int_Negative_ThrowsArgumentOutOfRangeException()
- {
- AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(-1));
- AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(int.MinValue));
- }
-
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void HashSet_Generic_Constructor_int_IEqualityComparer(int capacity)
- {
- IEqualityComparer<T> comparer = GetIEqualityComparer();
- HashSet<T> set = new HashSet<T>(capacity, comparer);
- Assert.Equal(0, set.Count);
- if (comparer == null)
- Assert.Equal(EqualityComparer<T>.Default, set.Comparer);
- else
- Assert.Equal(comparer, set.Comparer);
- }
-
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void HashSet_Generic_Constructor_int_IEqualityComparer_AddUpToAndBeyondCapacity(int capacity)
- {
- IEqualityComparer<T> comparer = GetIEqualityComparer();
- HashSet<T> set = new HashSet<T>(capacity, comparer);
-
- AddToCollection(set, capacity);
- Assert.Equal(capacity, set.Count);
-
- AddToCollection(set, capacity + 1);
- Assert.Equal(capacity + 1, set.Count);
- }
-
- [Fact]
- public void HashSet_Generic_Constructor_int_IEqualityComparer_Negative_ThrowsArgumentOutOfRangeException()
- {
- IEqualityComparer<T> comparer = GetIEqualityComparer();
- AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(-1, comparer));
- AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(int.MinValue, comparer));
- }
-
- #region TryGetValue
-
- [Fact]
- public void HashSet_Generic_TryGetValue_Contains()
- {
- T value = CreateT(1);
- HashSet<T> set = new HashSet<T> { value };
- T equalValue = CreateT(1);
- T actualValue;
- Assert.True(set.TryGetValue(equalValue, out actualValue));
- Assert.Equal(value, actualValue);
- if (!typeof(T).IsValueType)
- {
- Assert.Same((object)value, (object)actualValue);
- }
- }
-
- [Fact]
- public void HashSet_Generic_TryGetValue_Contains_OverwriteOutputParam()
- {
- T value = CreateT(1);
- HashSet<T> set = new HashSet<T> { value };
- T equalValue = CreateT(1);
- T actualValue = CreateT(2);
- Assert.True(set.TryGetValue(equalValue, out actualValue));
- Assert.Equal(value, actualValue);
- if (!typeof(T).IsValueType)
- {
- Assert.Same((object)value, (object)actualValue);
- }
- }
-
- [Fact]
- public void HashSet_Generic_TryGetValue_NotContains()
- {
- T value = CreateT(1);
- HashSet<T> set = new HashSet<T> { value };
- T equalValue = CreateT(2);
- T actualValue;
- Assert.False(set.TryGetValue(equalValue, out actualValue));
- Assert.Equal(default(T), actualValue);
- }
-
- [Fact]
- public void HashSet_Generic_TryGetValue_NotContains_OverwriteOutputParam()
- {
- T value = CreateT(1);
- HashSet<T> set = new HashSet<T> { value };
- T equalValue = CreateT(2);
- T actualValue = equalValue;
- Assert.False(set.TryGetValue(equalValue, out actualValue));
- Assert.Equal(default(T), actualValue);
- }
-
- #endregion
-
- #region EnsureCapacity
-
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void EnsureCapacity_Generic_RequestingLargerCapacity_DoesNotInvalidateEnumeration(int setLength)
- {
- HashSet<T> set = (HashSet<T>)(GenericISetFactory(setLength));
- var capacity = set.EnsureCapacity(0);
- IEnumerator valuesEnum = set.GetEnumerator();
- IEnumerator valuesListEnum = new List<T>(set).GetEnumerator();
-
- set.EnsureCapacity(capacity + 1); // Verify EnsureCapacity does not invalidate enumeration
-
- while (valuesEnum.MoveNext())
- {
- valuesListEnum.MoveNext();
- Assert.Equal(valuesListEnum.Current, valuesEnum.Current);
- }
- }
-
- [Fact]
- public void EnsureCapacity_Generic_NegativeCapacityRequested_Throws()
- {
- var set = new HashSet<T>();
- AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => set.EnsureCapacity(-1));
- }
-
- [Fact]
- public void EnsureCapacity_Generic_HashsetNotInitialized_RequestedZero_ReturnsZero()
- {
- var set = new HashSet<T>();
- Assert.Equal(0, set.EnsureCapacity(0));
- }
-
- [Theory]
- [InlineData(1)]
- [InlineData(2)]
- [InlineData(3)]
- [InlineData(4)]
- public void EnsureCapacity_Generic_HashsetNotInitialized_RequestedNonZero_CapacityIsSetToAtLeastTheRequested(int requestedCapacity)
- {
- var set = new HashSet<T>();
- Assert.InRange(set.EnsureCapacity(requestedCapacity), requestedCapacity, int.MaxValue);
- }
-
- [Theory]
- [InlineData(3)]
- [InlineData(7)]
- public void EnsureCapacity_Generic_RequestedCapacitySmallerThanCurrent_CapacityUnchanged(int currentCapacity)
- {
- HashSet<T> set;
-
- // assert capacity remains the same when ensuring a capacity smaller or equal than existing
- for (int i = 0; i <= currentCapacity; i++)
- {
- set = new HashSet<T>(currentCapacity);
- Assert.Equal(currentCapacity, set.EnsureCapacity(i));
- }
- }
-
- [Theory]
- [InlineData(7)]
- [InlineData(89)]
- public void EnsureCapacity_Generic_ExistingCapacityRequested_SameValueReturned(int capacity)
- {
- var set = new HashSet<T>(capacity);
- Assert.Equal(capacity, set.EnsureCapacity(capacity));
-
- set = (HashSet<T>)GenericISetFactory(capacity);
- Assert.Equal(capacity, set.EnsureCapacity(capacity));
- }
-
- [Theory]
- [InlineData(0)]
- [InlineData(1)]
- [InlineData(2)]
- [InlineData(3)]
- [InlineData(4)]
- public void EnsureCapacity_Generic_EnsureCapacityCalledTwice_ReturnsSameValue(int setLength)
- {
- HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
- int capacity = set.EnsureCapacity(0);
- Assert.Equal(capacity, set.EnsureCapacity(0));
-
- set = (HashSet<T>)GenericISetFactory(setLength);
- capacity = set.EnsureCapacity(setLength);
- Assert.Equal(capacity, set.EnsureCapacity(setLength));
-
- set = (HashSet<T>)GenericISetFactory(setLength);
- capacity = set.EnsureCapacity(setLength + 1);
- Assert.Equal(capacity, set.EnsureCapacity(setLength + 1));
- }
-
- [Theory]
- [InlineData(1)]
- [InlineData(5)]
- [InlineData(7)]
- [InlineData(8)]
- public void EnsureCapacity_Generic_HashsetNotEmpty_RequestedSmallerThanCount_ReturnsAtLeastSizeOfCount(int setLength)
- {
- HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
- Assert.InRange(set.EnsureCapacity(setLength - 1), setLength, int.MaxValue);
- }
-
- [Theory]
- [InlineData(7)]
- [InlineData(20)]
- public void EnsureCapacity_Generic_HashsetNotEmpty_SetsToAtLeastTheRequested(int setLength)
- {
- HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
-
- // get current capacity
- int currentCapacity = set.EnsureCapacity(0);
-
- // assert we can update to a larger capacity
- int newCapacity = set.EnsureCapacity(currentCapacity * 2);
- Assert.InRange(newCapacity, currentCapacity * 2, int.MaxValue);
- }
-
- [Fact]
- public void EnsureCapacity_Generic_CapacityIsSetToPrimeNumberLargerOrEqualToRequested()
- {
- var set = new HashSet<T>();
- Assert.Equal(17, set.EnsureCapacity(17));
-
- set = new HashSet<T>();
- Assert.Equal(17, set.EnsureCapacity(15));
-
- set = new HashSet<T>();
- Assert.Equal(17, set.EnsureCapacity(13));
- }
-
- [Theory]
- [InlineData(2)]
- [InlineData(10)]
- public void EnsureCapacity_Generic_GrowCapacityWithFreeList(int setLength)
- {
- HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
-
- // Remove the first element to ensure we have a free list.
- Assert.True(set.Remove(set.ElementAt(0)));
-
- int currentCapacity = set.EnsureCapacity(0);
- Assert.True(currentCapacity > 0);
-
- int newCapacity = set.EnsureCapacity(currentCapacity + 1);
- Assert.True(newCapacity > currentCapacity);
- }
-
- #endregion
- }
-}
/// <summary>
/// Contains tests that ensure the correctness of the Queue class.
/// </summary>
- public abstract partial class Queue_Generic_Tests<T> : IGenericSharedAPI_Tests<T>
+ public abstract class Queue_Generic_Tests<T> : IGenericSharedAPI_Tests<T>
{
#region Queue<T> Helper Methods
}
#endregion
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void Queue_Generic_TryDequeue_AllElements(int count)
+ {
+ Queue<T> queue = GenericQueueFactory(count);
+ List<T> elements = queue.ToList();
+ foreach (T element in elements)
+ {
+ T result;
+ Assert.True(queue.TryDequeue(out result));
+ Assert.Equal(element, result);
+ }
+ }
+
+ [Fact]
+ public void Queue_Generic_TryDequeue_EmptyQueue_ReturnsFalse()
+ {
+ T result;
+ Assert.False(new Queue<T>().TryDequeue(out result));
+ Assert.Equal(default(T), result);
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void Queue_Generic_TryPeek_AllElements(int count)
+ {
+ Queue<T> queue = GenericQueueFactory(count);
+ List<T> elements = queue.ToList();
+ foreach (T element in elements)
+ {
+ T result;
+ Assert.True(queue.TryPeek(out result));
+ Assert.Equal(element, result);
+
+ queue.Dequeue();
+ }
+ }
+
+ [Fact]
+ public void Queue_Generic_TryPeek_EmptyQueue_ReturnsFalse()
+ {
+ T result;
+ Assert.False(new Queue<T>().TryPeek(out result));
+ Assert.Equal(default(T), result);
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Xunit;
-
-namespace System.Collections.Tests
-{
- public abstract partial class Queue_Generic_Tests<T> : IGenericSharedAPI_Tests<T>
- {
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void Queue_Generic_TryDequeue_AllElements(int count)
- {
- Queue<T> queue = GenericQueueFactory(count);
- List<T> elements = queue.ToList();
- foreach (T element in elements)
- {
- T result;
- Assert.True(queue.TryDequeue(out result));
- Assert.Equal(element, result);
- }
- }
-
- [Fact]
- public void Queue_Generic_TryDequeue_EmptyQueue_ReturnsFalse()
- {
- T result;
- Assert.False(new Queue<T>().TryDequeue(out result));
- Assert.Equal(default(T), result);
- }
-
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void Queue_Generic_TryPeek_AllElements(int count)
- {
- Queue<T> queue = GenericQueueFactory(count);
- List<T> elements = queue.ToList();
- foreach (T element in elements)
- {
- T result;
- Assert.True(queue.TryPeek(out result));
- Assert.Equal(element, result);
-
- queue.Dequeue();
- }
- }
-
- [Fact]
- public void Queue_Generic_TryPeek_EmptyQueue_ReturnsFalse()
- {
- T result;
- Assert.False(new Queue<T>().TryPeek(out result));
- Assert.Equal(default(T), result);
- }
- }
-}
/// <summary>
/// Contains tests that ensure the correctness of the SortedSet class.
/// </summary>
- public abstract partial class SortedSet_Generic_Tests<T> : ISet_Generic_Tests<T>
+ public abstract class SortedSet_Generic_Tests<T> : ISet_Generic_Tests<T>
{
#region ISet<T> Helper Methods
Assert.True(comparerSet1.SetEquals(set));
Assert.True(comparerSet2.SetEquals(set));
}
+#endregion
+
+#region TryGetValue
+
+ [Fact]
+ public void SortedSet_Generic_TryGetValue_Contains()
+ {
+ T value = CreateT(1);
+ SortedSet<T> set = new SortedSet<T> { value };
+ T equalValue = CreateT(1);
+ T actualValue;
+ Assert.True(set.TryGetValue(equalValue, out actualValue));
+ Assert.Equal(value, actualValue);
+ if (!typeof(T).IsValueType)
+ {
+ Assert.Same((object)value, (object)actualValue);
+ }
+ }
+
+ [Fact]
+ public void SortedSet_Generic_TryGetValue_Contains_OverwriteOutputParam()
+ {
+ T value = CreateT(1);
+ SortedSet<T> set = new SortedSet<T> { value };
+ T equalValue = CreateT(1);
+ T actualValue = CreateT(2);
+ Assert.True(set.TryGetValue(equalValue, out actualValue));
+ Assert.Equal(value, actualValue);
+ if (!typeof(T).IsValueType)
+ {
+ Assert.Same((object)value, (object)actualValue);
+ }
+ }
+
+ [Fact]
+ public void SortedSet_Generic_TryGetValue_NotContains()
+ {
+ T value = CreateT(1);
+ SortedSet<T> set = new SortedSet<T> { value };
+ T equalValue = CreateT(2);
+ T actualValue;
+ Assert.False(set.TryGetValue(equalValue, out actualValue));
+ Assert.Equal(default(T), actualValue);
+ }
+
+ [Fact]
+ public void SortedSet_Generic_TryGetValue_NotContains_OverwriteOutputParam()
+ {
+ T value = CreateT(1);
+ SortedSet<T> set = new SortedSet<T> { value };
+ T equalValue = CreateT(2);
+ T actualValue = equalValue;
+ Assert.False(set.TryGetValue(equalValue, out actualValue));
+ Assert.Equal(default(T), actualValue);
+ }
+
#endregion
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Xunit;
-
-namespace System.Collections.Tests
-{
- /// <summary>
- /// Contains tests that ensure the correctness of the SortedSet class.
- /// </summary>
- public abstract partial class SortedSet_Generic_Tests<T> : ISet_Generic_Tests<T>
- {
- #region TryGetValue
-
- [Fact]
- public void SortedSet_Generic_TryGetValue_Contains()
- {
- T value = CreateT(1);
- SortedSet<T> set = new SortedSet<T> { value };
- T equalValue = CreateT(1);
- T actualValue;
- Assert.True(set.TryGetValue(equalValue, out actualValue));
- Assert.Equal(value, actualValue);
- if (!typeof(T).IsValueType)
- {
- Assert.Same((object)value, (object)actualValue);
- }
- }
-
- [Fact]
- public void SortedSet_Generic_TryGetValue_Contains_OverwriteOutputParam()
- {
- T value = CreateT(1);
- SortedSet<T> set = new SortedSet<T> { value };
- T equalValue = CreateT(1);
- T actualValue = CreateT(2);
- Assert.True(set.TryGetValue(equalValue, out actualValue));
- Assert.Equal(value, actualValue);
- if (!typeof(T).IsValueType)
- {
- Assert.Same((object)value, (object)actualValue);
- }
- }
-
- [Fact]
- public void SortedSet_Generic_TryGetValue_NotContains()
- {
- T value = CreateT(1);
- SortedSet<T> set = new SortedSet<T> { value };
- T equalValue = CreateT(2);
- T actualValue;
- Assert.False(set.TryGetValue(equalValue, out actualValue));
- Assert.Equal(default(T), actualValue);
- }
-
- [Fact]
- public void SortedSet_Generic_TryGetValue_NotContains_OverwriteOutputParam()
- {
- T value = CreateT(1);
- SortedSet<T> set = new SortedSet<T> { value };
- T equalValue = CreateT(2);
- T actualValue = equalValue;
- Assert.False(set.TryGetValue(equalValue, out actualValue));
- Assert.Equal(default(T), actualValue);
- }
-
- #endregion
- }
-}
/// <summary>
/// Contains tests that ensure the correctness of the Stack class.
/// </summary>
- public abstract partial class Stack_Generic_Tests<T> : IGenericSharedAPI_Tests<T>
+ public abstract class Stack_Generic_Tests<T> : IGenericSharedAPI_Tests<T>
{
#region Stack<T> Helper Methods
}
#endregion
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void Stack_Generic_TryPop_AllElements(int count)
+ {
+ Stack<T> stack = GenericStackFactory(count);
+ List<T> elements = stack.ToList();
+ foreach (T element in elements)
+ {
+ T result;
+ Assert.True(stack.TryPop(out result));
+ Assert.Equal(element, result);
+ }
+ }
+
+ [Fact]
+ public void Stack_Generic_TryPop_EmptyStack_ReturnsFalse()
+ {
+ T result;
+ Assert.False(new Stack<T>().TryPop(out result));
+ Assert.Equal(default(T), result);
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidCollectionSizes))]
+ public void Stack_Generic_TryPeek_AllElements(int count)
+ {
+ Stack<T> stack = GenericStackFactory(count);
+ List<T> elements = stack.ToList();
+ foreach (T element in elements)
+ {
+ T result;
+ Assert.True(stack.TryPeek(out result));
+ Assert.Equal(element, result);
+
+ stack.Pop();
+ }
+ }
+
+ [Fact]
+ public void Stack_Generic_TryPeek_EmptyStack_ReturnsFalse()
+ {
+ T result;
+ Assert.False(new Stack<T>().TryPeek(out result));
+ Assert.Equal(default(T), result);
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Xunit;
-
-namespace System.Collections.Tests
-{
- public abstract partial class Stack_Generic_Tests<T> : IGenericSharedAPI_Tests<T>
- {
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void Stack_Generic_TryPop_AllElements(int count)
- {
- Stack<T> stack = GenericStackFactory(count);
- List<T> elements = stack.ToList();
- foreach (T element in elements)
- {
- T result;
- Assert.True(stack.TryPop(out result));
- Assert.Equal(element, result);
- }
- }
-
- [Fact]
- public void Stack_Generic_TryPop_EmptyStack_ReturnsFalse()
- {
- T result;
- Assert.False(new Stack<T>().TryPop(out result));
- Assert.Equal(default(T), result);
- }
-
- [Theory]
- [MemberData(nameof(ValidCollectionSizes))]
- public void Stack_Generic_TryPeek_AllElements(int count)
- {
- Stack<T> stack = GenericStackFactory(count);
- List<T> elements = stack.ToList();
- foreach (T element in elements)
- {
- T result;
- Assert.True(stack.TryPeek(out result));
- Assert.Equal(element, result);
-
- stack.Pop();
- }
- }
-
- [Fact]
- public void Stack_Generic_TryPeek_EmptyStack_ReturnsFalse()
- {
- T result;
- Assert.False(new Stack<T>().TryPeek(out result));
- Assert.Equal(default(T), result);
- }
- }
-}
<Compile Include="BitArray\BitArray_CtorTests.cs" />
<Compile Include="BitArray\BitArray_GetSetTests.cs" />
<Compile Include="BitArray\BitArray_OperatorsTests.cs" />
+ <Compile Include="Generic\CollectionExtensionsTests.cs" />
<Compile Include="Generic\Comparers\Comparer.Generic.Tests.cs" />
<Compile Include="Generic\Comparers\Comparer.Tests.cs" />
<Compile Include="Generic\Comparers\Comparers.Generic.cs" />
<Compile Include="Generic\Dictionary\HashCollisionScenarios\InputData.cs" />
<Compile Include="Generic\Dictionary\HashCollisionScenarios\OutOfBoundsRegression.cs" />
<Compile Include="Generic\Dictionary\Dictionary.Generic.cs" />
+ <Compile Include="Generic\Dictionary\Dictionary.Generic.Tests.ConcurrentAccessDetection.cs" />
<Compile Include="Generic\Dictionary\Dictionary.Generic.Tests.cs" />
<Compile Include="Generic\Dictionary\Dictionary.Generic.Tests.Keys.cs" />
<Compile Include="Generic\Dictionary\Dictionary.Generic.Tests.Values.cs" />
<Compile Include="$(CommonTestPath)\System\Collections\IEnumerable.Generic.Serialization.Tests.cs">
<Link>Common\System\Collections\IEnumerable.Generic.Serialization.Tests.cs</Link>
</Compile>
- </ItemGroup>
- <ItemGroup Condition="'$(TargetsNetCoreApp)' == 'true'">
- <Compile Include="BitArray\BitArray_OperatorsTests.netcoreapp.cs" />
- <Compile Include="Generic\CollectionExtensionsTests.cs" />
- <Compile Include="Generic\Dictionary\Dictionary.Generic.Tests.netcoreapp.cs" />
- <Compile Include="Generic\Dictionary\Dictionary.Generic.Tests.ConcurrentAccessDetection.netcoreapp.cs" />
- <Compile Include="Generic\HashSet\HashSet.Generic.Tests.netcoreapp.cs" />
- <Compile Include="Generic\Stack\Stack.Generic.Tests.netcoreapp.cs" />
- <Compile Include="Generic\SortedSet\SortedSet.Generic.Tests.netcoreapp.cs" />
- <Compile Include="Generic\Queue\Queue.Generic.Tests.netcoreapp.cs" />
<Compile Include="$(CommonTestPath)\System\Collections\IDictionary.Generic.Tests.netcoreapp.cs">
<Link>Common\System\Collections\IDictionary.Generic.Tests.netcoreapp.cs</Link>
</Compile>