Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add toggle_range #38

Merged
merged 1 commit into from Apr 19, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 32 additions & 1 deletion src/lib.rs
Expand Up @@ -198,7 +198,7 @@ impl FixedBitSet

/// Sets every bit in the given range to the given state (`enabled`)
///
/// Use `..` to toggle the whole bitset.
/// Use `..` to set the whole bitset.
///
/// **Panics** if the range extends past the end of the bitset.
#[inline]
Expand Down Expand Up @@ -226,6 +226,21 @@ impl FixedBitSet
self.set_range(range, true);
}

/// Toggles (inverts) every bit in the given range.
///
/// Use `..` to toggle the whole bitset.
///
/// **Panics** if the range extends past the end of the bitset.
#[inline]
pub fn toggle_range<T: IndexRange>(&mut self, range: T)
{
for (block, mask) in Masks::new(range, self.length) {
unsafe {
*self.data.get_unchecked_mut(block) ^= mask;
}
}
}

/// View the bitset as a slice of `u32` blocks
#[inline]
pub fn as_slice(&self) -> &[u32]
Expand Down Expand Up @@ -885,6 +900,22 @@ fn set_range() {
assert!(!fb.contains(64));
}

#[test]
fn toggle_range() {
let mut fb = FixedBitSet::with_capacity(40);
fb.insert_range(..10);
fb.insert_range(34..38);

fb.toggle_range(5..12);
fb.toggle_range(30..);

for i in 0..40 {
assert_eq!(fb.contains(i), i<5 || 10<=i&&i<12 || 30<=i&&i<34 || 38<=i);
}
assert!(!fb.contains(40));
assert!(!fb.contains(64));
}

#[test]
fn bitand_equal_lengths() {
let len = 109;
Expand Down