Struct bitvec::BitVec

source ·
#[repr(transparent)]
pub struct BitVec<C = BigEndian, T = u8>where
    C: Cursor,
    T: Bits,
{ /* private fields */ }
Expand description

A compact Vec of bits, whose cursor and storage type can be customized.

BitVec is a newtype wrapper over Vec, and as such is exactly three words in size on the stack.

IMPORTANT NOTE: It is horrifically unsafe to use mem::transmute between Vec<T> and BitVec<_, T>, because BitVec achieves its size by using the length field of the underlying Vec to count bits, rather than elements. This means that it has a fixed maximum bit width regardless of element type, and the length field will always be horrifically wrong to be treated as a Vec. Safe methods exist to move between Vec and BitVecUSE THEM.

BitVec takes two type parameters.

  • C: Cursor must be an implementor of the Cursor trait. BitVec takes a PhantomData marker for access to the associated functions, and will never make use of an instance of the trait. The default implementations, LittleEndian and BigEndian, are zero-sized, and any further implementations should be as well, as the invoked functions will never receive state.
  • T: Bits must be a primitive type. Rust decided long ago to not provide a unifying trait over the primitives, so Bits provides access to just enough properties of the primitives for BitVec to use. This trait is sealed against downstream implementation, and can only be implemented in this crate.

Implementations

Constructs a new, empty, BitVec<C, T>.

The vector will not allocate until bits are pushed onto it.

Examples
use bitvec::*;
let bv: BitVec = BitVec::new();
assert!(bv.is_empty());
assert_eq!(bv.capacity(), 0);

Constructs a new, empty BitVec<T> with the specified capacity.

The vector will be able to hold exactly capacity elements without reallocating. If capacity is 0, the vector will not allocate.

Examples
use bitvec::*;
let bv: BitVec = BitVec::with_capacity(10);
assert!(bv.is_empty());
assert!(bv.capacity() >= 2);

Returns the number of bits the vector can hold without reallocating.

Examples
use bitvec::*;
let bv: BitVec = BitVec::with_capacity(10);
assert!(bv.is_empty());
assert!(bv.capacity() >= 2);

Appends a bit to the collection.

Examples
use bitvec::*;
let mut bv: BitVec = BitVec::new();
assert!(bv.is_empty());
bv.push(true);
assert_eq!(bv.len(), 1);
assert!(bv[0]);

Removes the last bit from the collection.

Returns None if the collection is empty.

Examples
use bitvec::*;
let mut bv: BitVec = BitVec::new();
assert!(bv.is_empty());
bv.push(true);
assert_eq!(bv.len(), 1);
assert!(bv[0]);

assert!(bv.pop().unwrap());
assert!(bv.is_empty());
assert!(bv.pop().is_none());

Empties out the BitVec, resetting it to length zero.

This does not affect the memory store! It will not zero the raw memory nor will it deallocate.

Examples
use bitvec::*;
let mut bv = bitvec![1; 30];
assert_eq!(bv.len(), 30);
assert!(bv.iter().all(|b| b));
bv.clear();
assert!(bv.is_empty());

After clear(), bv will no longer show raw memory, so the above test cannot show that the underlying memory is untouched. This is also an implementation detail on which you should not rely.

Reserves capacity for additional bits.

Examples
use bitvec::*;
let mut bv = bitvec![1; 5];
let cap = bv.capacity();
bv.reserve(10);
assert!(bv.capacity() >= cap + 10);

Shrinks the capacity to fit at least as much as is needed, but with as little or as much excess as the allocator chooses.

This may or may not deallocate tail space, as the allocator sees fit. This does not zero the abandoned memory.

Shrinks the BitVec to the given size, dropping all excess storage.

This does not affect the memory store! It will not zero the raw memory nor will it deallocate.

Examples
use bitvec::*;
let mut bv = bitvec![1; 30];
assert_eq!(bv.len(), 30);
let cap = bv.capacity();
bv.truncate(10);
assert_eq!(bv.len(), 10);
assert_eq!(bv.capacity(), cap);

Converts the BitVec into a boxed slice of storage elements. This drops all BitVec management semantics, including partial fill status of the trailing element or endianness, and gives ownership the raw storage.

Examples
use bitvec::*;
let bv: BitVec<BigEndian, u8> = bitvec![1; 64];
let bytes: Box<[u8]> = bv.into_boxed_slice();
assert_eq!(bytes.len(), 8);
for byte in bytes.iter() {
    assert_eq!(*byte, !0);
}

Sets the backing storage to the provided element.

