Skip to content

Commit d63dd69

Browse files
committed
Refactor to clearly define the method to clear the bit
1 parent f7a18aa commit d63dd69

File tree

1 file changed

+37
-39
lines changed

1 file changed

+37
-39
lines changed

src/bitmap/store/bitmap_store.rs

Lines changed: 37 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -315,26 +315,18 @@ impl BitmapStore {
315315
return;
316316
}
317317
self.len -= clear_bits;
318-
let min = self.min().unwrap();
319-
let key = key(min);
320-
for index in key..BITMAP_LENGTH {
321-
let mut mask = 1;
322-
let mut count = self.bits[index].count_ones() as u64;
323-
if clear_bits > count {
324-
self.bits[index] = 0;
325-
clear_bits -= count;
326-
continue;
327-
}
328-
while count > 0 {
329-
if self.bits[index] & mask == mask {
330-
self.bits[index] &= !mask;
331-
clear_bits -= 1;
332-
count -= 1;
333-
if clear_bits == 0 {
334-
return;
335-
}
318+
for word in self.bits.iter_mut() {
319+
let count = word.count_ones() as u64;
320+
if clear_bits < count {
321+
for _ in 0..clear_bits {
322+
*word = *word & (*word - 1);
336323
}
337-
mask <<= 1;
324+
return;
325+
}
326+
*word = 0;
327+
clear_bits -= count;
328+
if clear_bits == 0 {
329+
return;
338330
}
339331
}
340332
}
@@ -346,27 +338,18 @@ impl BitmapStore {
346338
return;
347339
}
348340
self.len -= clear_bits;
349-
let max = self.max().unwrap();
350-
let key = key(max);
351-
for index in (0..=key).rev() {
352-
let bit = self.bits[index].count_ones();
353-
let mut mask = 1 << (bit - 1);
354-
let mut count = self.bits[index].count_ones() as u64;
355-
if clear_bits > count {
356-
self.bits[index] = 0;
357-
clear_bits -= count;
358-
continue;
359-
}
360-
while count > 0 {
361-
if self.bits[index] & mask == mask {
362-
self.bits[index] &= !mask;
363-
clear_bits -= 1;
364-
count -= 1;
365-
if clear_bits == 0 {
366-
return;
367-
}
341+
for word in self.bits.iter_mut().rev() {
342+
let count = word.count_ones() as u64;
343+
if clear_bits < count {
344+
for _ in 0..clear_bits {
345+
*word &= !(1 << (63 - word.leading_zeros()));
368346
}
369-
mask >>= 1;
347+
return;
348+
}
349+
*word = 0;
350+
clear_bits -= count;
351+
if clear_bits == 0 {
352+
return;
370353
}
371354
}
372355
}
@@ -577,4 +560,19 @@ mod tests {
577560
0b1111111111111111111111111111111111111111111111111111111111101000
578561
);
579562
}
563+
564+
#[test]
565+
fn test_bitmap_remove_back() {
566+
let mut store = BitmapStore::new();
567+
let range = RangeInclusive::new(1, 3);
568+
store.insert_range(range);
569+
let range_second = RangeInclusive::new(5, 65535);
570+
// store.bits[1023] = 0b1111111111111111111111111111111111111111111111111111111111111111
571+
store.insert_range(range_second);
572+
store.remove_back(2);
573+
assert_eq!(
574+
store.bits[1023],
575+
0b11111111111111111111111111111111111111111111111111111111111111
576+
);
577+
}
580578
}

0 commit comments

Comments
 (0)