Skip to content

#30983 Ensure capacity returned of HashMap is max(capacity, length). #30991

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 1 commit into from
Feb 2, 2016
Merged
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
30 changes: 29 additions & 1 deletion src/libstd/collections/hash/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,10 @@ impl DefaultResizePolicy {
//
// This doesn't have to be checked for overflow since allocation size
// in bytes will overflow earlier than multiplication by 10.
cap * 10 / 11
//
// As per https://github.com/rust-lang/rust/pull/30991 this is updated
// to be: (cap * den + den - 1) / num
(cap * 10 + 10 - 1) / 11
}
}

Expand Down Expand Up @@ -2418,4 +2421,29 @@ mod test_map {
assert_eq!(a[&2], "two");
assert_eq!(a[&3], "three");
}

#[test]
fn test_capacity_not_less_than_len() {
let mut a = HashMap::new();
let mut item = 0;

for _ in 0..116 {
a.insert(item, 0);
item += 1;
}

assert!(a.capacity() > a.len());

let free = a.capacity() - a.len();
for _ in 0..free {
a.insert(item, 0);
item += 1;
}

assert_eq!(a.len(), a.capacity());

// Insert at capacity should cause allocation.
a.insert(item, 0);
assert!(a.capacity() > a.len());
}
}