diff --git a/agb/src/hash_map.rs b/agb/src/hash_map.rs index c691765e..57afd96a 100644 --- a/agb/src/hash_map.rs +++ b/agb/src/hash_map.rs @@ -43,10 +43,16 @@ pub struct HashMap { impl HashMap { pub fn new() -> Self { + Self::with_capacity(16) + } + + pub fn with_capacity(capacity: usize) -> Self { + let next_power_of_2 = find_next_power_of_2(capacity); + Self { number_of_elements: 0, max_distance_to_initial_bucket: 0, - nodes: iter::repeat_with(|| None).take(16).collect(), + nodes: iter::repeat_with(|| None).take(next_power_of_2).collect(), hasher: Default::default(), } } @@ -61,6 +67,15 @@ const fn fast_mod(len: usize, hash: HashType) -> usize { (hash as usize) & (len - 1) } +const fn find_next_power_of_2(n: usize) -> usize { + let mut next_power_of_2 = 1; + while next_power_of_2 <= n { + next_power_of_2 *= 2; + } + + next_power_of_2 +} + impl HashMap where K: Eq,