Skip to content

Ensure HashSet.TrimExcess() does not change the count #97989

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

Merged
merged 2 commits into from
Feb 6, 2024

Conversation

eiriktsarpalis
Copy link
Member

Fix #97947.

@eiriktsarpalis eiriktsarpalis added this to the 9.0.0 milestone Feb 5, 2024
@eiriktsarpalis eiriktsarpalis self-assigned this Feb 5, 2024
@ghost
Copy link

ghost commented Feb 5, 2024

Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.

Issue Details

Fix #97947.

Author: eiriktsarpalis
Assignees: eiriktsarpalis
Labels:

area-System.Collections

Milestone: 9.0.0

@@ -1055,7 +1049,7 @@ private void SetCapacity(int capacity)
}
}

_count = capacity;
_count = count;
_freeCount = 0;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_freeCount = capacity - count; ?

Copy link
Contributor

@weltkante weltkante Feb 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, not necessarily

  • _count is the number of "used" array slots (both free and actual hashset content)
  • _freeCount is the number of free slots within the first _count array slots

So the slots starting from index _count to the end of the backing array are not counted in _freeCount. This is beneficial because you can skip this section when iterating the hashset, so you don't want to include them in the counters. Trimming moves all content to the front of the new array so you get the most out of this repacking by leaving _freeCount at zero.

@github-actions github-actions bot locked and limited conversation to collaborators Mar 8, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Hashset.TrimExcess(int capacity) corrupts hashset data structure
4 participants