Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 62 additions & 1 deletion benchmarks/benches/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,66 @@ fn successive_or(c: &mut Criterion) {
group.finish();
}

fn interleaved_containers(c: &mut Criterion) {
let mut group = c.benchmark_group("interleaved_containers");
group.sample_size(10);

// One bitmap has containers at even keys and the other one at odd keys,
// so that none of the containers of one side exists on the other side.
for size in [8192u32, 16384, 32768] {
let even: RoaringBitmap = (0..size).map(|key| key << 17).collect();
let odd: RoaringBitmap = (0..size).map(|key| (key << 17) | (1 << 16)).collect();

group.bench_function(BenchmarkId::new("or_assign_own", size), |b| {
b.iter_batched(
|| (even.clone(), odd.clone()),
|(mut a, b)| {
a |= b;
a
},
BatchSize::LargeInput,
);
});

group.bench_function(BenchmarkId::new("or_assign_ref", size), |b| {
b.iter_batched(
|| even.clone(),
|mut a| {
a |= &odd;
a
},
BatchSize::LargeInput,
);
});

group.bench_function(BenchmarkId::new("multi_or_own", size), |b| {
b.iter_batched(
|| [even.clone(), odd.clone()],
|bitmaps| bitmaps.union(),
BatchSize::LargeInput,
);
});

group.bench_function(BenchmarkId::new("multi_or_ref", size), |b| {
b.iter(|| [&even, &odd].union());
});

group.bench_function(BenchmarkId::new("multi_xor_own", size), |b| {
b.iter_batched(
|| [even.clone(), odd.clone()],
|bitmaps| bitmaps.symmetric_difference(),
BatchSize::LargeInput,
);
});

group.bench_function(BenchmarkId::new("multi_xor_ref", size), |b| {
b.iter(|| [&even, &odd].symmetric_difference());
});
}

group.finish();
}

// LEGACY BENCHMARKS
// =================

Expand Down Expand Up @@ -765,6 +825,7 @@ criterion_group!(
serialization,
deserialization,
successive_and,
successive_or
successive_or,
interleaved_containers
);
criterion_main!(benches);
10 changes: 7 additions & 3 deletions roaring/src/bitmap/multiops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use alloc::borrow::Cow;

use crate::{MultiOps, RoaringBitmap};

use super::{container::Container, store::Store};
use super::{container::Container, store::Store, util::SortedInserts};

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
Expand Down Expand Up @@ -274,9 +274,10 @@ fn merge_container_owned(
rhs: Vec<Container>,
op: impl Fn(&mut Store, Store),
) {
let mut inserts = SortedInserts::new();
for mut rhs in rhs {
match lhs.binary_search_by_key(&rhs.key, |c| c.key) {
Err(loc) => lhs.insert(loc, rhs),
Err(loc) => inserts.insert(lhs, loc, rhs),
Comment on lines 279 to +280

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not even sure to understand how it can work because a container that is not found during the first loop run must be inserted and the next loop will be able to find it and will therefore enter the Ok branch hand this time, triggering the op function to merge both containers.

This currently works because you use the FEW_INSERTS and SHORT_SHIFT parameters to still insert in the target containers (and find the freshly inserted container) but it will no longer work if you inserted too many containers already or if you happen to insert too far on the left. I thought these container mergings could have been implement in the SortedInserts::finish method but as far as I read it I don't see anything like that.

I find the idea to avoid shifts really good but the implementation doesn't seems correct to me.

Ok(loc) => {
let lhs = &mut lhs[loc];
match (&lhs.store, &rhs.store) {
Expand All @@ -288,6 +289,7 @@ fn merge_container_owned(
}
}
}
inserts.finish(lhs);
}

#[inline]
Expand Down Expand Up @@ -390,11 +392,12 @@ fn merge_container_ref<'a>(
rhs: &'a [Container],
op: impl Fn(&mut Store, &Store),
) {
let mut inserts = SortedInserts::new();
for rhs in rhs {
match containers.binary_search_by_key(&rhs.key, |c| c.key) {
Err(loc) => {
// A container not currently in containers. Borrow it.
containers.insert(loc, Cow::Borrowed(rhs))
inserts.insert(containers, loc, Cow::Borrowed(rhs))
}
Ok(loc) => {
// A container that is in containers. Operate on it.
Expand Down Expand Up @@ -431,6 +434,7 @@ fn merge_container_ref<'a>(
}
}
}
inserts.finish(containers);
}

#[inline]
Expand Down
9 changes: 7 additions & 2 deletions roaring/src/bitmap/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use core::mem;
use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Sub, SubAssign};