This unconditionally sets each element in the backing storage to the provided value, without altering the BitVec length or capacity. It operates an the underlying Vec directly, and will ignore any partial bounds on the tail.

Examples
use bitvec::*;
let mut bv = bitvec![0; 10];
assert_eq!(bv.as_ref(), &[0, 0]);
bv.set_store(0xA5);
assert_eq!(bv.as_ref(), &[0xA5, 0xA5]);

Sets the length directly.

This is wildly unsafe! It directly sets the length of the vector to whatever you provide. As a sanity check, this absolutely will panic if the provided length would go past the vector’s allocated capacity.

Methods from Deref<Target = BitSlice<C, T>>

Gets the bit value at the given position.

The index value is a semantic count, not a bit address. It converts to a bit position internally to this function.

Examples
use bitvec::*;
let bv = bitvec![0, 0, 1, 0, 0];
let bits: &BitSlice = &bv;
assert!(bits.get(2));

Sets the bit value at the given position.

The index value is a semantic count, not a bit address. It converts to a bit position internally to this function.

Examples
use bitvec::*;
let mut bv = bitvec![0; 5];
let bits: &mut BitSlice = &mut bv;
bits.set(2, true);
assert!(bits.get(2));

Returns true if all bits in the slice are set (logical ).

Truth Table
0 0 => 0
0 1 => 0
1 0 => 0
1 1 => 1
Examples
use bitvec::*;
let all = bitvec![1; 10];
let any = bitvec![0, 0, 1, 0, 0];
let some = bitvec![1, 1, 0, 1, 1];
let none = bitvec![0; 10];

assert!(all.all());
assert!(!any.all());
assert!(!some.all());
assert!(!none.all());

Returns true if any bit in the slice is set (logical ).

Truth Table
0 0 => 0
0 1 => 1
1 0 => 1
1 1 => 1
Examples
use bitvec::*;
let all = bitvec![1; 10];
let any = bitvec![0, 0, 1, 0, 0];
let some = bitvec![1, 1, 0, 1, 1];
let none = bitvec![0; 10];

assert!(all.any());
assert!(any.any());
assert!(some.any());
assert!(!none.any());

Returns true if any bit in the slice is unset (logical ¬∧).

Truth Table
0 0 => 1
0 1 => 1
1 0 => 1
1 1 => 0
Examples
use bitvec::*;
let all = bitvec![1; 10];
let any = bitvec![0, 0, 1, 0, 0];
let some = bitvec![1, 1, 0, 1, 1];
let none = bitvec![0; 10];

assert!(!all.not_all());
assert!(any.not_all());
assert!(some.not_all());
assert!(none.not_all());

Returns true if all bits in the slice are unset (logical ¬∨).

Truth Table
0 0 => 1
0 1 => 0
1 0 => 0
1 1 => 0
Examples
use bitvec::*;
let all = bitvec![1; 10];
let any = bitvec![0, 0, 1, 0, 0];
let some = bitvec![1, 1, 0, 1, 1];
let none = bitvec![0; 10];

assert!(!all.not_any());
assert!(!any.not_any());
assert!(!some.not_any());
assert!(none.not_any());

Returns true if some, but not all, bits are set and some, but not all, are unset.

This is false if either all() or none() are true.

Truth Table
0 0 => 0
0 1 => 1
1 0 => 1
1 1 => 0
Examples
use bitvec::*;
let all = bitvec![1; 2];
let some = bitvec![1, 0];
let none = bitvec![0; 2];

assert!(!all.some());
assert!(some.some());
assert!(!none.some());

Counts how many bits are set high.

Examples
use bitvec::*;
let bv = bitvec![1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1];
assert_eq!(bv.count_ones(), 7);

Counts how many bits are set low.

Examples
use bitvec::*;
let bv = bitvec![1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1];
assert_eq!(bv.count_zeros(), 6);

Returns the number of bits contained in the BitSlice.

Examples
use bitvec::*;
let bv = bitvec![1; 10];
let bits: &BitSlice = &bv;
assert_eq!(bits.len(), 10);

Counts how many whole storage elements are in the BitSlice.

If the BitSlice length is not an even multiple of the width of T, then the slice under this BitSlice is one element longer than this method reports, and the number of bits in it are reported by bits().

Examples
use bitvec::*;
let bv = bitvec![1; 10];
let bits: &BitSlice = &bv;
assert_eq!(bits.elts(), 1);
use bitvec::*;
let bv = bitvec![1; 16];
let bits: &BitSlice = &bv;
assert_eq!(bits.elts(), 2);

