Struct BitVec
pub struct BitVec<B = u32> { /* private fields */ }
The bitvector type.
Examples
use bit_vec::BitVec;
let mut bv = BitVec::from_elem(10, false);
// insert all primes less than 10
bv.set(2, true);
bv.set(3, true);
bv.set(5, true);
bv.set(7, true);
println!("{:?}", bv);
println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
// flip all values in bitvector, producing non-primes less than 10
bv.negate();
println!("{:?}", bv);
println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
// reset bitvector to empty
bv.fill(false);
println!("{:?}", bv);
println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
Implementations
impl BitVec<u32>
fn new() -> SelfCreates an empty
BitVec.Examples
use bit_vec::BitVec; let mut bv = BitVec::new();fn from_elem(len: usize, bit: bool) -> SelfCreates a
BitVecthat holdsnbitselements, setting each element tobit.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_elem(10, false); assert_eq!(bv.len(), 10); for x in bv.iter() { assert_eq!(x, false); }fn with_capacity(capacity: usize) -> SelfConstructs a new, empty
BitVecwith the specified capacity.The bitvector will be able to hold at least
capacitybits without reallocating. Ifcapacityis 0, it will not allocate.It is important to note that this function does not specify the length of the returned bitvector, but only the capacity.
fn from_bytes(bytes: &[u8]) -> SelfTransforms a byte-vector into a
BitVec. Each byte becomes eight bits, with the most significant bits of each byte coming first. Each bit becomestrueif equal to 1 orfalseif equal to 0.Examples
use bit_vec::BitVec; let bv = BitVec::from_bytes(&[0b10100000, 0b00010010]); assert!(bv.eq_vec(&[true, false, true, false, false, false, false, false, false, false, false, true, false, false, true, false]));fn from_fn<F>(len: usize, f: F) -> Self where F: FnMut(usize) -> bool,Creates a
BitVecof the specified length where the value at each index isf(index).Examples
use bit_vec::BitVec; let bv = BitVec::from_fn(5, |i| { i % 2 == 0 }); assert!(bv.eq_vec(&[true, false, true, false, true]));
impl<B: BitBlock> BitVec<B>
fn new_general() -> SelfCreates an empty
BitVec.Examples
use bit_vec::BitVec; let mut bv = BitVec::<usize>::new_general();fn from_elem_general(len: usize, bit: bool) -> SelfCreates a
BitVecthat holdsnbitselements, setting each element tobit.Examples
use bit_vec::BitVec; let mut bv = BitVec::<usize>::from_elem_general(10, false); assert_eq!(bv.len(), 10); for x in bv.iter() { assert_eq!(x, false); }fn with_capacity_general(capacity: usize) -> SelfConstructs a new, empty
BitVecwith the specified capacity.The bitvector will be able to hold at least
capacitybits without reallocating. Ifcapacityis 0, it will not allocate.It is important to note that this function does not specify the length of the returned bitvector, but only the capacity.
fn from_bytes_general(bytes: &[u8]) -> SelfTransforms a byte-vector into a
BitVec. Each byte becomes eight bits, with the most significant bits of each byte coming first. Each bit becomestrueif equal to 1 orfalseif equal to 0.Examples
use bit_vec::BitVec; let bv = BitVec::<usize>::from_bytes_general(&[0b10100000, 0b00010010]); assert!(bv.eq_vec(&[true, false, true, false, false, false, false, false, false, false, false, true, false, false, true, false]));fn from_fn_general<F>(len: usize, f: F) -> Self where F: FnMut(usize) -> bool,Creates a
BitVecof the specified length where the value at each index isf(index).Examples
use bit_vec::BitVec; let bv = BitVec::<usize>::from_fn_general(5, |i| { i % 2 == 0 }); assert!(bv.eq_vec(&[true, false, true, false, true]));fn blocks(&self) -> Blocks<'_, B>Iterator over the underlying blocks of data
fn storage(&self) -> &[B]Exposes the raw block storage of this
BitVec.Only really intended for
BitSet.unsafe fn storage_mut(&mut self) -> &mut Vec<B>Exposes the raw block storage of this
BitVec.Safety
Can break the structure's invariants despite not giving real memory unsafety. Only really intended for
BitSet.fn get(&self, i: usize) -> Option<bool>Retrieves the value at index
i, orNoneif the index is out of bounds.Examples
use bit_vec::BitVec; let bv = BitVec::from_bytes(&[0b01100000]); assert_eq!(bv.get(0), Some(false)); assert_eq!(bv.get(1), Some(true)); assert_eq!(bv.get(100), None); // Can also use array indexing assert_eq!(bv[1], true);unsafe fn get_unchecked(&self, i: usize) -> boolRetrieves the value at index
i, without doing bounds checking.For a safe alternative, see
get.Safety
Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used.
Examples
use bit_vec::BitVec; let bv = BitVec::from_bytes(&[0b01100000]); // Safety: // We access the structure with in-bounds indices (those smaller // than 32). unsafe { assert_eq!(bv.get_unchecked(0), false); assert_eq!(bv.get_unchecked(1), true); }fn get_mut(&mut self, index: usize) -> Option<MutBorrowedBit<'_, B>>Retrieves a smart pointer to the value at index
i, orNoneif the index is out of bounds.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_bytes(&[0b01100000]); *bv.get_mut(0).unwrap() = true; *bv.get_mut(1).unwrap() = false; assert!(bv.get_mut(100).is_none()); assert_eq!(bv, BitVec::from_bytes(&[0b10100000]));unsafe fn get_unchecked_mut(&mut self, index: usize) -> MutBorrowedBit<'_, B>Retrieves a smart pointer to the value at index
i, without doing bounds checking.Safety
Calling this method with out-of-bounds
indexmay cause undefined behavior even when the result is not used.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_bytes(&[0b01100000]); unsafe { *bv.get_unchecked_mut(0) = true; *bv.get_unchecked_mut(1) = false; } assert_eq!(bv, BitVec::from_bytes(&[0b10100000]));fn set(&mut self, i: usize, x: bool)Sets the value of a bit at an index
i.Panics
Panics if
iis out of bounds.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_elem(5, false); bv.set(3, true); assert_eq!(bv[3], true);fn set_all(&mut self)Sets all bits to 1.
Examples
use bit_vec::BitVec; let before = 0b01100000; let after = 0b11111111; let mut bv = BitVec::from_bytes(&[before]); bv.set_all(); assert_eq!(bv, BitVec::from_bytes(&[after]));fn negate(&mut self)Flips all bits.
Examples
use bit_vec::BitVec; let before = 0b01100000; let after = 0b10011111; let mut bv = BitVec::from_bytes(&[before]); bv.negate(); assert_eq!(bv, BitVec::from_bytes(&[after]));fn union(&mut self, other: &Self) -> boolCalculates the union of two bitvectors. This acts like the bitwise
orfunction.Sets
selfto the union ofselfandother. Both bitvectors must be the same length. Returnstrueifselfchanged.Panics
Panics if the bitvectors are of different lengths.
Examples
use bit_vec::BitVec; let a = 0b01100100; let b = 0b01011010; let res = 0b01111110; let mut a = BitVec::from_bytes(&[a]); let b = BitVec::from_bytes(&[b]); assert!(a.union(&b)); assert_eq!(a, BitVec::from_bytes(&[res]));fn intersect(&mut self, other: &Self) -> boolCalculates the intersection of two bitvectors. This acts like the bitwise
andfunction.Sets
selfto the intersection ofselfandother. Both bitvectors must be the same length. Returnstrueifselfchanged.Panics
Panics if the bitvectors are of different lengths.
Examples
use bit_vec::BitVec; let a = 0b01100100; let b = 0b01011010; let res = 0b01000000; let mut a = BitVec::from_bytes(&[a]); let b = BitVec::from_bytes(&[b]); assert!(a.intersect(&b)); assert_eq!(a, BitVec::from_bytes(&[res]));fn or(&mut self, other: &Self) -> boolCalculates the bitwise
orof two bitvectors.Sets
selfto the union ofselfandother. Both bitvectors must be the same length. Returnstrueifselfchanged.Panics
Panics if the bitvectors are of different lengths.
Examples
use bit_vec::BitVec; let a = 0b01100100; let b = 0b01011010; let res = 0b01111110; let mut a = BitVec::from_bytes(&[a]); let b = BitVec::from_bytes(&[b]); assert!(a.or(&b)); assert_eq!(a, BitVec::from_bytes(&[res]));fn and(&mut self, other: &Self) -> boolCalculates the bitwise
andof two bitvectors.Sets
selfto the intersection ofselfandother. Both bitvectors must be the same length. Returnstrueifselfchanged.Panics
Panics if the bitvectors are of different lengths.
Examples
use bit_vec::BitVec; let a = 0b01100100; let b = 0b01011010; let res = 0b01000000; let mut a = BitVec::from_bytes(&[a]); let b = BitVec::from_bytes(&[b]); assert!(a.and(&b)); assert_eq!(a, BitVec::from_bytes(&[res]));fn difference(&mut self, other: &Self) -> boolCalculates the difference between two bitvectors.
Sets each element of
selfto the value of that element minus the element ofotherat the same index. Both bitvectors must be the same length. Returnstrueifselfchanged.Panics
Panics if the bitvectors are of different length.
Examples
use bit_vec::BitVec; let a = 0b01100100; let b = 0b01011010; let a_b = 0b00100100; // a - b let b_a = 0b00011010; // b - a let mut bva = BitVec::from_bytes(&[a]); let bvb = BitVec::from_bytes(&[b]); assert!(bva.difference(&bvb)); assert_eq!(bva, BitVec::from_bytes(&[a_b])); let bva = BitVec::from_bytes(&[a]); let mut bvb = BitVec::from_bytes(&[b]); assert!(bvb.difference(&bva)); assert_eq!(bvb, BitVec::from_bytes(&[b_a]));fn xor(&mut self, other: &Self) -> boolCalculates the xor of two bitvectors.
Sets
selfto the xor ofselfandother. Both bitvectors must be the same length. Returnstrueifselfchanged.Panics
Panics if the bitvectors are of different length.
Examples
use bit_vec::BitVec; let a = 0b01100110; let b = 0b01010100; let res = 0b00110010; let mut a = BitVec::from_bytes(&[a]); let b = BitVec::from_bytes(&[b]); assert!(a.xor(&b)); assert_eq!(a, BitVec::from_bytes(&[res]));fn nand(&mut self, other: &Self) -> boolCalculates the nand of two bitvectors.
Sets
selfto the nand ofselfandother. Both bitvectors must be the same length. Returnstrueifselfchanged.Panics
Panics if the bitvectors are of different length.
Examples
use bit_vec::BitVec; let a = 0b01100110; let b = 0b01010100; let res = 0b10111011; let mut a = BitVec::from_bytes(&[a]); let b = BitVec::from_bytes(&[b]); assert!(a.nand(&b)); assert_eq!(a, BitVec::from_bytes(&[res]));fn nor(&mut self, other: &Self) -> boolCalculates the nor of two bitvectors.
Sets
selfto the nor ofselfandother. Both bitvectors must be the same length. Returnstrueifselfchanged.Panics
Panics if the bitvectors are of different length.
Examples
use bit_vec::BitVec; let a = 0b01100110; let b = 0b01010100; let res = 0b10001001; let mut a = BitVec::from_bytes(&[a]); let b = BitVec::from_bytes(&[b]); assert!(a.nor(&b)); assert_eq!(a, BitVec::from_bytes(&[res]));fn xnor(&mut self, other: &Self) -> boolCalculates the xnor of two bitvectors.
Sets
selfto the xnor ofselfandother. Both bitvectors must be the same length. Returnstrueifselfchanged.Panics
Panics if the bitvectors are of different length.
Examples
use bit_vec::BitVec; let a = 0b01100110; let b = 0b01010100; let res = 0b11001101; let mut a = BitVec::from_bytes(&[a]); let b = BitVec::from_bytes(&[b]); assert!(a.xnor(&b)); assert_eq!(a, BitVec::from_bytes(&[res]));fn all(&self) -> boolReturns
trueif all bits are 1.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_elem(5, true); assert_eq!(bv.all(), true); bv.set(1, false); assert_eq!(bv.all(), false);fn count_ones(&self) -> u64Returns the number of ones in the binary representation.
Also known as the Hamming weight.
Examples
use bit_vec::BitVec; let mut bv = BitVec::from_elem(100, true); assert_eq!(bv.count_ones(), 100); bv.set(50, false); assert_eq!(bv.count_ones(), 99);fn count_zeros(&self) -> u64Returns the number of zeros in the binary representation.
Also known as the opposite of Hamming weight.
Examples
use bit_vec::BitVec; let mut bv = BitVec::from_elem(100, false); assert_eq!(bv.count_zeros(), 100); bv.set(50, true); assert_eq!(bv.count_zeros(), 99);fn iter(&self) -> Iter<'_, B>Returns an iterator over the elements of the vector in order.
Examples
use bit_vec::BitVec; let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]); assert_eq!(bv.iter().filter(|x| *x).count(), 7);fn iter_mut(&mut self) -> IterMut<'_, B>Returns an iterator over mutable smart pointers to the elements of the vector in order.
Examples
use bit_vec::BitVec; let mut a = BitVec::from_elem(8, false); a.iter_mut().enumerate().for_each(|(index, mut bit)| { *bit = if index % 2 == 1 { true } else { false }; }); assert!(a.eq_vec(&[ false, true, false, true, false, true, false, true ]));fn append(&mut self, other: &mut Self)Moves all bits from
otherintoSelf, leavingotherempty.Examples
use bit_vec::BitVec; let mut a = BitVec::from_bytes(&[0b10000000]); let mut b = BitVec::from_bytes(&[0b01100001]); a.append(&mut b); assert_eq!(a.len(), 16); assert_eq!(b.len(), 0); assert!(a.eq_vec(&[true, false, false, false, false, false, false, false, false, true, true, false, false, false, false, true]));fn split_off(&mut self, at: usize) -> SelfSplits the
BitVecinto two at the given bit, retaining the first half in-place and returning the second one.Panics
Panics if
atis out of bounds.Examples
use bit_vec::BitVec; let mut a = BitVec::new(); a.push(true); a.push(false); a.push(false); a.push(true); let b = a.split_off(2); assert_eq!(a.len(), 2); assert_eq!(b.len(), 2); assert!(a.eq_vec(&[true, false])); assert!(b.eq_vec(&[false, true]));fn none(&self) -> boolReturns
trueif all bits are 0.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_elem(10, false); assert_eq!(bv.none(), true); bv.set(3, true); assert_eq!(bv.none(), false);fn any(&self) -> boolReturns
trueif any bit is 1.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_elem(10, false); assert_eq!(bv.any(), false); bv.set(3, true); assert_eq!(bv.any(), true);fn to_bytes(&self) -> Vec<u8>Organises the bits into bytes, such that the first bit in the
BitVecbecomes the high-order bit of the first byte. If the size of theBitVecis not a multiple of eight then trailing bits will be filled-in withfalse.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_elem(3, true); bv.set(1, false); assert_eq!(bv.to_bytes(), [0b10100000]); let mut bv = BitVec::from_elem(9, false); bv.set(2, true); bv.set(8, true); assert_eq!(bv.to_bytes(), [0b00100000, 0b10000000]);fn eq_vec(&self, v: &[bool]) -> boolCompares a
BitVecto a slice ofbools. Both theBitVecand slice must have the same length.Panics
Panics if the
BitVecand slice are of different length.Examples
use bit_vec::BitVec; let bv = BitVec::from_bytes(&[0b10100000]); assert!(bv.eq_vec(&[true, false, true, false, false, false, false, false]));fn truncate(&mut self, len: usize)Shortens a
BitVec, dropping excess elements.If
lenis greater than the vector's current length, this has no effect.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_bytes(&[0b01001011]); bv.truncate(2); assert!(bv.eq_vec(&[false, true]));fn reserve(&mut self, additional: usize)Reserves capacity for at least
additionalmore bits to be inserted in the givenBitVec. The collection may reserve more space to avoid frequent reallocations.Panics
Panics if the new capacity overflows
usize.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_elem(3, false); bv.reserve(10); assert_eq!(bv.len(), 3); assert!(bv.capacity() >= 13);fn reserve_exact(&mut self, additional: usize)Reserves the minimum capacity for exactly
additionalmore bits to be inserted in the givenBitVec. Does nothing if the capacity is already sufficient.Note that the allocator may give the collection more space than it requests. Therefore capacity can not be relied upon to be precisely minimal. Prefer
reserveif future insertions are expected.Panics
Panics if the new capacity overflows
usize.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_elem(3, false); bv.reserve(10); assert_eq!(bv.len(), 3); assert!(bv.capacity() >= 13);fn capacity(&self) -> usizeReturns the capacity in bits for this bit vector. Inserting any element less than this amount will not trigger a resizing.
Examples
use bit_vec::BitVec; let mut bv = BitVec::new(); bv.reserve(10); assert!(bv.capacity() >= 10);fn grow(&mut self, n: usize, value: bool)Grows the
BitVecin-place, addingncopies ofvalueto theBitVec.Panics
Panics if the new len overflows a
usize.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_bytes(&[0b01001011]); bv.grow(2, true); assert_eq!(bv.len(), 10); assert_eq!(bv.to_bytes(), [0b01001011, 0b11000000]);fn pop(&mut self) -> Option<bool>Removes the last bit from the
BitVec, and returns it. ReturnsNoneif theBitVecis empty.Examples
use bit_vec::BitVec; let mut bv = BitVec::from_bytes(&[0b01001001]); assert_eq!(bv.pop(), Some(true)); assert_eq!(bv.pop(), Some(false)); assert_eq!(bv.len(), 6);fn push(&mut self, elem: bool)Pushes a
boolonto the end.Examples
use bit_vec::BitVec; let mut bv = BitVec::new(); bv.push(true); bv.push(false); assert!(bv.eq_vec(&[true, false]));fn len(&self) -> usizeReturns the total number of bits in this vector
unsafe fn set_len(&mut self, len: usize)Sets the number of bits that this
BitVecconsiders initialized.Safety
Almost certainly can cause bad stuff. Only really intended for
BitSet.fn is_empty(&self) -> boolReturns true if there are no bits in this vector
fn clear(&mut self)Clears all bits in this vector.
fn fill(&mut self, bit: bool)Assigns all bits in this vector to the given boolean value.
Invariants
fn shrink_to_fit(&mut self)Shrinks the capacity of the underlying storage as much as possible.
It will drop down as close as possible to the length but the allocator may still inform the underlying storage that there is space for a few more elements/bits.
fn insert(&mut self, at: usize, bit: bool)Inserts a given bit at index
at, shifting all bits after by onePanics
Panics if
atis out of bounds forBitVec's length (that is, ifat > BitVec::len())Examples
use bit_vec::BitVec; let mut b = BitVec::new(); b.push(true); b.push(true); b.insert(1, false); assert!(b.eq_vec(&[true, false, true]));Time complexity
Takes O(
len) time. All items after the insertion index must be shifted to the right. In the worst case, all elements are shifted when the insertion index is 0.fn remove(&mut self, at: usize) -> boolRemove a bit at index
at, shifting all bits after by one.Panics
Panics if
atis out of bounds forBitVec's length (that is, ifat >= BitVec::len())Examples
use bit_vec::BitVec; let mut b = BitVec::new(); b.push(true); b.push(false); b.push(false); b.push(true); assert!(!b.remove(1)); assert!(b.eq_vec(&[true, false, true]));Time complexity
Takes O(
len) time. All items after the removal index must be shifted to the left. In the worst case, all elements are shifted when the removal index is 0.fn remove_all(&mut self)Removes all bits in this vector.
Note: this method is not named
clearto avoid confusion whenever.fill(false)is needed.fn push_within_capacity(&mut self, bit: bool) -> Result<(), bool>Appends an element if there is sufficient spare capacity, otherwise an error is returned with the element.
Unlike
pushthis method will not reallocate when there's insufficient capacity. The caller should usereserveto ensure that there is enough capacity.Examples
use bit_vec::BitVec; let initial_capacity = 64; let mut bitvec = BitVec::with_capacity(64); for _ in 0..initial_capacity - 1 { bitvec.push(false); } assert_eq!(bitvec.len(), initial_capacity - 1); // there is space for only 1 bit assert_eq!(bitvec.push_within_capacity(true), Ok(())); // Successfully push a bit assert_eq!(bitvec.len(), initial_capacity); // So we can't push within capacity anymore assert_eq!(bitvec.push_within_capacity(true), Err(true)); assert_eq!(bitvec.len(), initial_capacity); assert_eq!(bitvec.capacity(), initial_capacity);Time Complexity
Takes O(1) time.
Trait Implementations
impl<B: BitBlock> Clone for BitVec<B>
fn clone(&self) -> Selffn clone_from(&mut self, source: &Self)
impl<B: BitBlock> Debug for BitVec<B>
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result
impl<B: BitBlock> Default for BitVec<B>
fn default() -> Self
impl<B: BitBlock> Display for BitVec<B>
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result
impl<B: BitBlock> Eq for BitVec<B>
impl<B: BitBlock> Extend<bool> for BitVec<B>
fn extend<I: IntoIterator<Item = bool>>(&mut self, iterable: I)
impl<B: BitBlock> FromIterator<bool> for BitVec<B>
fn from_iter<I: IntoIterator<Item = bool>>(iter: I) -> Self
impl<B: BitBlock> Hash for BitVec<B>
fn hash<H: Hasher>(&self, state: &mut H)
impl<B: BitBlock> Index<usize> for BitVec<B>
type Output = bool;fn index(&self, i: usize) -> &bool
impl<B: BitBlock> IntoIterator for BitVec<B>
type Item = bool;type IntoIter = IntoIter<B>;fn into_iter(self) -> IntoIter<B>
impl<B: BitBlock> Ord for BitVec<B>
fn cmp(&self, other: &Self) -> Ordering
impl<B: BitBlock> PartialEq for BitVec<B>
fn eq(&self, other: &Self) -> bool
impl<B: BitBlock> PartialOrd for BitVec<B>
fn partial_cmp(&self, other: &Self) -> Option<Ordering>