Skip to content

Commit 1561661

Browse files
committed
add reserve_at_least method to LinearMap/LinearSet
1 parent 1e809aa commit 1561661

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

src/libcore/hashmap.rs

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ pub mod linear {
5151
FoundEntry(uint), FoundHole(uint), TableFull
5252
}
5353

54+
#[inline(always)]
5455
pure fn resize_at(capacity: uint) -> uint {
5556
((capacity as float) * 3. / 4.) as uint
5657
}
@@ -126,12 +127,19 @@ pub mod linear {
126127
TableFull
127128
}
128129

129-
/// Expands the capacity of the array and re-inserts each
130-
/// of the existing buckets.
130+
/// Expand the capacity of the array to the next power of two
131+
/// and re-insert each of the existing buckets.
132+
#[inline(always)]
131133
fn expand(&mut self) {
134+
let new_capacity = self.buckets.len() * 2;
135+
self.resize(new_capacity);
136+
}
137+
138+
/// Expands the capacity of the array and re-insert each of the
139+
/// existing buckets.
140+
fn resize(&mut self, new_capacity: uint) {
132141
let old_capacity = self.buckets.len();
133-
let new_capacity = old_capacity * 2;
134-
self.resize_at = ((new_capacity as float) * 3.0 / 4.0) as uint;
142+
self.resize_at = resize_at(new_capacity);
135143

136144
let mut old_buckets = vec::from_fn(new_capacity, |_| None);
137145
self.buckets <-> old_buckets;
@@ -331,6 +339,14 @@ pub mod linear {
331339
linear_map_with_capacity(INITIAL_CAPACITY)
332340
}
333341
342+
/// Reserve space for at least `n` elements in the hash table.
343+
fn reserve_at_least(&mut self, n: uint) {
344+
if n > self.buckets.len() {
345+
let buckets = n * 4 / 3 + 1;
346+
self.resize(uint::next_power_of_two(buckets));
347+
}
348+
}
349+
334350
fn pop(&mut self, k: &K) -> Option<V> {
335351
let hash = k.hash_keyed(self.k0, self.k1) as uint;
336352
self.pop_internal(hash, k)
@@ -562,6 +578,11 @@ pub mod linear {
562578
pub impl <T: Hash IterBytes Eq> LinearSet<T> {
563579
/// Create an empty LinearSet
564580
static fn new() -> LinearSet<T> { LinearSet{map: LinearMap::new()} }
581+
582+
/// Reserve space for at least `n` elements in the hash table.
583+
fn reserve_at_least(&mut self, n: uint) {
584+
self.map.reserve_at_least(n)
585+
}
565586
}
566587
}
567588

0 commit comments

Comments
 (0)