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

Avoid reporting a capacity of zero when there is still space in the map. #436

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
9 changes: 9 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,15 @@ impl<K, V, S, A: Allocator + Clone> HashMap<K, V, S, A> {
self.table.capacity()
}

/// Returns the maximum number of elements the map could potentially hold
/// without reallocating.
///
/// This number is an upper bound.
#[cfg_attr(feature = "inline-more", inline)]
pub fn max_capacity(&self) -> usize {
self.table.max_capacity()
}

/// An iterator visiting all keys in arbitrary order.
/// The iterator element type is `&'a K`.
///
Expand Down
18 changes: 18 additions & 0 deletions src/raw/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1389,6 +1389,15 @@ impl<T, A: Allocator + Clone> RawTable<T, A> {
self.table.items + self.table.growth_left
}

/// Returns the maximum number of elements the map could potentially hold
/// without reallocating.
///
/// This number is an upper bound.
#[inline]
pub fn max_capacity(&self) -> usize {
bucket_mask_to_capacity(self.table.bucket_mask)
}

/// Returns the number of elements in the table.
#[inline]
pub fn len(&self) -> usize {
Expand Down Expand Up @@ -2485,6 +2494,15 @@ impl<A: Allocator + Clone> RawTableInner<A> {
// SAFETY: the caller must uphold the safety contract for `erase` method.
self.set_ctrl(index, ctrl);
self.items -= 1;

// If the last item was removed we can do some cleanup
if unlikely(self.items == 0) {
let desired_capacity = bucket_mask_to_capacity(self.bucket_mask);
if self.growth_left <= desired_capacity / 2 {
// Restore an accurate view of the capacity
self.clear_no_drop()
}
}
}
}

Expand Down