use crate::bitmap::container::Container;
use crate::bitmap::util::SortedInserts;
use crate::bitmap::Pairs;
use crate::RoaringBitmap;

Expand Down Expand Up @@ -161,26 +162,30 @@ impl BitOrAssign<RoaringBitmap> for RoaringBitmap {
mem::swap(self, &mut rhs);
}

let mut inserts = SortedInserts::new();
for container in rhs.containers {
let key = container.key;
match self.containers.binary_search_by_key(&key, |c| c.key) {
Err(loc) => self.containers.insert(loc, container),
Err(loc) => inserts.insert(&mut self.containers, loc, container),
Ok(loc) => BitOrAssign::bitor_assign(&mut self.containers[loc], container),
}
}
inserts.finish(&mut self.containers);
}
}

impl BitOrAssign<&RoaringBitmap> for RoaringBitmap {
/// An `union` between two sets.
fn bitor_assign(&mut self, rhs: &RoaringBitmap) {
let mut inserts = SortedInserts::new();
for container in &rhs.containers {
let key = container.key;
match self.containers.binary_search_by_key(&key, |c| c.key) {
Err(loc) => self.containers.insert(loc, container.clone()),
Err(loc) => inserts.insert(&mut self.containers, loc, container.clone()),
Ok(loc) => BitOrAssign::bitor_assign(&mut self.containers[loc], container),
}
}
inserts.finish(&mut self.containers);
}
}

Expand Down
87 changes: 86 additions & 1 deletion roaring/src/bitmap/util.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use core::ops::{Bound, RangeBounds, RangeInclusive};

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

/// Returns the container key and the index
/// in this container for a given integer.
#[inline]
Expand Down Expand Up @@ -61,11 +64,66 @@ where
}
}

// Thresholds of `SortedInserts`, picked from benchmarks.
const FEW_INSERTS: usize = 8;
const SHORT_SHIFT: usize = 64;

/// Inserts values into a sorted `Vec` at the positions given by failed binary searches.
///
/// Every insertion shifts the values after it, which is quadratic when many values are
/// interleaved with the existing ones. So a value is only inserted directly when that is
/// cheap: when it shifts fewer than `SHORT_SHIFT` values, or for the first `FEW_INSERTS`
/// values that shift more. The other ones are deferred and merged into the vector by
/// `finish` in a single pass.
pub struct SortedInserts<T> {
long_inserts: usize,
deferred: Vec<(usize, T)>,
}

impl<T> SortedInserts<T> {
pub fn new() -> Self {
SortedInserts { long_inserts: 0, deferred: Vec::new() }
}

/// Inserts `value` at `index` in `vec`, or defers it until `finish` is called.
/// `index` must come from a failed binary search in `vec`, and values must be
/// given in ascending order.
pub fn insert(&mut self, vec: &mut Vec<T>, index: usize, value: T) {
let short = vec.len() - index < SHORT_SHIFT;
if short || self.long_inserts < FEW_INSERTS {
// The deferred indexes stay valid: the values deferred so far belong at or
// before `index`, so before `value`.
vec.insert(index, value);
self.long_inserts += usize::from(!short);
} else {
self.deferred.push((index, value));
}
}

/// Merges the deferred values into `vec`, moving the values that follow the first
/// deferred index once.
pub fn finish(self, vec: &mut Vec<T>) {
let Some(&(start, _)) = self.deferred.first() else { return };
vec.reserve(self.deferred.len());
let mut tail = vec.split_off(start).into_iter();
let mut prev = start;
for (index, value) in self.deferred {
vec.extend(tail.by_ref().take(index - prev));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to depend on deferred being in sorted order: otherwise, index could be less than prev (and would panic in debug mode, do weird stuff in release mode).

@Kerollmops Kerollmops Oct 27, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed, @Dr-Emann is right here. In the insert method, you push a tuple of index and value that are arbitrary, and the first index could be larger than the second one pushed. Then, in the finish method, you iterate over all the deferred entries and seem to try to implement some sort of merge join, but the deferred values are always pushed back (never inserted, obviously). To implement a merge join, deferred values must be in sorted order.

I ran the fuzzer for ten minutes but didn't find anything, yet...

vec.push(value);
prev = index;
}
vec.extend(tail);
}
}

