diff --git a/src/raw/mod.rs b/src/raw/mod.rs index fa7e4563b1..2c99b11a1d 100644 --- a/src/raw/mod.rs +++ b/src/raw/mod.rs @@ -177,16 +177,22 @@ impl Iterator for ProbeSeq { // Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258 #[cfg_attr(target_os = "emscripten", inline(never))] fn capacity_to_buckets(cap: usize) -> Option { - let adjusted_cap = if cap < 8 { - // Need at least 1 free bucket on small tables - cap + 1 - } else { - // Otherwise require 1/8 buckets to be empty (87.5% load) - // - // Be careful when modifying this, calculate_layout relies on the - // overflow check here. - cap.checked_mul(8)? / 7 - }; + debug_assert_ne!(cap, 0); + + // For small tables we require at least 1 empty bucket so that lookups are + // guaranteed to terminate if an element doesn't exist in the table. + if cap < 8 { + // We don't bother with a table size of 2 buckets since that can only + // hold a single element. Instead we skip directly to a 4 bucket table + // which can hold 3 elements. + return Some(if cap < 4 { 4 } else { 8 }); + } + + // Otherwise require 1/8 buckets to be empty (87.5% load) + // + // Be careful when modifying this, calculate_layout relies on the + // overflow check here. + let adjusted_cap = cap.checked_mul(8)? / 7; // Any overflows will have been caught by the checked_mul. Also, any // rounding errors from the division above will be cleaned up by