Counts how many bits are in the trailing partial storage element.

If the BitSlice length is an even multiple of the width of T, then this returns 0 and the BitSlice does not consider its final element to be partially used.

Examples
use bitvec::*;
let bv = bitvec![1; 10];
let bits: &BitSlice = &bv;
assert_eq!(bits.bits(), 2);
use bitvec::*;
let bv = bitvec![1; 16];
let bits: &BitSlice = &bv;
assert_eq!(bits.bits(), 0);

Returns true if the slice contains no bits.

Examples
use bitvec::*;
let bv = bitvec![];
let bits: &BitSlice = &bv;
assert!(bits.is_empty());
use bitvec::*;
let bv = bitvec![0; 5];
let bits: &BitSlice = &bv;
assert!(!bits.is_empty());

Provides read-only iteration across the collection.

The iterator returned from this method implements ExactSizeIterator and DoubleEndedIterator just as the consuming .into_iter() method’s iterator does.

Provides mutable traversal of the collection.

It is impossible to implement IndexMut on BitSlice because bits do not have addresses, so there can be no &mut u1. This method allows the client to receive an enumerated bit, and provide a new bit to set at each index.

Examples
use bitvec::*;
let mut bv = bitvec![1; 8];
let bref: &mut BitSlice = &mut bv;
bref.for_each(|idx, bit| {
    if idx % 2 == 0 {
        !bit
    }
    else {
        bit
    }
});
assert_eq!(&[0b01010101], bref.as_ref());

Trait Implementations

Adds two BitVecs together, zero-extending the shorter.

BitVec addition works just like adding numbers longhand on paper. The first bits in the BitVec are the highest, so addition works from right to left, and the shorter BitVec is assumed to be extended to the left with zero.

The output BitVec may be one bit longer than the longer input, if addition overflowed.

Numeric arithmetic is provided on BitVec as a convenience. Serious numeric computation on variable-length integers should use the num_bigint crate instead, which is written specifically for that use case. BitVecs are not intended for arithmetic, and bitvec makes no guarantees about sustained correctness in arithmetic at this time.

Adds two BitVecs.

Examples
use bitvec::*;
let a = bitvec![0, 1, 0, 1];
let b = bitvec![0, 0, 1, 1];
let s = a + b;
assert_eq!(bitvec![1, 0, 0, 0], s);

This example demonstrates the addition of differently-sized BitVecs, and will overflow.

use bitvec::*;
let a = bitvec![1; 4];
let b = bitvec![1; 1];
let s = b + a;
assert_eq!(bitvec![1, 0, 0, 0, 0], s);
The resulting type after applying the + operator.

Adds another BitVec into self, zero-extending the shorter.

BitVec addition works just like adding numbers longhand on paper. The first bits in the BitVec are the highest, so addition works from right to left, and the shorter BitVec is assumed to be extended to the left with zero.

The output BitVec may be one bit longer than the longer input, if addition overflowed.

Numeric arithmetic is provided on BitVec as a convenience. Serious numeric computation on variable-length integers should use the num_bigint crate instead, which is written specifically for that use case. BitVecs are not intended for arithmetic, and bitvec makes no guarantees about sustained correctness in arithmetic at this time.

Adds another BitVec into self.

Examples
use bitvec::*;
let mut a = bitvec![1, 0, 0, 1];
let b = bitvec![0, 1, 1, 1];
a += b;
assert_eq!(a, bitvec![1, 0, 0, 0, 0]);

Gives write access to all live elements in the underlying storage, including the partially-filled tail.

Accesses the underlying store.

Examples
use bitvec::*;
let mut bv: BitVec = bitvec![0, 0, 0, 0, 0, 0, 0, 0, 1];
for elt in bv.as_mut() {
    *elt += 2;
}
assert_eq!(&[2, 0b1000_0010], bv.as_ref());

Gives read access to all live elements in the underlying storage, including the partially-filled tail.

Accesses the underlying store.

Examples
use bitvec::*;
let bv = bitvec![0, 0, 0, 0, 0, 0, 0, 0, 1];
assert_eq!(&[0, 0b1000_0000], bv.as_ref());

Performs the Boolean AND operation between each element of a BitVec and anything that can provide a stream of bool values (such as another BitVec, or any bool generator of your choice). The BitVec emitted will have the length of the shorter sequence of bits – if one is longer than the other, the extra bits will be ignored.

ANDs a vector and a bitstream, producing a new vector.

