Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix HashSet.Remove to use provided comparer #154

Merged
merged 1 commit into from
Nov 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ public static IEnumerable<object[]> ValidCollectionSizes()
yield return new object[] { 75 };
}

public static IEnumerable<object[]> ValidPositiveCollectionSizes()
{
yield return new object[] { 1 };
yield return new object[] { 75 };
}

public enum EnumerableType
{
HashSet,
Expand Down
18 changes: 18 additions & 0 deletions src/libraries/Common/tests/System/Collections/TestingTypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -366,5 +366,23 @@ public struct ValueDelegateEquatable : IEquatable<ValueDelegateEquatable>
public bool Equals(ValueDelegateEquatable other) => EqualsWorker(other);
}

public sealed class TrackingEqualityComparer<T> : IEqualityComparer<T>
{
public int EqualsCalls;
public int GetHashCodeCalls;

public bool Equals(T x, T y)
{
EqualsCalls++;
return EqualityComparer<T>.Default.Equals(x, y);
}

public int GetHashCode(T obj)
{
GetHashCodeCalls++;
return EqualityComparer<T>.Default.GetHashCode(obj);
}
}

#endregion
}
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ public bool Remove(T item)

for (i = _buckets[bucket] - 1; i >= 0; last = i, i = slots[i].next)
{
if (slots[i].hashCode == hashCode && EqualityComparer<T>.Default.Equals(slots[i].value, item))
if (slots[i].hashCode == hashCode && comparer.Equals(slots[i].value, item))
{
goto ReturnFound;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -626,5 +626,29 @@ public void EnsureCapacity_Generic_GrowCapacityWithFreeList(int setLength)
}

#endregion

#region Remove

[Theory]
[MemberData(nameof(ValidPositiveCollectionSizes))]
public void Remove_NonDefaultComparer_ComparerUsed(int capacity)
{
var c = new TrackingEqualityComparer<T>();
var set = new HashSet<T>(capacity, c);

AddToCollection(set, capacity);
T first = set.First();
c.EqualsCalls = 0;
c.GetHashCodeCalls = 0;

Assert.Equal(capacity, set.Count);
set.Remove(first);
Assert.Equal(capacity - 1, set.Count);

Assert.InRange(c.EqualsCalls, 1, int.MaxValue);
Assert.InRange(c.GetHashCodeCalls, 1, int.MaxValue);
}

#endregion
}
}