Skip to content

Commit 7a7ae99

Browse files
committed
collections::bitv: correct use of Vec<T>::grow
The argument passed to Vec::grow is the number of elements to grow the vector by, not the target number of elements. The old `Bitv` code did the wrong thing, allocating more memory than it needed to.
1 parent a698b81 commit 7a7ae99

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/libcollections/bitv.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -515,9 +515,10 @@ impl BitvSet {
515515
/// Grows the vector to be able to store bits with indices `[0, size - 1]`
516516
fn grow(&mut self, size: uint) {
517517
let &BitvSet(ref mut bitv) = self;
518+
let old_size = bitv.storage.len();
518519
let size = (size + uint::BITS - 1) / uint::BITS;
519-
if bitv.storage.len() < size {
520-
bitv.storage.grow(size, &0);
520+
if old_size < size {
521+
bitv.storage.grow(size - old_size, &0);
521522
}
522523
}
523524

@@ -1253,14 +1254,22 @@ mod tests {
12531254

12541255
#[test]
12551256
fn test_bitv_set_basic() {
1257+
// calculate nbits with uint::BITS granularity
1258+
fn calc_nbits(bits: uint) -> uint {
1259+
uint::BITS * ((bits + uint::BITS - 1) / uint::BITS)
1260+
}
1261+
12561262
let mut b = BitvSet::new();
1263+
assert_eq!(b.capacity(), calc_nbits(0));
12571264
assert!(b.insert(3));
1265+
assert_eq!(b.capacity(), calc_nbits(3));
12581266
assert!(!b.insert(3));
12591267
assert!(b.contains(&3));
12601268
assert!(b.insert(4));
12611269
assert!(!b.insert(4));
12621270
assert!(b.contains(&3));
12631271
assert!(b.insert(400));
1272+
assert_eq!(b.capacity(), calc_nbits(400));
12641273
assert!(!b.insert(400));
12651274
assert!(b.contains(&400));
12661275
assert_eq!(b.len(), 3);

0 commit comments

Comments
 (0)