Examples
use bitvec::*;
let lhs = bitvec![BigEndian, u8; 0, 1, 0, 1];
let rhs = bitvec![BigEndian, u8; 0, 0, 1, 1];
let and = lhs & rhs;
assert_eq!("0001", &format!("{}", and));
The resulting type after applying the & operator.

Performs the Boolean AND operation in place on a BitVec, using a stream of bool values as the other bit for each operation. If the other stream is shorter than self, self will be truncated when the other stream expires.

ANDs another bitstream into a vector.

Examples
use bitvec::*;
let mut src  = bitvec![BigEndian, u8; 0, 1, 0, 1];
        src &= bitvec![BigEndian, u8; 0, 0, 1, 1];
assert_eq!("0001", &format!("{}", src));

Performs the Boolean OR operation between each element of a BitVec and anything that can provide a stream of bool values (such as another BitVec, or any bool generator of your choice). The BitVec emitted will have the length of the shorter sequence of bits – if one is longer than the other, the extra bits will be ignored.

ORs a vector and a bitstream, producing a new vector.

Examples
use bitvec::*;
let lhs = bitvec![0, 1, 0, 1];
let rhs = bitvec![0, 0, 1, 1];
let or  = lhs | rhs;
assert_eq!("0111", &format!("{}", or));
The resulting type after applying the | operator.

Performs the Boolean OR operation in place on a BitVec, using a stream of bool values as the other bit for each operation. If the other stream is shorter than self, self will be truncated when the other stream expires.

ORs another bitstream into a vector.

Examples
use bitvec::*;
let mut src  = bitvec![0, 1, 0, 1];
        src |= bitvec![0, 0, 1, 1];
assert_eq!("0111", &format!("{}", src));

Performs the Boolean XOR operation between each element of a BitVec and anything that can provide a stream of bool values (such as another BitVec, or any bool generator of your choice). The BitVec emitted will have the length of the shorter sequence of bits – if one is longer than the other, the extra bits will be ignored.

XORs a vector and a bitstream, producing a new vector.

Examples
use bitvec::*;
let lhs = bitvec![0, 1, 0, 1];
let rhs = bitvec![0, 0, 1, 1];
let xor = lhs ^ rhs;
assert_eq!("0110", &format!("{}", xor));
The resulting type after applying the ^ operator.

Performs the Boolean XOR operation in place on a BitVec, using a stream of bool values as the other bit for each operation. If the other stream is shorter than self, self will be truncated when the other stream expires.

XORs another bitstream into a vector.

Examples
use bitvec::*;
let mut src  = bitvec![0, 1, 0, 1];
        src ^= bitvec![0, 0, 1, 1];
assert_eq!("0110", &format!("{}", src));

Signifies that BitSlice is the borrowed form of BitVec.

Borrows the BitVec as a BitSlice.

Examples
use bitvec::*;
use std::borrow::Borrow;
let bv = bitvec![0; 8];
let bref: &BitSlice = bv.borrow();
assert!(!bref.get(7));

Signifies that BitSlice is the borrowed form of BitVec.

Mutably borrows the BitVec as a BitSlice.

Examples
use bitvec::*;
use std::borrow::BorrowMut;
let mut bv = bitvec![0; 8];
let bref: &mut BitSlice = bv.borrow_mut();
assert!(!bref.get(7));
bref.set(7, true);
assert!(bref.get(7));
Returns a copy of the value. Read more
Performs copy-assignment from source. Read more

Prints the BitVec for debugging.

The output is of the form BitVec<C, T> [ELT, *], where <C, T> is the endianness and element type, with square brackets on each end of the bits and all the live elements in the vector printed in binary. The printout is always in semantic order, and may not reflect the underlying store. To see the underlying store, use format!("{:?}", self.as_ref()); instead.

