Repository navigation
Fix HashSet.SetCapacity() that increases capacity failing after a successful Remove(). - #40638
Conversation
…cessful Remove(). Resolves #40621
|
|
||
| HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); | ||
| set.Remove(set.ElementAt(0)); | ||
| set.EnsureCapacity(set.Count * 3); // * 3 to ensure we hit the next prime so that a resize happens. |
There was a problem hiding this comment.
Is this a known property of primes or just tested happenstance?
There was a problem hiding this comment.
Yes, see Bertrand's postulate.
There was a problem hiding this comment.
hit the next prime
Eg.
prime := 2 => 2 * 3 = 6, which is not a prime
prime := 3 => 3 * 3 = 9, which is not a prime
...
prime := 4001 => 4001 * 3 = 12003, which is not a prime
Bertrand's postulate states something different.
Or the comment is misleading, as the next prime must not be hit exactely.
There was a problem hiding this comment.
set.EnsureCapacity(set.Count * 3); // * 3 to ensure we hit the next prime so that a resize happens.
Wouldn't it need to be based on capacity rather than count?
There was a problem hiding this comment.
Bertrand would use * 2 since it's "there some prime between here and twice here" (here > 1), which is true mathematically, but since the hash helper table of primes skips 2 and 5 it "doesn't hold" for N < 7 in our implementation.
set.EnsureCapacity(set.Capacity + 1) will always grow to the next bigger prime (predefined, or actual). If you're wanting to actually skip over (at least) one and go to the next one then set.Capacity * 3 or (set.Capacity + 1) * 2 will do it (the +1 solves the 3 => 6 => 7 problem where we skipped 5, and becomes 3 => 8 => 11). But I don't know that we really would care how many prime candidates we skipped... so I'd just do +1 and assert that the number it returned was bigger than the capacity before the call.
There was a problem hiding this comment.
set.EnsureCapacity(set.Capacity + 1) will always grow to the next bigger prime (predefined, or actual).
Yea, this is my planned change. I was trying to avoid reflection (there is no public Capacity), but basing it off Count seems fragile if we ever change ValidCollectionSizes and I've realized EnsureCapacity can be used to get the current.
|
|
||
| [Theory] | ||
| [MemberData(nameof(ValidCollectionSizes))] | ||
| public void EnsureCapacity_AfterRemovingOne(int setLength) |
There was a problem hiding this comment.
stephentoub
left a comment
There was a problem hiding this comment.
Other than the comments, LGTM.
Change test so it won't break if we introduce new set sizes.
…cessful Remove(). (dotnet/corefx#40638) Fix HashSet.SetCapacity() not accounting for freelist when increasing capacity. Resolves dotnet/corefx#40621 Commit migrated from dotnet/corefx@2d6fe6b
HashSet.SetCapacity does not take into account the freelist, and will bomb out due to a bad array index.
Resolves #40621