#[cfg(test)]
mod test {
use super::{convert_range_to_inclusive, join, split, ConvertRangeError};
use super::{convert_range_to_inclusive, join, split, ConvertRangeError, SortedInserts};
use core::ops::Bound;

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

#[test]
fn test_split_u32() {
assert_eq!((0x0000u16, 0x0000u16), split(0x0000_0000u32));
Expand Down Expand Up @@ -119,4 +177,31 @@ mod test {
convert_range_to_inclusive((Bound::Excluded(0), Bound::Included(0)))
);
}

#[test]
fn test_sorted_inserts() {
fn check(mut vec: Vec<u32>, values: Vec<u32>) {
let mut expected = [vec.as_slice(), values.as_slice()].concat();
expected.sort_unstable();

let mut inserts = SortedInserts::new();
for value in values {
let index = vec.binary_search(&value).unwrap_err();
inserts.insert(&mut vec, index, value);
}
inserts.finish(&mut vec);
assert_eq!(vec, expected);
}

let even: Vec<u32> = (0..1000).map(|i| 2 * i).collect();
let odd: Vec<u32> = (0..1000).map(|i| 2 * i + 1).collect();
check(even.clone(), odd.clone());
check(odd.clone(), even.clone());
check(even.clone(), (0..5).map(|i| 400 * i + 1).collect());
check(even.clone(), (2000..3000).collect());
check(even[500..600].to_vec(), odd[..100].iter().chain(&odd[900..]).copied().collect());
check(even[..10].to_vec(), odd[..100].to_vec());
check(Vec::new(), odd.clone());
check(even, Vec::new());
}
}
77 changes: 76 additions & 1 deletion roaring/tests/symmetric_difference_with.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
extern crate roaring;
use roaring::RoaringBitmap;
use std::collections::BTreeSet;

use proptest::collection::vec;
use proptest::prelude::*;
use roaring::{MultiOps, RoaringBitmap};

#[test]
fn array() {
Expand Down Expand Up @@ -122,3 +126,74 @@ fn bitmaps() {

assert_eq!(bitmap1, bitmap3);
}

#[test]
fn interleaved_containers() {
// One side has containers at even keys and the other one at odd keys.
let even = (0..4096).map(|key| key << 17).collect::<RoaringBitmap>();
let odd = (0..4096).map(|key| (key << 17) | (1 << 16)).collect::<RoaringBitmap>();
let expected = (0..8192).map(|key| key << 16).collect::<RoaringBitmap>();

let mut bitmap = even.clone();
bitmap ^= &odd;
assert_eq!(bitmap, expected);

let mut bitmap = odd.clone();
bitmap ^= even.clone();
assert_eq!(bitmap, expected);

assert_eq!([&even, &odd].symmetric_difference(), expected);
assert_eq!([odd, even].symmetric_difference(), expected);
}

/// A bitmap made of ranges of up to 64 values spread over up to 512 containers,
/// along with the set of its values.
fn bitmap_and_set() -> impl Strategy<Value = (RoaringBitmap, BTreeSet<u32>)> {
vec((0u32..512, any::<u16>(), 0u32..64), 0..256).prop_map(|ranges| {
let mut bitmap = RoaringBitmap::new();
let mut set = BTreeSet::new();
for (key, low, len) in ranges {
let start = (key << 16) | u32::from(low);
let end = (start + len).min(start | 0xFFFF);
bitmap.insert_range(start..=end);
set.extend(start..=end);
}
(bitmap, set)
})
}

proptest! {
#[test]
fn symmetric_difference_matches_btreeset(
(a, set_a) in bitmap_and_set(),
(b, set_b) in bitmap_and_set(),
(c, set_c) in bitmap_and_set(),
) {
let expected = &set_a ^ &set_b;

let mut assign_ref = a.clone();
assign_ref ^= &b;
let mut assign_own = a.clone();
assign_own ^= b.clone();

for bitmap in [
assign_ref,
assign_own,
&a ^ &b,
&a ^ b.clone(),
a.clone() ^ &b,
a.clone() ^ b.clone(),
[&a, &b].symmetric_difference(),
[a.clone(), b.clone()].symmetric_difference(),
] {
prop_assert_eq!(bitmap.len(), expected.len() as u64);
prop_assert!(bitmap.iter().eq(expected.iter().copied()));
}

let expected = &expected ^ &set_c;
for bitmap in [[&a, &b, &c].symmetric_difference(), [a, b, c].symmetric_difference()] {
prop_assert_eq!(bitmap.len(), expected.len() as u64);
prop_assert!(bitmap.iter().eq(expected.iter().copied()));
}
}
}
Loading
Loading