The alternate character {:#?} prints each element on its own line, rather than separated by a space.

Renders the BitVec type header and contents for debug.

Examples
use bitvec::*;
let bv = bitvec![LittleEndian, u16;
    0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1
];
assert_eq!(
    "BitVec<LittleEndian, u16> [0101000011110101]",
    &format!("{:?}", bv)
);
Returns the “default value” for a type. Read more

Reborrows the BitVec as a BitSlice.

This mimics the separation between Vec<T> and [T].

Dereferences &BitVec down to &BitSlice.

Examples
use bitvec::*;
let bv: BitVec = bitvec![1; 4];
let bref: &BitSlice = &bv;
assert!(bref.get(2));
The resulting type after dereferencing.

Mutably reborrows the BitVec as a BitSlice.

This mimics the separation between Vec<T> and [T].

Dereferences &mut BitVec down to &mut BitSlice.

Examples
use bitvec::*;
let mut bv: BitVec = bitvec![0; 6];
let bref: &mut BitSlice = &mut bv;
assert!(!bref.get(5));
bref.set(5, true);
assert!(bref.get(5));

Prints the BitVec for displaying.

This prints each element in turn, formatted in binary in semantic order (so the first bit seen is printed first and the last bit seen printed last). Each element of storage is separated by a space for ease of reading.

The alternate character {:#} prints each element on its own line.

To see the in-memory representation, use AsRef to get access to the raw elements and print that slice instead.

Renders the BitVec contents for display.

Examples
use bitvec::*;
let bv = bitvec![BigEndian, u8; 0, 1, 0, 0, 1, 0, 1, 1, 0, 1];
assert_eq!("01001011 01", &format!("{}", bv));

Readies the underlying storage for Drop.

Restore the interior Vec to sane condition before it drops.

Extends a BitVec with the contents of another bitstream.

At present, this just calls .push() in a loop. When specialization becomes available, it will be able to more intelligently perform bulk moves from the source into self when the source is BitSlice-compatible.

Extends a BitVec from another bitstream.

Examples
use bitvec::*;
let mut bv = bitvec![0; 4];
bv.extend(bitvec![1; 4]);
assert_eq!("00001111", &format!("{}", bv));
🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more

Builds a BitVec out of a borrowed slice of elements.

This copies the memory as-is from the source buffer into the new BitVec. The source buffer will be unchanged by this operation, so you don’t need to worry about using the correct cursor type for the read.

This operation does a copy from the source buffer into a new allocation, as it can only borrow the source and not take ownership.

Builds a BitVec<C: Cursor, T: Bits> from a borrowed &[T].

Examples
use bitvec::*;
let src: &[u8] = &[5, 10];
let bv: BitVec = src.into();
assert_eq!("00000101 00001010", &format!("{}", bv));

Builds a BitVec out of a slice of bool.

This is primarily for the bitvec! macro; it is not recommended for general use.

Converts to this type from the input type.

Copies a BitSlice into an owned BitVec.

The idiomatic BitSlice to BitVec conversion is BitSlice::to_owned, but just as &[T].into() yields a Vec, &BitSlice.into() yields a BitVec.

Converts to this type from the input type.

Changes cursors on a BitVec without mutating the underlying data.

I don’t know why this would be useful at the time of writing, as the From implementations on collections crawl the collection elements in the order requested and so the source and destination storage collections will be bitwise identical, but here’s the option anyway.

If the tail element is partially filled, then this operation will shift the tail element so that the edge of the filled section is on the correct edge of the tail element.

Converts to this type from the input type.

Changes cursors on a BitVec without mutating the underlying data.

I don’t know why this would be useful at the time of writing, as the From implementations on collections crawl the collection elements in the order requested and so the source and destination storage collections will be bitwise identical, but here’s the option anyway.

If the tail element is partially filled, then this operation will shift the tail element so that the edge of the filled section is on the correct edge of the tail element.

Converts to this type from the input type.

Builds a BitVec out of an owned slice of elements.

This moves the memory as-is from the source buffer into the new BitVec. The source buffer will be unchanged by this operation, so you don’t need to worry about using the correct cursor type.

Consumes a Box<[T: Bits]> and creates a BitVec<C: Cursor, T> from it.

Examples
use bitvec::*;
let src: Box<[u8]> = Box::new([3, 6, 9, 12, 15]);
let bv: BitVec = src.into();
assert_eq!("00000011 00000110 00001001 00001100 00001111", &format!("{}", bv));

Builds a BitVec out of a Vec of elements.

This moves the memory as-is from the source buffer into the new BitVec. The source buffer will be unchanged by this operation, so you don’t need to worry about using the correct cursor type.

Consumes a Vec<T: Bits> and creates a BitVec<C: Cursor, T> from it.

Examples
use bitvec::*;
let src: Vec<u8> = vec![1, 2, 4, 8];
let bv: BitVec = src.into();
assert_eq!("00000001 00000010 00000100 00001000", &format!("{}", bv));

Permits the construction of a BitVec by using .collect() on an iterator of bool.

Collects an iterator of bool into a vector.

Examples
use bitvec::*;
use std::iter::repeat;
let bv: BitVec = repeat(true).take(4).chain(repeat(false).take(4)).collect();
assert_eq!("11110000", &format!("{}", bv));

Writes the contents of the BitVec, in semantic bit order, into a hasher.

Writes each bit of the BitVec, as a full bool, into the hasher.

Feeds a slice of this type into the given Hasher. Read more

Gets the bit in a specific element. The element index must be less than or equal to the value returned by elts(), and the bit index must be less than the width of the storage type.

If the BitVec has a partially-filled tail, then the value returned by elts() is a valid index.

The element and bit indices are combined using Bits::join for the storage type.

This index is not recommended for public use.

Indexes into a BitVec using a known element index and a count into that element. The count must not be converted for endianness outside the call.

Examples
use bitvec::*;
let bv = bitvec![BigEndian, u8; 1, 1, 1, 1, 0, 0, 0, 0, 0, 1];
assert!(bv[(1, 1)]); // -----------------------------------^
The returned type after indexing.

Gets the bit at a specific index. The index must be less than the length of the BitVec.

Looks up a single bit by semantic count.

Examples
use bitvec::*;
let bv = bitvec![BigEndian, u8; 0, 0, 0, 0, 0, 0, 0, 0, 1, 0];
assert!(!bv[7]); // ---------------------------------^  |  |
assert!( bv[8]); // ------------------------------------^  |
assert!(!bv[9]); // ---------------------------------------^

If the index is greater than or equal to the length, indexing will panic.

The below test will panic when accessing index 1, as only index 0 is valid.

use bitvec::*;
let mut bv: BitVec = BitVec::new();
bv.push(true);
bv[1];
The returned type after indexing.

Produces an iterator over all the bits in the vector.

This iterator follows the ordering in the vector type, and implements ExactSizeIterator, since BitVecs always know exactly how large they are, and DoubleEndedIterator, since they have known ends.

Iterates over the vector.

Examples
use bitvec::*;
let bv = bitvec![BigEndian, u8; 1, 1, 1, 1, 0, 0, 0, 0];
let mut count = 0;
for bit in bv {
    if bit { count += 1; }
}
assert_eq!(count, 4);
The type of the elements being iterated over.

type IntoIter: Iterator<Item = Self::Item>

Which kind of iterator are we turning this into?

2’s-complement negation of a BitVec.

In 2’s-complement, negation is defined as bit-inversion followed by adding one.

Numeric arithmetic is provided on BitVec as a convenience. Serious numeric computation on variable-length integers should use the num_bigint crate instead, which is written specifically for that use case. BitVecs are not intended for arithmetic, and bitvec makes no guarantees about sustained correctness in arithmetic at this time.

Numerically negates a BitVec using 2’s-complement arithmetic.

Examples
use bitvec::*;
let bv = bitvec![0, 1, 1];
let ne = -bv;
assert_eq!("101", &format!("{}", ne));
The resulting type after applying the - operator.

Flips all bits in the vector.

This invokes the ! operator on each element of the borrowed storage, and so it will also flip bits in the tail that are outside the BitVec length if any. Use ^= repeat(true) to flip only the bits actually inside the BitVec purview. ^= also has the advantage of being a borrowing operator rather than a consuming/returning operator.

Inverts all bits in the vector.

Examples
use bitvec::*;
let bv: BitVec<BigEndian, u32> = BitVec::from(&[0u32] as &[u32]);
let flip = !bv;
assert_eq!(!0u32, flip.as_ref()[0]);
The resulting type after applying the ! operator.
This method returns an Ordering between self and other. Read more
Compares and returns the maximum of two values. Read more
Compares and returns the minimum of two values. Read more
Restrict a value to a certain interval. Read more

Tests if two BitVecs are semantically — not bitwise — equal.

It is valid to compare two vectors of different endianness or element types.

The equality condition requires that they have the same number of stored bits and that each pair of bits in semantic order are identical.

Performs a comparison by ==.

Examples
use bitvec::*;
let l: BitVec<LittleEndian, u16> = bitvec![LittleEndian, u16; 0, 1, 0, 1];
let r: BitVec<BigEndian, u32> = bitvec![BigEndian, u32; 0, 1, 0, 1];
assert!(l == r);

This example uses the same types to prove that raw, bitwise, values are not used for equality comparison.

use bitvec::*;
let l: BitVec<BigEndian, u8> = bitvec![BigEndian, u8; 0, 1, 0, 1];
let r: BitVec<LittleEndian, u8> = bitvec![LittleEndian, u8; 0, 1, 0, 1];

assert_eq!(l, r);
assert_ne!(l.as_ref(), r.as_ref());
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more

Compares two BitVecs by semantic — not bitwise — ordering.

The comparison sorts by testing each index for one vector to have a set bit where the other vector has an unset bit. If the vectors are different, the vector with the set bit sorts greater than the vector with the unset bit.

If one of the vectors is exhausted before they differ, the longer vector is greater.

Performs a comparison by < or >.

Examples
use bitvec::*;
use bitvec::*;
let a = bitvec![0, 1, 0, 0];
let b = bitvec![0, 1, 0, 1];
let c = bitvec![0, 1, 0, 1, 1];
assert!(a < b);
assert!(b < c);
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Shifts all bits in the vector to the left – DOWN AND TOWARDS THE FRONT.

On primitives, the left-shift operator << moves bits away from origin and towards the ceiling. This is because we label the bits in a primitive with the minimum on the right and the maximum on the left, which is big-endian bit order. This increases the value of the primitive being shifted.

THAT IS NOT HOW BITVEC WORKS!

BitVec defines its layout with the minimum on the left and the maximum on the right! Thus, left-shifting moves bits towards the minimum.

In BigEndian order, the effect in memory will be what you expect the << operator to do.

In LittleEndian order, the effect will be equivalent to using >> on the primitives in memory!

Notes

In order to preserve the effects in memory that this operator traditionally expects, the bits that are emptied by this operation are zeroed rather than left to their old value.

The length of the vector is decreased by the shift amount.

If the shift amount is greater than the length, the vector calls clear() and zeroes its memory. This is not an error.

Shifts a BitVec to the left, shortening it.

Examples
use bitvec::*;
let bv = bitvec![BigEndian, u8; 0, 0, 0, 1, 1, 1];
assert_eq!("000111", &format!("{}", bv));
assert_eq!(0b0001_1100, bv.as_ref()[0]);
assert_eq!(bv.len(), 6);
let ls = bv << 2usize;
assert_eq!("0111", &format!("{}", ls));
assert_eq!(0b0111_0000, ls.as_ref()[0]);
assert_eq!(ls.len(), 4);
The resulting type after applying the << operator.

Shifts all bits in the vector to the left – DOWN AND TOWARDS THE FRONT.

On primitives, the left-shift operator << moves bits away from origin and towards the ceiling. This is because we label the bits in a primitive with the minimum on the right and the maximum on the left, which is big-endian bit order. This increases the value of the primitive being shifted.

THAT IS NOT HOW BITVEC WORKS!

BitVec defines its layout with the minimum on the left and the maximum on the right! Thus, left-shifting moves bits towards the minimum.

In BigEndian order, the effect in memory will be what you expect the << operator to do.

In LittleEndian order, the effect will be equivalent to using >> on the primitives in memory!

Notes

In order to preserve the effects in memory that this operator traditionally expects, the bits that are emptied by this operation are zeroed rather than left to their old value.

The length of the vector is decreased by the shift amount.

If the shift amount is greater than the length, the vector calls clear() and zeroes its memory. This is not an error.

Shifts a BitVec to the left in place, shortening it.

Examples
use bitvec::*;
let mut bv = bitvec![LittleEndian, u8; 0, 0, 0, 1, 1, 1];
assert_eq!("000111", &format!("{}", bv));
assert_eq!(0b0011_1000, bv.as_ref()[0]);
assert_eq!(bv.len(), 6);
bv <<= 2;
assert_eq!("0111", &format!("{}", bv));
assert_eq!(0b0000_1110, bv.as_ref()[0]);
assert_eq!(bv.len(), 4);

Shifts all bits in the vector to the right – UP AND TOWARDS THE BACK.

On primitives, the right-shift operator >> moves bits towards the origin and away from the ceiling. This is because we label the bits in a primitive with the minimum on the right and the maximum on the left, which is big-endian bit order. This decreases the value of the primitive being shifted.

THAT IS NOT HOW BITVEC WORKS!

BitVec defines its layout with the minimum on the left and the maximum on the right! Thus, right-shifting moves bits towards the maximum.

In BigEndian order, the effect in memory will be what you expect the >> operator to do.

In LittleEndian order, the effect will be equivalent to using << on the primitives in memory!

Notes

In order to preserve the effects in memory that this operator traditionally expects, the bits that are emptied by this operation are zeroed rather than left to their old value.

The length of the vector is increased by the shift amount.

If the new length of the vector would overflow, a panic occurs. This is an error.

Shifts a BitVec to the right, lengthening it and filling the front with 0.

Examples
use bitvec::*;
let bv = bitvec![BigEndian, u8; 0, 0, 0, 1, 1, 1];
assert_eq!("000111", &format!("{}", bv));
assert_eq!(0b0001_1100, bv.as_ref()[0]);
assert_eq!(bv.len(), 6);
let rs = bv >> 2usize;
assert_eq!("00000111", &format!("{}", rs));
assert_eq!(0b0000_0111, rs.as_ref()[0]);
assert_eq!(rs.len(), 8);
The resulting type after applying the >> operator.

Shifts all bits in the vector to the right – UP AND TOWARDS THE BACK.

On primitives, the right-shift operator >> moves bits towards the origin and away from the ceiling. This is because we label the bits in a primitive with the minimum on the right and the maximum on the left, which is big-endian bit order. This decreases the value of the primitive being shifted.

THAT IS NOT HOW BITVEC WORKS!

BitVec defines its layout with the minimum on the left and the maximum on the right! Thus, right-shifting moves bits towards the maximum.

In BigEndian order, the effect in memory will be what you expect the >> operator to do.

In LittleEndian order, the effect will be equivalent to using << on the primitives in memory!

Notes

In order to preserve the effects in memory that this operator traditionally expects, the bits that are emptied by this operation are zeroed rather than left to their old value.

The length of the vector is increased by the shift amount.

If the new length of the vector would overflow, a panic occurs. This is an error.

Shifts a BitVec to the right in place, lengthening it and filling the front with 0.

Examples
use bitvec::*;
let mut bv = bitvec![LittleEndian, u8; 0, 0, 0, 1, 1, 1];
assert_eq!("000111", &format!("{}", bv));
assert_eq!(0b0011_1000, bv.as_ref()[0]);
assert_eq!(bv.len(), 6);
bv >>= 2;
assert_eq!("00000111", &format!("{}", bv));
assert_eq!(0b1110_0000, bv.as_ref()[0]);
assert_eq!(bv.len(), 8);

Subtracts one BitVec from another assuming 2’s-complement encoding.

Subtraction is a more complex operation than addition. The bit-level work is largely the same, but semantic distinctions must be made. Unlike addition, which is commutative and tolerant of switching the order of the addends, subtraction cannot swap the minuend (LHS) and subtrahend (RHS).

Because of the properties of 2’s-complement arithmetic, M - S is equivalent to M + (!S + 1). Subtraction therefore bitflips the subtrahend and adds one. This may, in a degenerate case, cause the subtrahend to increase in length.

Once the subtrahend is stable, the minuend zero-extends its left side in order to match the length of the subtrahend if needed (this is provided by the >> operator).

When the minuend is stable, the minuend and subtrahend are added together by the <BitVec as Add> implementation. The output will be encoded in 2’s-complement, so a leading one means that the output is considered negative.

Interpreting the contents of a BitVec as an integer is beyond the scope of this crate.

Numeric arithmetic is provided on BitVec as a convenience. Serious numeric computation on variable-length integers should use the num_bigint crate instead, which is written specifically for that use case. BitVecs are not intended for arithmetic, and bitvec makes no guarantees about sustained correctness in arithmetic at this time.

Subtracts one BitVec from another.

Examples

Minuend larger than subtrahend, positive difference.

use bitvec::*;
let a = bitvec![1, 0];
let b = bitvec![   1];
let c = a - b;
assert_eq!(bitvec![0, 1], c);

Minuend smaller than subtrahend, negative difference.

use bitvec::*;
let a = bitvec![   1];
let b = bitvec![1, 0];
let c = a - b;
assert_eq!(bitvec![1, 1], c);

Subtraction from self is correctly handled.

use bitvec::*;
let a = bitvec![1; 4];
let b = a.clone();
let c = a - b;
assert!(c.not_any(), "{:?}", c);
The resulting type after applying the - operator.

Subtracts another BitVec from self, assuming 2’s-complement encoding.

The minuend is zero-extended, or the subtrahend sign-extended, as needed to ensure that the vectors are the same width before subtraction occurs.

The Sub trait has more documentation on the subtraction process.

Numeric arithmetic is provided on BitVec as a convenience. Serious numeric computation on variable-length integers should use the num_bigint crate instead, which is written specifically for that use case. BitVecs are not intended for arithmetic, and bitvec makes no guarantees about sustained correctness in arithmetic at this time.

Subtracts another BitVec from self.

Examples
use bitvec::*;
let a = bitvec![0, 0, 0, 1];
let b = bitvec![0, 0, 0, 0];
let c = a - b;
assert_eq!(c, bitvec![0, 0, 0, 1]);

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.