[][src]Struct bitvec::vec::BitVec

#[repr(C)]
pub struct BitVec<C = BigEndian, T = u8> where
    C: Cursor,
    T: BitStore
{ /* fields omitted */ }

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.

Examples

use bitvec::prelude::*;

let mut bv: BitVec = BitVec::new();
bv.push(false);
bv.push(true);

assert_eq!(bv.len(), 2);
assert_eq!(bv[0], false);

assert_eq!(bv.pop(), Some(true));
assert_eq!(bv.len(), 1);

bv.set(0, true);
assert_eq!(bv[0], true);

bv.extend([0u8, 1, 0].iter().map(|n| *n != 0u8));
for bit in &*bv {
  println!("{}", bit);
}
assert_eq!(bv, bitvec![1, 0, 1, 0]);

The bitvec! macro is provided to make initialization more convenient.

use bitvec::prelude::*;

let mut bv = bitvec![0, 1, 2, 3];
bv.push(false);
assert_eq!(bv, bitvec![0, 1, 1, 1, 0]);

It can also initialize each element of a BitVec<_, T> with a given value. This may be more efficient than performing allocation and initialization in separate steps, especially when initializing a vector of zeros:

use bitvec::prelude::*;

let bv = bitvec![0; 15];
assert_eq!(bv, bitvec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);

// The following is equivalent, but potentially slower:
let mut bv1: BitVec = BitVec::with_capacity(15);
bv1.resize(15, false);

Use a BitVec<T> as an efficient stack:

use bitvec::prelude::*;
let mut stack: BitVec = BitVec::new();

stack.push(false);
stack.push(true);
stack.push(true);

while let Some(top) = stack.pop() {
  //  Prints true, true, false
  println!("{}", top);
}

Indexing

The BitVec type allows you to access values by index, because it implements the Index trait. An example will be more explicit:

use bitvec::prelude::*;

let bv = bitvec![0, 0, 1, 1];
println!("{}", bv[1]); // it will display 'false'

However, be careful: if you try to access an index which isn’t in the BitVec, your software will panic! You cannot do this:

use bitvec::prelude::*;

let bv = bitvec![0, 1, 0, 1];
println!("{}", bv[6]); // it will panic!

In conclusion: always check if the index you want to get really exists before doing it.

Slicing

A BitVec is growable. A BitSlice, on the other hand, is fixed size. To get a bit slice, use &. Example:

use bitvec::prelude::*;
fn read_bitslice(slice: &BitSlice) {
	// use slice
}

let bv = bitvec![0, 1];
read_bitslice(&bv);

// … and that’s all!
// you can also do it like this:
let bs : &BitSlice = &bv;

In Rust, it’s more common to pass slices as arguments rather than vectors when you do not want to grow or shrink it. The same goes for Vec and [&[]], and String and &str.

Capacity and Reallocation

The capacity of a bit vector is the amount of space allocated for any future bits that will be added onto the vector. This is not to be confused with the length of a vector, which specifies the number of live, useful bits within the vector. If a vector’s length exceeds its capacity, its capacity will automatically be increased, but its storage elements will have to be reallocated.

For example, a bit vector with capacity 10 and length 0 would be an allocated, but uninhabited, vector, with space for ten more bits. Pushing ten or fewer bits onto the vector will not change its capacity or cause reallocation to occur. However, if the vector’s length is increased to eleven, it will have to reallocate, which can be slow. For this reason, it is recommended to use BitVec::with_capacity whenever possible to specify how big the bit vector is expected to get.

Guarantees

Due to its incredibly fundamental nature, BitVec makes a lot of guarantees about its design. This ensures that it is as low-overhead as possible in the general case, and can be correctly manipulated in fundamental ways by unsafe code.

Most fundamentally, BitVec is and always will be a ([BitPtr], capacity) doublet. No more, no less. The order of these fields is unspecified, and you should only interact with the members through the provided APIs. Note that BitPtr is not directly manipulable, and must never be written or interpreted as anything but opaque binary data by user code.

When a BitVec has allocated memory, then the memory to which it points is on the heap (as defined by the allocator Rust is configured to use by default), and its pointer points to len initialized bits in order of the Cursor type parameter, followed by capacity - len logically uninitialized bits.

BitVec will never perform a “small optimization” where elements are stored in its handle representation, for two reasons:

  • It would make it more difficult for user code to correctly manipulate a BitVec. The contents of the BitVec would not have a stable address if the handle were moved, and it would be more difficult to determine if a BitVec had allocated memory.

  • It would penalize the general, heap-allocated, case by incurring a branch on every access.

BitVec will never automatically shrink itself, even if it is emptied. This ensures that no unnecessary allocations or deallocations occur. Emptying a BitVec and then refilling it to the same length will incur no calls to the allocator. If you wish to free up unused memory, use shrink_to_fit.

Erasure

BitVec will not specifically overwrite any data that is removed from it, nor will it specifically preserve it. Its uninitialized memory is scratch space that may be used however the implementation desires, and must not be relied upon as stable. Do not rely on removed data to be erased for security purposes. Even if you drop a BitVec, its buffer may simply be reused for other data structures in your program. Even if you zero a BitVec’s memory first, that may not actually occur if the optimizer does not consider this an observable side effect. There is one case that will never break, however: using unsafe to construct a [T] slice over the BitVec’s capacity, and writing to the excess space, then increasing the length to match, is always valid.

Type Parameters

  • C: Cursor: An implementor of the Cursor trait. This type is used to convert semantic indices into concrete bit positions in elements, and store or retrieve bit values from the storage type.
  • T: BitStore: An implementor of the BitStore trait: u8, u16, u32, or u64 (64-bit systems only). This is the actual type in memory that the vector will use to store data.

Safety

The BitVec handle has the same size as standard Rust Vec handles, but it is extremely binary incompatible with them. Attempting to treat BitVec<_, T> as Vec<T> in any manner except through the provided APIs is catastrophically unsafe and unsound.

[&[]]: https://doc.rust-lang.org/stable/std/primitive.slice.html

Methods

impl<C, T> BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

pub fn new() -> Self[src]

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

The vector does not allocate until bits are written into it.

Returns

An empty, unallocated, BitVec handle.

Examples

use bitvec::prelude::*;

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

pub fn with_capacity(capacity: usize) -> Self[src]

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

The new vector will be able to hold at least capacity elements before it reallocates. If capacity is 0, it will not allocate.

Parameters

  • capacity: The minimum number of bits that the new vector will need to be able to hold.

Returns

An empty vector with at least the given capacity.

Examples

use bitvec::prelude::*;

let bv: BitVec = BitVec::with_capacity(10);
assert!(bv.is_empty());
assert!(bv.capacity() >= 10);

pub fn from_element(elt: T) -> Self[src]

Constructs a BitVec from a single element.

The produced BitVec will span the element, and include all bits in it.

Parameters

  • elt: The source element.

Returns

A BitVec over the provided element.

Examples

use bitvec::prelude::*;

let bv = BitVec::<BigEndian, u8>::from_element(5);
assert_eq!(bv.count_ones(), 2);

pub fn from_slice(slice: &[T]) -> Self[src]

Constructs a BitVec from a slice of elements.

The produced BitVec will span the provided slice.

Parameters

  • slice: The source elements to copy into the new BitVec.

Returns

A BitVec set to the provided slice values.

Examples

use bitvec::prelude::*;

let src = [5, 10];
let bv = BitVec::<BigEndian, u8>::from_slice(&src[..]);
assert!(bv[5]);
assert!(bv[7]);
assert!(bv[12]);
assert!(bv[14]);

pub fn from_vec(vec: Vec<T>) -> Self[src]

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

Parameters

  • vec: The source vector whose memory will be used.

Returns

A new BitVec using the vec Vec’s memory.

Panics

Panics if the source vector would cause the BitVec to overflow capacity.

Examples

use bitvec::prelude::*;

let bv = BitVec::<BigEndian, u8>::from_vec(vec![1, 2, 4, 8]);
assert_eq!(
  "[00000001, 00000010, 00000100, 00001000]",
  &format!("{}", bv),
);

pub fn from_bitslice(slice: &BitSlice<C, T>) -> Self[src]

Clones a &BitSlice into a BitVec.

Parameters

  • slice

Returns

A BitVec containing the same bits as the source slice.

Examples

use bitvec::prelude::*;

let bs = [0u8, !0].as_bitslice::<BigEndian>();
let bv = BitVec::from_bitslice(bs);
assert_eq!(bv.len(), 16);
assert!(bv.some());

pub fn from_boxed_bitslice(slice: BitBox<C, T>) -> Self[src]

Converts a frozen BitBox allocation into a growable BitVec.

This does not copy or reallocate.

Parameters

  • slice: A BitBox to be thawed.

Returns

A growable collection over the original memory of the slice.

Examples

use bitvec::prelude::*;

let bv = BitVec::from_boxed_bitslice(bitbox![0, 1]);
assert_eq!(bv.len(), 2);
assert!(bv.some());

pub unsafe fn from_raw_parts(pointer: BitPtr<T>, capacity: usize) -> Self[src]

Creates a new BitVec<C, T> directly from the raw parts of another.

Parameters

  • pointer: The BitPtr<T> to use.
  • capacity: The number of T elements allocated in that slab.

Returns

A BitVec over the given slab of memory.

Safety

This is highly unsafe, due to the number of invariants that aren’t checked:

  • pointer needs to have been previously allocated by some allocating type.
  • pointer’s T needs to have the same size and alignment as it was initially allocated.
  • pointer’s element count needs to be less than or equal to the original allocation capacity.
  • capacity needs to be the original allocation capacity for the vector. This is not the value produced by .capacity().

Violating these will cause problems, like corrupting the handle’s concept of memory, the allocator’s internal data structures, and the sanity of your program. It is absolutely not safe to construct a BitVec whose T differs from the type used for the initial allocation.

The ownership of pointer is effectively transferred to the BitVec<C, T> which may then deallocate, reallocate, or modify the contents of the referent slice at will. Ensure that nothing else uses the pointer after calling this function.

pub fn capacity(&self) -> usize[src]

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

Parameters

  • &self

Returns

The number of bits that the vector can hold before reallocating.

Examples

use bitvec::prelude::*;

let bv: BitVec = BitVec::with_capacity(10);
assert!(bv.is_empty());
assert!(bv.capacity() >= 10);

pub fn reserve(&mut self, additional: usize)[src]

Reserves capacity for at least additional more bits to be inserted.

The collection may reserve more space to avoid frequent reallocations. After calling reserve, capacity will be greater than or equal to self.len() + additional. Does nothing if the capacity is already sufficient.

Parameters

  • &mut self
  • additional: The number of extra bits to be granted space.

Panics

Panics if the new capacity would overflow the vector’s limits.

Examples

use bitvec::prelude::*;

let mut bv = bitvec![1; 5];
assert!(bv.capacity() >= 5);
bv.reserve(10);
assert!(bv.capacity() >= 15);

pub fn reserve_exact(&mut self, additional: usize)[src]

Reserves the minimum capacity for at least additional more bits.

After calling reserve_exact, the capacity will be greater than or equal to self.len() + additional. Does nothing if the capacity is already sufficient.

Note that the allocator may give the collection more space than it requests. Therefore, the capacity cannot be relied upon to be precisely minimal. Prefer reserve if future insertions are expected.

Parameters

  • &mut self
  • additional: The number of extra bits to be granted space.

Panics

Panics if the new capacity would overflow the vector’s limits.

Examples

use bitvec::prelude::*;

let mut bv = bitvec![1; 5];
assert!(bv.capacity() >= 5);
bv.reserve_exact(10);
assert!(bv.capacity() >= 15);

pub fn shrink_to_fit(&mut self)[src]

Shrinks the capacity of the vector as much as possible.

It will drop down as close as possible to the length, but the allocator may still inform the vector that there is space for bits.

This does not modify the contents of the memory store! It will not zero any memory that had been used and then removed from the vector’s live count.

Parameters

  • &mut self

Examples

use bitvec::prelude::*;

let mut bv = bitvec![1; 100];
let cap = bv.capacity();
bv.truncate(10);
bv.shrink_to_fit();
assert!(bv.capacity() <= cap);

pub fn truncate(&mut self, len: usize)[src]

Shortens the vector, keeping the first len bits and dropping the rest.

If len is greater than the vector’s current length, this has no effect.

Parameters

  • &mut self
  • len: The new length of the vector.

Examples

use bitvec::prelude::*;

let mut bv = bitvec![1; 15];
bv.truncate(10);
assert_eq!(bv.len(), 10);

bv.truncate(15);
assert_eq!(bv.len(), 10);

pub fn as_bitslice(&self) -> &BitSlice<C, T>[src]

Produces a BitSlice containing the entire vector.

Equivalent to &s[..].

Parameters

  • &self

Returns

A BitSlice over the vector.

Examples

use bitvec::prelude::*;

let bv = bitvec![0, 1, 1, 0];
let bs = bv.as_bitslice();

pub fn as_mut_bitslice(&mut self) -> &mut BitSlice<C, T>[src]

Produces a mutable BitSlice containing the entire vector.

Equivalent to &mut s[..].

Parameters

  • &mut self

Returns

A mutable BitSlice over the vector.

Examples

use bitvec::prelude::*;

let mut bv = bitvec![0, 1, 1, 0];
let bs = bv.as_mut_bitslice();

pub unsafe fn set_len(&mut self, len: usize)[src]

Sets the length of the vector.

This unconditionally sets the size of the vector, without modifying its contents. It is up to the caller to ensure that the vector’s buffer can hold the new size.

Parameters

  • &mut self
  • len: The new length of the vector. This must be less than the maximum number of bits that the vector can hold.

Panics

This panics if len overflows the vector's intrinsic or allocated capacities.

Safety

The caller must ensure that the new length is sound for the vector.

Examples

use bitvec::prelude::*;

let mut bv: BitVec = BitVec::with_capacity(15);
assert!(bv.is_empty());
unsafe { bv.set_len(10) };
assert_eq!(bv.len(), 10);

pub fn swap_remove(&mut self, index: usize) -> bool[src]

Removes a bit from the vector and returns it.

The removed bit is replaced by the last bit in the vector.

Parameters

  • &mut self
  • index: The index whose bit is to be returned, and replaced by the tail.

Returns

The bit at the requested index.

Panics

Panics if the index is out of bounds.

Examples

use bitvec::prelude::*;

let mut bv = bitvec![0, 0, 0, 0, 1];
assert!(!bv[2]);
assert_eq!(bv.len(), 5);
assert!(!bv.swap_remove(2));
assert!(bv[2]);
assert_eq!(bv.len(), 4);

pub fn insert(&mut self, index: usize, value: bool)[src]

Inserts a bit at a position, shifting all bits after it to the right.

Note that this is O(n) runtime.

Parameters

  • &mut self
  • index: The position at which to insert. This may be any value from 0 up to and including self.len(). At self.len(), it is equivalent to calling self.push(value).
  • value: The bit to be inserted.

Panics

Panics if index is greater than the length.

Examples

use bitvec::prelude::*;

let mut bv = bitvec![0, 0, 0, 0];
bv.insert(2, true);
assert_eq!(bv, bitvec![0, 0, 1, 0, 0]);
bv.insert(5, true);
assert_eq!(bv, bitvec![0, 0, 1, 0, 0, 1]);

pub fn remove(&mut self, index: usize) -> bool[src]

Removes and returns the bit at position index, shifting all bits after it to the left.

Parameters

  • &mut self
  • index: The position whose bit is to be removed. This must be in the domain 0 .. self.len().

Returns

The bit at the requested index.

Panics

Panics if index is out of bounds for the vector.

Examples

use bitvec::prelude::*;

let mut bv = bitvec![0, 0, 1, 0, 0];
assert!(bv.remove(2));
assert_eq!(bv, bitvec![0, 0, 0, 0]);

pub fn retain<F>(&mut self, pred: F) where
    F: FnMut(usize, bool) -> bool
[src]

Retains only the bits that pass the predicate.

This removes all bits b where f(e) returns false. This method operates in place and preserves the order of the retained bits. Because it is in-place, it operates in O(n²) time.

Parameters

  • &mut self
  • pred: The testing predicate for each bit.

Type Parameters

  • F: FnMut(usize, bool) -> bool: A function that can be invoked on each bit, returning whether the bit should be kept or not. Receives the index (following BitSlice::for_each) to provide additional context to determine whether the entry satisfies the condition.

Examples

use bitvec::prelude::*;

let mut bv = bitvec![0, 1, 0, 1, 0, 1];
bv.retain(|_, b| b);
assert_eq!(bv, bitvec![1, 1, 1]);

pub fn push(&mut self, value: bool)[src]

Appends a bit to the back of the vector.

If the vector is at capacity, this may cause a reallocation.

Parameters

  • &mut self
  • value: The bit value to append.

Panics

This will panic if the push will cause the vector to allocate above BitPtr<T> or machine capacity.

Examples

use bitvec::prelude::*;

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

pub fn pop(&mut self) -> Option<bool>[src]

Removes the last bit from the collection, if present.

Parameters

  • &mut self

Returns

If the vector is not empty, this returns the last bit; if it is empty, this returns None.

Examples

use bitvec::prelude::*;

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());

pub fn append<D, U>(&mut self, other: &mut BitVec<D, U>) where
    D: Cursor,
    U: BitStore
[src]

Moves all the elements of other into self, leaving other empty.

Parameters

  • &mut self
  • other: A BitVec of any order and storage type. Its bits are appended to self.

Panics

Panics if the joined vector is too large.

Examples

use bitvec::prelude::*;

let mut bv1 = bitvec![0; 10];
let mut bv2 = bitvec![1; 10];
bv1.append(&mut bv2);
assert_eq!(bv1.len(), 20);
assert!(bv1[10]);
assert!(bv2.is_empty());

Important traits for Drain<'a, C, T>
pub fn drain<R>(&mut self, range: R) -> Drain<C, T> where
    R: RangeBounds<usize>, 
[src]

Creates a draining iterator that removes the specified range from the vector and yields the removed bits.

Notes

  1. The element range is removed, regardless of whether the iterator is consumed.
  2. The amount of items removed from the vector if the draining iterator is leaked, is left unspecified.

Parameters

  • &mut self
  • range: any range literal, which is used to define the range of the vector that is drained.

Returns

An iterator over the specified range.

Panics

Panics if the range is ill-formed, or if it is beyond the vector bounds.

Examples

use bitvec::prelude::*;

let mut bv = bitvec![0, 0, 1, 1, 1, 0, 0];
assert_eq!(bv.len(), 7);
for bit in bv.drain(2 .. 5) {
  assert!(bit);
}
assert!(bv.not_any());
assert_eq!(bv.len(), 4);

pub fn clear(&mut self)[src]

Clears the vector, removing all values.

Note that this method has no effect on the allocated capacity of the vector.

Parameters

  • &mut self

Effects

Becomes an uninhabited slice.

Examples

use bitvec::prelude::*;

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

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

pub fn split_off(&mut self, at: usize) -> Self[src]

Splits the collection into two at the given index.

Returns a newly allocated Self. self contains elements [0, at), and the returned Self contains elements [at, self.len()).

Note that the capacity of self does not change.

Parameters

  • &mut self
  • at: The index at which to perform the split. This must be in the domain 0 ..= self.len(). When it is self.len(), an empty vector is returned.

Returns

A new BitVec containing all the elements from at onwards.

Panics

Panics if at is beyond self.len().

Examples

use bitvec::prelude::*;

let mut bv1 = bitvec![0, 0, 0, 1, 1, 1];
let bv2 = bv1.split_off(3);
assert_eq!(bv1, bitvec![0, 0, 0]);
assert_eq!(bv2, bitvec![1, 1, 1]);

pub fn resize(&mut self, new_len: usize, value: bool)[src]

Resizes the BitVec in place so that len is equal to new_len.

If new_len is greater than len, then the vector is extended by the difference, and filled with the provided value. If new_len is less than len, then the vector is just truncated.

Parameters

  • &mut self
  • new_len: The new length of the vector.
  • value: The fill value if the vector is to be extended.

Examples

use bitvec::prelude::*;

let mut bv = bitvec![0; 4];
bv.resize(8, true);
assert_eq!(bv, bitvec![0, 0, 0, 0, 1, 1, 1, 1]);
bv.resize(5, false);
assert_eq!(bv, bitvec![0, 0, 0, 0, 1]);

Important traits for Splice<'a, C, T, I>
pub fn splice<R, I>(
    &mut self,
    range: R,
    replacement: I
) -> Splice<C, T, <I as IntoIterator>::IntoIter> where
    R: RangeBounds<usize>,
    I: IntoIterator<Item = bool>, 
[src]

Creates a splicing iterator that exchanges the specified range for the replacement iterator, yielding the removed items. The range and its replacement do not need to be the same size.

Notes

  1. The element range is removed and replaced even if the iterator produced by this method is not fully consumed.
  2. It is unspecified how many bits are removed from the BitVec if the returned iterator is leaked.
  3. The input iterator replacement is only consumed when the returned iterator is dropped.
  4. This is optimal if:
    • the tail (elements in the BitVec after range) is empty,
    • replace_with yields fewer characters than range’s length,
    • the lower bound of replacement.size_hint() is exact.

Parameters

  • &mut self
  • range: A range of indices in the BitVec to pull out of the collection.
  • replacement: Something which can be used to provide new bits to replace the removed range.

The entirety of replacement will be inserted into the slot marked by range. If replacement is an infinite iterator, then this will hang, and crash your program.

Returns

An iterator over the bits marked by range.

Panics

Panics if the range is ill-formed, or extends past the end of the BitVec.

Examples

This example starts with six bits of zero, and then splices out bits 2 and 3 and replaces them with four bits of one.

use bitvec::prelude::*;

let mut bv = bitvec![0; 6];
let bv2 = bitvec![1; 4];

let s = bv.splice(2 .. 4, bv2).collect::<BitVec>();
assert_eq!(s.len(), 2);
assert!(!s[0]);
assert_eq!(bv, bitvec![0, 0, 1, 1, 1, 1, 0, 0]);

pub fn set_elements(&mut self, element: T)[src]

Sets the backing storage to the provided element.

This unconditionally sets each allocated element in the backing storage to the provided value, without altering the BitVec length or capacity. It operates on the underlying Vec’s memory region directly, and will ignore the BitVec’s cursors.

This has the unobservable effect of setting the allocated, but dead, bits beyond the end of the vector’s length, up to its capacity.

Parameters

  • &mut self
  • element: The value to which each allocated element in the backing store will be set.

Examples

use bitvec::prelude::*;

let mut bv = bitvec![0; 10];
assert_eq!(bv.as_slice(), &[0, 0]);
bv.set_elements(0xA5);
assert_eq!(bv.as_slice(), &[0xA5, 0xA5]);

pub fn add_reverse<I>(self, addend: I) -> Self where
    I: IntoIterator<Item = bool>, 
[src]

Performs “reverse” addition (left to right instead of right to left).

This addition traverses the addends from left to right, performing the addition at each index and writing the sum into self.

If addend expires before self does, addend is zero-extended and the carry propagates through the rest of self. If self expires before addend, then self is zero-extended and the carry propagates through the rest of addend, growing self until addend expires.

An infinite addend will cause unbounded memory growth until the vector overflows and panics.

Parameters

  • self
  • addend: impl IntoIterator<Item=bool>: A stream of bits to add into self, from left to right.

Returns

The sum vector of self and addend.

Examples

use bitvec::prelude::*;

let a = bitvec![0, 1, 0, 1];
let b = bitvec![0, 0, 1, 1];
let c = a.add_reverse(b);
assert_eq!(c, bitvec![0, 1, 1, 0, 1]);

pub fn add_assign_reverse<I>(&mut self, addend: I) where
    I: IntoIterator<Item = bool>, 
[src]

Performs “reverse” addition (left to right instead of right to left).

This addition traverses the addends from left to right, performing the addition at each index and writing the sum into self.

If addend expires before self does, addend is zero-extended and the carry propagates through the rest of self. If self expires before addend, then self is zero-extended and the carry propagates through the rest of addend, growing self until addend expires.

An infinite addend will cause unbounded memory growth until the vector overflows and panics.

Parameters

  • &mut self
  • addend: impl IntoIterator<Item=bool>: A stream of bits to add into self, from left to right.

Effects

self may grow as a result of the final carry-out bit being 1 and pushed onto the right end.

Examples

use bitvec::prelude::*;

let mut a = bitvec![0, 1, 0, 1];
let     b = bitvec![0, 0, 1, 1];
a.add_assign_reverse(&b);
assert_eq!(a, bitvec![0, 1, 1, 0, 1]);

Important traits for BitVec<C, T>
pub fn change_cursor<D>(self) -> BitVec<D, T> where
    D: Cursor
[src]

Changes the cursor type on the vector handle, without changing its contents.

Parameters

  • self

Returns

An equivalent vector handle with a new cursor type. The contents of the backing storage are unchanged.

To reorder the bits in memory, drain this vector into a new handle with the desired cursor type.

pub fn into_boxed_bitslice(self) -> BitBox<C, T>[src]

Degrades a BitVec to a BitBox, freezing its size.

Parameters

  • self

Returns

Itself, with its size frozen and ungrowable.

pub fn into_boxed_slice(self) -> Box<[T]>[src]

Degrades a BitVec to a standard boxed slice.

Parameters

  • self

Returns

A boxed slice of the data the BitVec had owned.

pub fn into_vec(self) -> Vec<T>[src]

Degrades a BitVec to a standard Vec.

Parameters

  • self

Returns

The plain vector underlying the BitVec.

pub fn bitptr(&self) -> BitPtr<T>[src]

Gets the raw BitPtr powering the vector.

Parameters

  • &self

Returns

The underlying BitPtr for the vector.

Notes

The BitPtr<T> return type is opaque, and not exported by the crate. Users are not able to use it in any way except to construct another BitVec<_, T> from it. It is not possible for user code to even express the name of the type.

use bitvec::prelude::*;
use std::mem;

let bv = bitvec![1; 10];
let bitptr = bv.bitptr();
let cap = bv.capacity();
mem::forget(bv);
let bv2 = unsafe {
  BitVec::<BigEndian, _>::from_raw_parts(bitptr, cap)
};
assert_eq!(bv2.len(), 10);
assert!(bv2[9]);

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

pub fn len(&self) -> usize[src]

Returns the number of bits contained in the BitSlice.

Parameters

  • &self

Returns

The number of live bits in the slice domain.

Examples

use bitvec::prelude::*;

let store = 0u8;
let bs = store.as_bitslice::<BigEndian>();
assert_eq!(bs.len(), 8);

pub fn is_empty(&self) -> bool[src]

Tests if the slice is empty.

Parameters

  • &self

Returns

Whether the slice has no live bits.

Examples

use bitvec::prelude::*;

let bs = BitSlice::<BigEndian, u8>::empty();
assert!(bs.is_empty());
let bs = 0u8.as_bitslice::<BigEndian>();
assert!(!bs.is_empty());

pub fn first(&self) -> Option<bool>[src]

Gets the first element of the slice, if present.

Parameters

  • &self

Returns

None if the slice is empty, or Some(bit) if it is not.

Examples

use bitvec::prelude::*;

assert!(BitSlice::<BigEndian, u8>::empty().first().is_none());
assert!(128u8.as_bitslice::<BigEndian>().first().unwrap());

pub fn split_first(&self) -> Option<(bool, &Self)>[src]

Returns the first and all the rest of the bits of the slice, or None if it is empty.

Parameters

  • &self

Returns

If the slice is empty, this returns None, otherwise, it returns Some of:

  • the first bit
  • a &BitSlice of all the rest of the bits (this may be empty)

Examples

use bitvec::prelude::*;

assert!(BitSlice::<BigEndian, u8>::empty().split_first().is_none());

let store = 128u8;
let bits = store.as_bitslice::<BigEndian>();
let (h, t) = bits.split_first().unwrap();
assert!(h);
assert!(t.not_any());

let (h, t) = bits[0 .. 1].split_first().unwrap();
assert!(h);
assert!(t.is_empty());

pub fn split_first_mut(&mut self) -> Option<(bool, &mut Self)>[src]

Returns the first and all the rest of the bits of the slice, or None if it is empty.

Parameters

  • &self

Returns

If the slice is empty, this returns None, otherwise, it returns Some of:

  • the first bit
  • a &mut BitSlice of all the rest of the bits (this may be empty)

Examples

use bitvec::prelude::*;

let mut store = 0u8;
let bits = store.as_mut_bitslice::<LittleEndian>();
assert!(!bits[0]);
*bits.at(0) = true;
let (h, t) = bits.split_first_mut().unwrap();
assert!(h);
assert_eq!(t.len(), 7);

pub fn split_last(&self) -> Option<(bool, &Self)>[src]

Returns the last and all the rest of the bits in the slice, or None if it is empty.

Parameters

  • &self

Returns

If the slice is empty, this returns None, otherwise, it returns Some of:

  • the last bit
  • a &BitSlice of all the rest of the bits (this may be empty)

Examples

use bitvec::prelude::*;

assert!(BitSlice::<BigEndian, u8>::empty().split_last().is_none());

let bits = 1u8.as_bitslice::<BigEndian>();
let (t, h) = bits.split_last().unwrap();
assert!(t);
assert!(h.not_any());

let bits = &bits[7 .. 8];
let (t, h) = bits.split_last().unwrap();
assert!(t);
assert!(h.is_empty());

pub fn split_last_mut(&mut self) -> Option<(bool, &mut Self)>[src]

Returns the last and all the rest of the bits in the slice, or None if it is empty.

Parameters

  • &self

Returns

If the slice is empty, this returns None, otherwise, it returns Some of:

  • the last bit
  • a &BitSlice of all the rest of the bits (this may be empty)

Examples

use bitvec::prelude::*;

let mut store = 0u8;
let bits = store.as_mut_bitslice::<LittleEndian>();
assert!(!bits[7]);
*bits.at(7) = true;
let (h, t) = bits.split_last_mut().unwrap();
assert!(h);
assert_eq!(t.len(), 7);

pub fn last(&self) -> Option<bool>[src]

Gets the last element of the slice, or None if it is empty.

Parameters

  • &self

Returns

None if the slice is empty, or Some(bit) if it is not.

Examples

use bitvec::prelude::*;

assert!(BitSlice::<BigEndian, u8>::empty().last().is_none());
assert!(1u8.as_bitslice::<BigEndian>().last().unwrap());

pub fn get(&self, index: usize) -> Option<bool>[src]

Gets the bit value at the given position.

Parameters

  • &self
  • index: The bit index to retrieve.

Returns

The bit at the specified index, if any. If index is beyond the bounds of self, then None is produced.

Examples

use bitvec::prelude::*;

let bits = 8u8.as_bitslice::<BigEndian>();
assert!(bits.get(4).unwrap());
assert!(!bits.get(3).unwrap());
assert!(bits.get(10).is_none());

pub unsafe fn get_unchecked(&self, index: usize) -> bool[src]

Looks up a bit at an index, without doing bounds checking.

This is generally not recommended; use with caution! For a safe alternative, see get.

Parameters

  • &self
  • index: The bit index to retrieve. This index is not checked against the length of self.

Returns

The bit at the requested index.

Safety

This method is not safe. It performs raw pointer arithmetic to seek from the start of the slice to the requested index, and look up the bit there. It does not inspect the length of self, and it is free to perform out-of-bounds memory access.

Use this method only when you have already performed the bounds check, and can guarantee that the call occurs with a safely in-bounds index.

Examples

This example uses a bit slice of length 2, and demonstrates out-of-bounds access to the last bit in the element.

use bitvec::prelude::*;

let src = 1u8;
let bits = &src.as_bitslice::<BigEndian>()[2 .. 4];
assert_eq!(bits.len(), 2);
assert!(unsafe { bits.get_unchecked(5) });

pub fn set(&mut self, index: usize, value: bool)[src]

Sets the bit value at the given position.

Parameters

  • &mut self
  • index: The bit index to set. It must be in the domain 0 .. self.len().
  • value: The value to be set, true for 1 and false for 0.

Panics

This method panics if index is outside the slice domain.

Examples

use bitvec::prelude::*;

let mut store = 8u8;
let bits = store.as_mut_bitslice::<BigEndian>();
assert!(!bits[3]);
bits.set(3, true);
assert!(bits[3]);

pub unsafe fn set_unchecked(&mut self, index: usize, value: bool)[src]

Sets a bit at an index, without doing bounds checking.

This is generally not recommended; use with caution! For a safe alternative, see set.

Parameters

  • &mut self
  • index: The bit index to retrieve. This index is not checked against the length of self.

Effects

The bit at index is set to value.

Safety

This method is not safe. It performs raw pointer arithmetic to seek from the start of the slice to the requested index, and set the bit there. It does not inspect the length of self, and it is free to perform out-of-bounds memory write access.

Use this method only when you have already performed the bounds check, and can guarantee that the call occurs with a safely in-bounds index.

Examples

This example uses a bit slice of length 2, and demonstrates out-of-bounds access to the last bit in the element.

use bitvec::prelude::*;

let mut src = 0u8;
{
 let bits = &mut src.as_mut_bitslice::<BigEndian>()[2 .. 4];
 assert_eq!(bits.len(), 2);
 unsafe { bits.set_unchecked(5, true); }
}
assert_eq!(src, 1);

pub fn at(&mut self, index: usize) -> BitGuard<C, T>[src]

Produces a write reference to a single bit in the slice.

The structure returned by this method extends the borrow until it drops, which precludes parallel use.

The split_at_mut method allows splitting the borrows of a slice, and will enable safe parallel use of these write references. The atomic feature guarantees that parallel use does not cause data races when modifying the underlying slice.

Lifetimes

  • 'a Propagates the lifetime of the referent slice to the single-bit reference produced.

Parameters

  • &mut self
  • index: The index of the bit in self selected.

Returns

A write reference to the requested bit. Due to Rust limitations, this is not a native reference type, but is a custom structure that holds the address of the requested bit and its value. The produced structure implements Deref and DerefMut to its cached bit, and commits the cached bit to the parent slice on drop.

Usage

You must use the dereference operator on the .at() expression in order to assign to it. In general, you should prefer immediately using and discarding the returned value, rather than binding it to a name and letting it live for more than one statement.

Examples

use bitvec::prelude::*;

let mut src = 0u8;
let bits = src.as_mut_bitslice::<BigEndian>();

assert!(!bits[0]);
*bits.at(0) = true;
//  note the leading dereference.
assert!(bits[0]);

This example shows multiple usage by using split_at_mut.

use bitvec::prelude::*;

let mut src = 0u8;
let bits = src.as_mut_bitslice::<BigEndian>();

{
 let (mut a, rest) = bits.split_at_mut(2);
 let (mut b, rest) = rest.split_at_mut(3);
 *a.at(0) = true;
 *b.at(0) = true;
 *rest.at(0) = true;
}

assert_eq!(bits.as_slice()[0], 0b1010_0100);
//                               a b   rest

The above example splits the slice into three (the first, the second, and the rest) in order to hold multiple write references into the slice.

pub fn as_ptr(&self) -> *const T[src]

Retrieves a read pointer to the start of the underlying data slice.

Parameters

  • &self

Returns

A pointer to the first element, partial or not, in the underlying store.

If self is empty, then the null pointer is returned.

Safety

The caller must ensure that the slice outlives the pointer this function returns, or else it will dangle and point to garbage.

Modifying the container referenced by this slice may cause its buffer to reallocate, which would also make any pointers to it invalid.

Examples

use bitvec::prelude::*;

let src = [0u8; 4];
let bits = src.as_bitslice::<BigEndian>();
assert_eq!(src.as_ptr(), bits.as_ptr());

pub fn as_mut_ptr(&mut self) -> *mut T[src]

Retrieves a write pointer to the start of the underlying data slice.

Parameters

  • &mut self

Returns

A pointer to the first element, partial or not, in the underlying store.

If self is empty, then the null pointer is returned.

Safety

The caller must ensure that the slice outlives the pointer this function returns, or else it will dangle and point to garbage.

Modifying the container referenced by this slice may cause its buffer to reallocate, which would also make any pointers to it invalid.

Examples

use bitvec::prelude::*;

let mut src = [0u8; 4];
let src_ptr = src.as_mut_ptr();
let bits = src.as_mut_bitslice::<BigEndian>();
assert_eq!(src_ptr, bits.as_mut_ptr());

pub fn swap(&mut self, a: usize, b: usize)[src]

Swaps two bits in the slice.

Parameters

  • &mut self
  • a: The first index to be swapped.
  • b: The second index to be swapped.

Panics

Panics if either a or b are out of bounds.

Examples

use bitvec::prelude::*;

let mut store = 32u8;
let bits = store.as_mut_bitslice::<BigEndian>();
assert!(!bits[0]);
assert!(bits[2]);
bits.swap(0, 2);
assert!(bits[0]);
assert!(!bits[2]);

pub fn reverse(&mut self)[src]

Reverses the order of bits in the slice, in place.

Parameters

  • &mut self

Examples

use bitvec::prelude::*;

let mut src = 0b1010_1010u8;
{
  let bits = src.as_mut_bitslice::<BigEndian>();
  bits[1 .. 7].reverse();
}
eprintln!("{:b}", src);
assert_eq!(src, 0b1101_0100);

Important traits for Iter<'a, C, T>
pub fn iter(&self) -> Iter<C, T>[src]

Provides read-only iteration across the slice domain.

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

Parameters

  • &self

Returns

An iterator over all bits in the slice domain, in C and T ordering.

Examples

use bitvec::prelude::*;

let src = 64u8;
let bits = src.as_bitslice::<BigEndian>();
let mut iter = bits[.. 2].iter();
assert!(!iter.next().unwrap());
assert!(iter.next().unwrap());
assert!(iter.next().is_none());

Important traits for Windows<'a, C, T>
pub fn windows(&self, size: usize) -> Windows<C, T>[src]

Produces a sliding iterator over consecutive windows in the slice. Each windows has the width size. The windows overlap. If the slice is shorter than size, the produced iterator is empty.

Parameters

  • &self
  • size: The width of each window.

Returns

An iterator which yields sliding views into the slice.

Panics

This function panics if the size is zero.

Examples

use bitvec::prelude::*;

let src = 0b0100_1011u8;
let bits = src.as_bitslice::<BigEndian>();
let mut windows = bits.windows(4);
assert_eq!(windows.next(), Some(&bits[0 .. 4]));
assert_eq!(windows.next(), Some(&bits[1 .. 5]));
assert_eq!(windows.next(), Some(&bits[2 .. 6]));
assert_eq!(windows.next(), Some(&bits[3 .. 7]));
assert_eq!(windows.next(), Some(&bits[4 .. 8]));
assert!(windows.next().is_none());

Important traits for Chunks<'a, C, T>
pub fn chunks(&self, size: usize) -> Chunks<C, T>[src]

Produces a galloping iterator over consecutive chunks in the slice. Each chunk, except possibly the last, has the width size. The chunks do not overlap. If the slice is shorter than size, the produced iterator produces only one chunk.

Parameters

  • &self
  • size: The width of each chunk.

Returns

An iterator which yields consecutive chunks of the slice.

Panics

This function panics if the size is zero.

Examples

use bitvec::prelude::*;

let src = 0b0100_1011u8;
let bits = src.as_bitslice::<BigEndian>();
let mut chunks = bits.chunks(3);
assert_eq!(chunks.next(), Some(&bits[0 .. 3]));
assert_eq!(chunks.next(), Some(&bits[3 .. 6]));
assert_eq!(chunks.next(), Some(&bits[6 .. 8]));
assert!(chunks.next().is_none());

Important traits for ChunksMut<'a, C, T>
pub fn chunks_mut(&mut self, size: usize) -> ChunksMut<C, T>[src]

Produces a galloping iterator over consecutive chunks in the slice. Each chunk, except possibly the last, has the width size. The chunks do not overlap. If the slice is shorter than size, the produced iterator produces only one chunk.

Parameters

  • &mut self
  • size: The width of each chunk.

Returns

An iterator which yields consecutive mutable chunks of the slice.

Panics

This function panics if the size is zero.

Examples

use bitvec::prelude::*;

let mut src = 0b0100_1011u8;
{
 let bits = src.as_mut_bitslice::<BigEndian>();
 let mut chunks = bits.chunks_mut(3);
 chunks.next().unwrap().set(2, true);
 chunks.next().unwrap().set(2, true);
 chunks.next().unwrap().set(1, false);
}
assert_eq!(src, 0b0110_1110);

Important traits for ChunksExact<'a, C, T>
pub fn chunks_exact(&self, size: usize) -> ChunksExact<C, T>[src]

Produces a galloping iterator over consecutive chunks in the slice. Each chunk has the width size. If size does not evenly divide the slice, then the remainder is not part of the iteration, and can be accessed separately with the .remainder() method.

Parameters

  • &self
  • size: The width of each chunk.

Returns

An iterator which yields consecutive chunks of the slice.

Panics

This function panics if size is zero.

Examples

use bitvec::prelude::*;

let src = 0b0100_1011u8;
let bits = src.as_bitslice::<BigEndian>();
let mut chunks_exact = bits.chunks_exact(3);
assert_eq!(chunks_exact.next(), Some(&bits[0 .. 3]));
assert_eq!(chunks_exact.next(), Some(&bits[3 .. 6]));
assert!(chunks_exact.next().is_none());
assert_eq!(chunks_exact.remainder(), &bits[6 .. 8]);

Important traits for ChunksExactMut<'a, C, T>
pub fn chunks_exact_mut(&mut self, size: usize) -> ChunksExactMut<C, T>[src]

Produces a galloping iterator over consecutive chunks in the slice. Each chunk has the width size. If size does not evenly divide the slice, then the remainder is not part of the iteration, and can be accessed separately with the .remainder() method.

Parameters

  • &mut self
  • size: The width of each chunk.

Returns

An iterator which yields consecutive mutable chunks of the slice.

Panics

This function panics if size is zero.

Examples

use bitvec::prelude::*;

let mut src = 0b0100_1011u8;
{
 let bits = src.as_mut_bitslice::<BigEndian>();
 let mut chunks_exact = bits.chunks_exact_mut(3);
 chunks_exact.next().unwrap().set(2, true);
 chunks_exact.next().unwrap().set(2, true);
 assert!(chunks_exact.next().is_none());
}
assert_eq!(src, 0b0110_1111);

Important traits for RChunks<'a, C, T>
pub fn rchunks(&self, size: usize) -> RChunks<C, T>[src]

Produces a galloping iterator over consecutive chunks in the slice, from the back to the front. Each chunk, except possibly the front, has the width size. The chunks do not overlap. If the slice is shorter than size, then the iterator produces one item.

Parameters

  • &self
  • size: The width of each chunk.

Returns

An iterator which yields consecutive chunks of the slice, from the back to the front.

Panics

This function panics if size is zero.

Examples

use bitvec::prelude::*;

let src = 0b0100_1011u8;
let bits = src.as_bitslice::<BigEndian>();
let mut rchunks = bits.rchunks(3);
assert_eq!(rchunks.next(), Some(&bits[5 .. 8]));
assert_eq!(rchunks.next(), Some(&bits[2 .. 5]));
assert_eq!(rchunks.next(), Some(&bits[0 .. 2]));
assert!(rchunks.next().is_none());

Important traits for RChunksMut<'a, C, T>
pub fn rchunks_mut(&mut self, size: usize) -> RChunksMut<C, T>[src]

Produces a galloping iterator over consecutive chunks in the slice, from the back to the front. Each chunk, except possibly the front, has the width size. The chunks do not overlap. If the slice is shorter than size, then the iterator produces one item.

Parameters

  • &mut self
  • size: The width of each chunk.

Returns

An iterator which yields consecutive mutable chunks of the slice, from the back to the front.

Panics

This function panics if size is zero.

Examples

use bitvec::prelude::*;

let mut src = 0b0100_1011u8;
{
 let bits = src.as_mut_bitslice::<BigEndian>();
 let mut rchunks = bits.rchunks_mut(3);
 rchunks.next().unwrap().set(0, true);
 rchunks.next().unwrap().set(2, false);
 rchunks.next().unwrap().set(1, false);
 assert!(rchunks.next().is_none());
}
assert_eq!(src, 0b0000_0111);

Important traits for RChunksExact<'a, C, T>
pub fn rchunks_exact(&self, size: usize) -> RChunksExact<C, T>[src]

Produces a galloping iterator over consecutive chunks in the slice, from the back to the front. Each chunk has the width size. If size does not evenly divide the slice, then the remainder is not part of the iteration, and can be accessed separately with the .remainder() method.

Parameters

  • &self
  • size: The width of each chunk.

Returns

An iterator which yields consecutive chunks of the slice, from the back to the front.

Panics

This function panics if size is zero.

Examples

use bitvec::prelude::*;

let store: &[u8] = &[0b0100_1011];
let bits: &BitSlice = store.into();
let mut rchunks_exact = bits.rchunks_exact(3);
assert_eq!(rchunks_exact.next(), Some(&bits[5 .. 8]));
assert_eq!(rchunks_exact.next(), Some(&bits[2 .. 5]));
assert!(rchunks_exact.next().is_none());
assert_eq!(rchunks_exact.remainder(), &bits[0 .. 2]);

Important traits for RChunksExactMut<'a, C, T>
pub fn rchunks_exact_mut(&mut self, size: usize) -> RChunksExactMut<C, T>[src]

Produces a galloping iterator over consecutive chunks in the slice, from the back to the front. Each chunk has the width size. If size does not evenly divide the slice, then the remainder is not part of the iteration, and can be accessed separately with the .remainder() method.

Parameters

  • &mut self
  • size: The width of each chunk.

Returns

An iterator which yields consecutive mutable chunks of the slice, from the back to the front.

Panics

This function panics if size is zero.

Examples

use bitvec::prelude::*;

let mut src = 0b0100_1011u8;
{
 let bits = src.as_mut_bitslice::<BigEndian>();
 let mut rchunks_exact = bits.rchunks_exact_mut(3);
 rchunks_exact.next().unwrap().set(0, true);
 rchunks_exact.next().unwrap().set(2, false);
 assert!(rchunks_exact.next().is_none());
}
assert_eq!(src, 0b0100_0111);

pub fn split_at(&self, mid: usize) -> (&Self, &Self)[src]

Divides one slice into two at an index.

The first will contain all indices from [0, mid) (excluding the index mid itself) and the second will contain all indices from [mid, len) (excluding the index len itself).

Parameters

  • &self
  • mid: The index at which to split

Returns

  • The bits up to but not including mid.
  • The bits from mid onwards.

Panics

Panics if mid > self.len().

Examples

use bitvec::prelude::*;

let bits = 15u8.as_bitslice::<BigEndian>();

let (l, r) = bits.split_at(0);
assert!(l.is_empty());
assert_eq!(r, bits);

let (l, r) = bits.split_at(4);
assert_eq!(l, &bits[0 .. 4]);
assert_eq!(r, &bits[4 .. 8]);

let (l, r) = bits.split_at(8);
assert_eq!(l, bits);
assert!(r.is_empty());

pub fn split_at_mut(&mut self, mid: usize) -> (&mut Self, &mut Self)[src]

Divides one slice into two at an index.

The first will contain all indices from [0, mid) (excluding the index mid itself) and the second will contain all indices from [mid, len) (excluding the index len itself).

Parameters

  • &mut self
  • mid: The index at which to split

Returns

  • The bits up to but not including mid.
  • The bits from mid onwards.

Panics

Panics if mid > self.len().

pub fn starts_with<D, U>(&self, prefix: &BitSlice<D, U>) -> bool where
    D: Cursor,
    U: BitStore
[src]

Tests if the slice begins with the given prefix.

Parameters

  • &self
  • prefix: Any BitSlice against which self is tested. This is not required to have the same cursor or storage types as self.

Returns

Whether self begins with prefix. This is true only if self is at least as long as prefix and their bits are semantically equal.

Examples

use bitvec::prelude::*;

let bits = 0xA6u8.as_bitslice::<BigEndian>();
assert!(bits.starts_with(&bits[.. 3]));
assert!(!bits.starts_with(&bits[3 ..]));

pub fn ends_with<D, U>(&self, suffix: &BitSlice<D, U>) -> bool where
    D: Cursor,
    U: BitStore
[src]

Tests if the slice ends with the given suffix.

Parameters

  • &self
  • suffix: Any BitSlice against which self is tested. This is not required to have the same cursor or storage types as self.

Returns

Whether self ends with suffix. This is true only if self is at least as long as suffix and their bits are semantically equal.

Examples

use bitvec::prelude::*;

let bits = 0xA6u8.as_bitslice::<BigEndian>();
assert!(bits.ends_with(&bits[5 ..]));
assert!(!bits.ends_with(&bits[.. 5]));

pub fn rotate_left(&mut self, by: usize)[src]

Rotates the slice, in place, to the left.

After calling this method, the bits from [.. by] will be at the back of the slice, and the bits from [by ..] will be at the front. This operates fully in-place.

In-place rotation of bits requires this method to take O(k × n) time. It is impossible to use machine intrinsics to perform galloping rotation on bits.

Parameters

  • &mut self
  • by: The number of bits by which to rotate left. This must be in the range 0 ..= self.len(). If it is 0 or self.len(), then this method is a no-op.

Examples

use bitvec::prelude::*;

let mut src = 0xF0u8;
let bits = src.as_mut_bitslice::<BigEndian>();
bits.rotate_left(2);
assert_eq!(bits.as_ref()[0], 0xC3);

pub fn rotate_right(&mut self, by: usize)[src]

Rotates the slice, in place, to the right.

After calling this method, the bits from [self.len() - by ..] will be at the front of the slice, and the bits from [.. self.len() - by] will be at the back. This operates fully in-place.

In-place rotation of bits requires this method to take O(k × n) time. It is impossible to use machine intrinsics to perform galloping rotation on bits.

Parameters

  • &mut self
  • by: The number of bits by which to rotate right. This must be in the range 0 ..= self.len(). If it is 0 or self.len, then this method is a no-op.

Examples

use bitvec::prelude::*;

let mut src = 0xF0u8;
let bits = src.as_mut_bitslice::<BigEndian>();
bits.rotate_right(2);
assert_eq!(bits.as_ref()[0], 0x3C);

pub fn all(&self) -> bool[src]

Tests if all bits in the slice domain are set (logical ).

Truth Table

0 0 => 0
0 1 => 0
1 0 => 0
1 1 => 1

Parameters

  • &self

Returns

Whether all bits in the slice domain are set. The empty slice returns true.

Examples

use bitvec::prelude::*;

let bits = 0xFDu8.as_bitslice::<BigEndian>();
assert!(bits[.. 4].all());
assert!(!bits[4 ..].all());

pub fn any(&self) -> bool[src]

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

Truth Table

0 0 => 0
0 1 => 1
1 0 => 1
1 1 => 1

Parameters

  • &self

Returns

Whether any bit in the slice domain is set. The empty slice returns false.

Examples

use bitvec::prelude::*;

let bits = 0x40u8.as_bitslice::<BigEndian>();
assert!(bits[.. 4].any());
assert!(!bits[4 ..].any());

pub fn not_all(&self) -> bool[src]

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

Truth Table

0 0 => 1
0 1 => 1
1 0 => 1
1 1 => 0

Parameters

  • `&self

Returns

Whether any bit in the slice domain is unset.

Examples

use bitvec::prelude::*;

let bits = 0xFDu8.as_bitslice::<BigEndian>();
assert!(!bits[.. 4].not_all());
assert!(bits[4 ..].not_all());

pub fn not_any(&self) -> bool[src]

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

Truth Table

0 0 => 1
0 1 => 0
1 0 => 0
1 1 => 0

Parameters

  • &self

Returns

Whether all bits in the slice domain are unset.

Examples

use bitvec::prelude::*;

let bits = 0x40u8.as_bitslice::<BigEndian>();
assert!(!bits[.. 4].not_any());
assert!(bits[4 ..].not_any());

pub fn some(&self) -> bool[src]

Tests whether the slice has some, but not all, bits set and some, but not all, bits unset.

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

Truth Table

0 0 => 0
0 1 => 1
1 0 => 1
1 1 => 0

Parameters

  • &self

Returns

Whether the slice domain has mixed content. The empty slice returns false.

Examples

use bitvec::prelude::*;

let bits = 0b111_000_10u8.as_bitslice::<BigEndian>();
assert!(!bits[0 .. 3].some());
assert!(!bits[3 .. 6].some());
assert!(bits[6 ..].some());

pub fn count_ones(&self) -> usize[src]

Counts how many bits are set high.

Parameters

  • &self

Returns

The number of high bits in the slice domain.

Examples

use bitvec::prelude::*;

let bits = [0xFDu8, 0x25].as_bitslice::<BigEndian>();
assert_eq!(bits.count_ones(), 10);

pub fn count_zeros(&self) -> usize[src]

Counts how many bits are set low.

Parameters

  • &self

Returns

The number of low bits in the slice domain.

Examples

use bitvec::prelude::*;

let bits = [0xFDu8, 0x25].as_bitslice::<BigEndian>();
assert_eq!(bits.count_zeros(), 6);

pub fn set_all(&mut self, value: bool)[src]

Set all bits in the slice to a value.

Parameters

  • &mut self
  • value: The bit value to which all bits in the slice will be set.

Examples

use bitvec::prelude::*;

let mut src = 0u8;
let bits = src.as_mut_bitslice::<BigEndian>();
bits[2 .. 6].set_all(true);
assert_eq!(bits.as_ref(), &[0b0011_1100]);
bits[3 .. 5].set_all(false);
assert_eq!(bits.as_ref(), &[0b0010_0100]);
bits[.. 1].set_all(true);
assert_eq!(bits.as_ref(), &[0b1010_0100]);

pub fn for_each<F>(&mut self, func: F) where
    F: Fn(usize, bool) -> bool
[src]

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.

Parameters

  • &mut self
  • func: A function which receives a (usize, bool) pair of index and value, and returns a bool. It receives the bit at each position, and the return value is written back at that position.

Examples

use bitvec::prelude::*;

let mut src = 0u8;
{
 let bits = src.as_mut_bitslice::<BigEndian>();
 bits.for_each(|idx, _bit| idx % 3 == 0);
}
assert_eq!(src, 0b1001_0010);

pub fn add_assign_reverse<I>(&mut self, addend: I) -> bool where
    I: IntoIterator<Item = bool>, 
[src]

Performs “reverse” addition (left to right instead of right to left).

This addition interprets the slice, and the other addend, as having its least significant bits first in the order and its most significant bits last. This is most likely to be numerically useful under a LittleEndian Cursor type.

Parameters

  • &mut self: The addition uses self as one addend, and writes the sum back into self.
  • addend: impl IntoIterator<Item=bool>: A stream of bits. When this is another BitSlice, iteration proceeds from left to right.

Return

The final carry bit is returned

Effects

Starting from index 0 and proceeding upwards until either self or addend expires, the carry-propagated addition of self[i] and addend[i] is written to self[i].

  101111
+ 0010__ (the two missing bits are logically zero)
--------
  100000 1 (the carry-out is returned)

Examples

use bitvec::prelude::*;

let mut a = 0b0000_1010u8;
let     b = 0b0000_1100u8;
//      s =      1 0110
let ab = &mut a.as_mut_bitslice::<LittleEndian>()[.. 4];
let bb = &    b.as_bitslice::<LittleEndian>()[.. 4];
let c = ab.add_assign_reverse(bb);
assert!(c);
assert_eq!(ab.as_slice()[0], 0b0000_0110u8);

Performance Notes

When using LittleEndian Cursor types, this can be accelerated by delegating the addition to the underlying types. This is a software implementation of the ripple-carry adder, which has O(n) runtime in the number of bits. The CPU is much faster, as it has access to element-wise or vectorized addition operations.

If your use case sincerely needs binary-integer arithmetic operations on bit sets

pub fn as_slice(&self) -> &[T][src]

Accesses the backing storage of the BitSlice as a slice of its elements.

Parameters

  • &self

Returns

A slice of all the elements that the BitSlice uses for storage.

Examples

use bitvec::prelude::*;

let src = [1u8, 66];
let bits = src.as_bitslice::<BigEndian>();

let accum = bits.as_slice()
  .iter()
  .map(|elt| elt.count_ones())
  .sum::<usize>();
assert_eq!(accum, 3);

pub fn as_mut_slice(&mut self) -> &mut [T][src]

Accesses the underlying store.

Examples

use bitvec::prelude::*;

let mut src = [1u8, 64];
let bits = src.as_mut_bitslice::<BigEndian>();
for elt in bits.as_mut_slice() {
  *elt |= 2;
}
assert_eq!(&[3, 66], bits.as_slice());

pub fn change_cursor<D>(&self) -> &BitSlice<D, T> where
    D: Cursor
[src]

Changes the cursor type of the slice handle.

Parameters

  • &self

Returns

An equivalent slice handle with a new cursor type.

Type Parameters

  • D: Cursor The new cursor type to use for the handle.

Examples

use bitvec::prelude::*;

let src = 2u8;
let bits = src.as_bitslice::<BigEndian>();
assert!(bits[6]);
let bits = bits.change_cursor::<LittleEndian>();
assert!(bits[1]);

pub fn change_cursor_mut<D>(&mut self) -> &mut BitSlice<D, T> where
    D: Cursor
[src]

Changes the cursor type of the slice handle.

Parameters

  • &mut self

Returns

An equivalent slice handle with a new cursor type.

Type Parameters

  • D: Cursor The new cursor type to use for the handle.

Examples

use bitvec::prelude::*;

let mut src = 0u8;
*src.as_mut_bitslice::<BigEndian>().at(1) = true;
assert_eq!(src, 64);
src.as_mut_bitslice::<BigEndian>()
   .change_cursor_mut::<LittleEndian>()
   .set(1, true);
assert_eq!(src, 66);

pub fn bitptr(&self) -> BitPtr<T>[src]

Accesses the underlying pointer structure.

Parameters

  • &self

Returns

The BitPtr structure of the slice handle.

Trait Implementations

impl<C, T> Send for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

BitVec is safe to move across thread boundaries, as is &mut BitVec.

impl<C, T> Sync for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

&BitVec is safe to move across thread boundaries.

impl<C, T> Drop for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

Readies the underlying storage for Drop.

fn drop(&mut self)[src]

Rebuild the interior Vec and let it run the deallocator.

impl<C, T> AsRef<BitSlice<C, T>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> AsRef<[T]> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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

fn as_ref(&self) -> &[T][src]

Accesses the underlying store.

Examples

use bitvec::prelude::*;

let bv = bitvec![0, 0, 0, 0, 0, 0, 0, 0, 1];
assert_eq!(&[0, 0b1000_0000], bv.as_slice());

impl<C, T> AsMut<BitSlice<C, T>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> AsMut<[T]> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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

impl<C, T> Into<Box<[T]>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> Into<Vec<T>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> From<BitVec<C, T>> for BitBox<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<'_, C, T> From<&'_ BitSlice<C, T>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<'_, C, T> From<&'_ [bool]> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

Builds a BitVec out of a slice of bool.

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

impl<C, T> From<BitBox<C, T>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<'_, C, T> From<&'_ [T]> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> From<Box<[T]>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> From<Vec<T>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

impl<C, T> Extend<bool> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

fn extend<I: IntoIterator<Item = bool>>(&mut self, src: I)[src]

Extends a BitVec from another bitstream.

Parameters

  • &mut self
  • src: A source bitstream.

Type Parameters

  • I: IntoIterator<Item=bool>: The source bitstream with which to extend self.

Examples

use bitvec::prelude::*;

let mut bv = bitvec![0; 4];
bv.extend(bitvec![1; 4]);
assert_eq!(0x0F, bv.as_slice()[0]);

impl<C, T> IntoIterator for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

type Item = bool

The type of the elements being iterated over.

type IntoIter = IntoIter<C, T>

Which kind of iterator are we turning this into?

fn into_iter(self) -> Self::IntoIter[src]

Iterates over the vector.

Examples

use bitvec::prelude::*;

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);

impl<'a, C, T> IntoIterator for &'a BitVec<C, T> where
    C: Cursor,
    T: 'a + BitStore
[src]

type Item = bool

The type of the elements being iterated over.

type IntoIter = <&'a BitSlice<C, T> as IntoIterator>::IntoIter

Which kind of iterator are we turning this into?

impl<C, T> Clone for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> Default for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> Eq for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> Ord for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<A, B, C, D> PartialEq<BitVec<C, D>> for BitSlice<A, B> where
    A: Cursor,
    B: BitStore,
    C: Cursor,
    D: BitStore
[src]

Allow comparison against the allocated form.

impl<'_, A, B, C, D> PartialEq<BitVec<C, D>> for &'_ BitSlice<A, B> where
    A: Cursor,
    B: BitStore,
    C: Cursor,
    D: BitStore
[src]

impl<A, B, C, D> PartialEq<BitVec<C, D>> for BitVec<A, B> where
    A: Cursor,
    B: BitStore,
    C: Cursor,
    D: BitStore
[src]

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

It is valid to compare two vectors of different cursor 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.

fn eq(&self, rhs: &BitVec<C, D>) -> bool[src]

Performs a comparison by ==.

Parameters

  • &self
  • rhs: The other vector to compare.

Returns

Whether the vectors compare equal.

Examples

use bitvec::prelude::*;

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::prelude::*;

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_slice(), r.as_slice());

impl<A, B, C, D> PartialEq<BitSlice<C, D>> for BitVec<A, B> where
    A: Cursor,
    B: BitStore,
    C: Cursor,
    D: BitStore
[src]

impl<'_, A, B, C, D> PartialEq<&'_ BitSlice<C, D>> for BitVec<A, B> where
    A: Cursor,
    B: BitStore,
    C: Cursor,
    D: BitStore
[src]

impl<A, B, C, D> PartialOrd<BitVec<C, D>> for BitSlice<A, B> where
    A: Cursor,
    B: BitStore,
    C: Cursor,
    D: BitStore
[src]

impl<'_, A, B, C, D> PartialOrd<BitVec<C, D>> for &'_ BitSlice<A, B> where
    A: Cursor,
    B: BitStore,
    C: Cursor,
    D: BitStore
[src]

impl<A, B, C, D> PartialOrd<BitVec<C, D>> for BitVec<A, B> where
    A: Cursor,
    B: BitStore,
    C: Cursor,
    D: BitStore
[src]

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.

fn partial_cmp(&self, rhs: &BitVec<C, D>) -> Option<Ordering>[src]

Performs a comparison by < or >.

Parameters

  • &self
  • rhs: The other vector to compare.

Returns

The relative ordering of the two vectors.

Examples

use bitvec::prelude::*;

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);

impl<A, B, C, D> PartialOrd<BitSlice<C, D>> for BitVec<A, B> where
    A: Cursor,
    B: BitStore,
    C: Cursor,
    D: BitStore
[src]

impl<'_, A, B, C, D> PartialOrd<&'_ BitSlice<C, D>> for BitVec<A, B> where
    A: Cursor,
    B: BitStore,
    C: Cursor,
    D: BitStore
[src]

impl<C, T> Display for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

fn fmt(&self, f: &mut Formatter) -> Result[src]

Renders the BitVec contents for display.

Examples

use bitvec::prelude::*;

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

impl<C, T> Debug for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

Prints the BitVec for debugging.

The output is of the form BitVec<C, T> [ELT, *], where <C, T> is the cursor 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_slice()); instead.

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

fn fmt(&self, f: &mut Formatter) -> Result[src]

Renders the BitVec type header and contents for debug.

Examples

use bitvec::prelude::*;

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)
);

impl<C, T> Sub<BitVec<C, T>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

type Output = Self

The resulting type after applying the - operator.

fn sub(self, subtrahend: Self) -> Self::Output[src]

Subtracts one BitVec from another.

Examples

Minuend larger than subtrahend, positive difference.

use bitvec::prelude::*;

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::prelude::*;

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::prelude::*;

let a = bitvec![0, 1, 1, 0];
let b = a.clone();
let c = a - b;
assert!(c.not_any(), "{:?}", c);

impl<C, T> Add<BitVec<C, T>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

type Output = Self

The resulting type after applying the + operator.

fn add(self, addend: Self) -> Self::Output[src]

Adds two BitVecs.

Examples

use bitvec::prelude::*;

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::prelude::*;

let a = bitvec![1; 4];
let b = bitvec![1; 1];
let s = b + a;
assert_eq!(bitvec![1, 0, 0, 0, 0], s);

impl<C, T> Neg for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

type Output = Self

The resulting type after applying the - operator.

fn neg(self) -> Self::Output[src]

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

Examples

use bitvec::prelude::*;

let bv = bitvec![0, 1, 1];
let ne = -bv;
assert_eq!(ne, bitvec![1, 0, 1]);

impl<C, T> AddAssign<BitVec<C, T>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

fn add_assign(&mut self, addend: Self)[src]

Adds another BitVec into self.

Examples

use bitvec::prelude::*;

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]);

impl<C, T> SubAssign<BitVec<C, T>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

fn sub_assign(&mut self, subtrahend: Self)[src]

Subtracts another BitVec from self.

Examples

use bitvec::prelude::*;

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]);

impl<C, T> Not for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

Flips all bits in the vector.

type Output = Self

The resulting type after applying the ! operator.

fn not(self) -> Self::Output[src]

Inverts all bits in the vector.

Examples

use bitvec::prelude::*;

let bv: BitVec<BigEndian, u32> = BitVec::from(&[0u32] as &[u32]);
let flip = !bv;
assert_eq!(!0u32, flip.as_slice()[0]);

impl<C, T, I> BitAnd<I> for BitVec<C, T> where
    C: Cursor,
    T: BitStore,
    I: IntoIterator<Item = bool>, 
[src]

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.

type Output = Self

The resulting type after applying the & operator.

fn bitand(self, rhs: I) -> Self::Output[src]

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

Examples

use bitvec::prelude::*;

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));

impl<C, T, I> BitOr<I> for BitVec<C, T> where
    C: Cursor,
    T: BitStore,
    I: IntoIterator<Item = bool>, 
[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.

type Output = Self

The resulting type after applying the | operator.

fn bitor(self, rhs: I) -> Self::Output[src]

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

Examples

use bitvec::prelude::*;

let lhs = bitvec![0, 1, 0, 1];
let rhs = bitvec![0, 0, 1, 1];
let or  = lhs | rhs;
assert_eq!("[0111]", &format!("{}", or));

impl<C, T, I> BitXor<I> for BitVec<C, T> where
    C: Cursor,
    T: BitStore,
    I: IntoIterator<Item = bool>, 
[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.

type Output = Self

The resulting type after applying the ^ operator.

fn bitxor(self, rhs: I) -> Self::Output[src]

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

Examples

use bitvec::prelude::*;

let lhs = bitvec![0, 1, 0, 1];
let rhs = bitvec![0, 0, 1, 1];
let xor = lhs ^ rhs;
assert_eq!("[0110]", &format!("{}", xor));

impl<C, T> Shl<usize> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

type Output = Self

The resulting type after applying the << operator.

fn shl(self, shamt: usize) -> Self::Output[src]

Shifts a BitVec to the left, shortening it.

Examples

use bitvec::prelude::*;

let bv = bitvec![BigEndian, u8; 0, 0, 0, 1, 1, 1];
assert_eq!("[000111]", &format!("{}", bv));
assert_eq!(0b0001_1100, bv.as_slice()[0]);
assert_eq!(bv.len(), 6);
let ls = bv << 2usize;
assert_eq!("[0111]", &format!("{}", ls));
assert_eq!(0b0111_0000, ls.as_slice()[0]);
assert_eq!(ls.len(), 4);

impl<C, T> Shr<usize> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

type Output = Self

The resulting type after applying the >> operator.

fn shr(self, shamt: usize) -> Self::Output[src]

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

Examples

use bitvec::prelude::*;

let bv = bitvec![BigEndian, u8; 0, 0, 0, 1, 1, 1];
assert_eq!("[000111]", &format!("{}", bv));
assert_eq!(0b0001_1100, bv.as_slice()[0]);
assert_eq!(bv.len(), 6);
let rs = bv >> 2usize;
assert_eq!("[00000111]", &format!("{}", rs));
assert_eq!(0b0000_0111, rs.as_slice()[0]);
assert_eq!(rs.len(), 8);

impl<C, T, I> BitAndAssign<I> for BitVec<C, T> where
    C: Cursor,
    T: BitStore,
    I: IntoIterator<Item = bool>, 
[src]

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.

fn bitand_assign(&mut self, rhs: I)[src]

ANDs another bitstream into a vector.

Examples

use bitvec::prelude::*;

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

impl<C, T, I> BitOrAssign<I> for BitVec<C, T> where
    C: Cursor,
    T: BitStore,
    I: IntoIterator<Item = bool>, 
[src]

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.

fn bitor_assign(&mut self, rhs: I)[src]

ORs another bitstream into a vector.

Examples

use bitvec::prelude::*;

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

impl<C, T, I> BitXorAssign<I> for BitVec<C, T> where
    C: Cursor,
    T: BitStore,
    I: IntoIterator<Item = bool>, 
[src]

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.

fn bitxor_assign(&mut self, rhs: I)[src]

XORs another bitstream into a vector.

Examples

use bitvec::prelude::*;

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

impl<C, T> ShlAssign<usize> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

fn shl_assign(&mut self, shamt: usize)[src]

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

Examples

use bitvec::prelude::*;

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

impl<C, T> ShrAssign<usize> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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.

fn shr_assign(&mut self, shamt: usize)[src]

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

Examples

use bitvec::prelude::*;

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

impl<C, T> Deref for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

Reborrows the BitVec as a BitSlice.

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

type Target = BitSlice<C, T>

The resulting type after dereferencing.

fn deref(&self) -> &Self::Target[src]

Dereferences &BitVec down to &BitSlice.

Examples

use bitvec::prelude::*;

let bv: BitVec = bitvec![1; 4];
let bref: &BitSlice = &bv;
assert!(bref[2]);

impl<C, T> DerefMut for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

Mutably reborrows the BitVec as a BitSlice.

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

fn deref_mut(&mut self) -> &mut Self::Target[src]

Dereferences &mut BitVec down to &mut BitSlice.

Examples

use bitvec::prelude::*;

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

impl<C, T> Index<usize> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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

type Output = bool

The returned type after indexing.

fn index(&self, cursor: usize) -> &Self::Output[src]

Looks up a single bit by semantic count.

Examples

use bitvec::prelude::*;

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::prelude::*;

let mut bv: BitVec = BitVec::new();
bv.push(true);
bv[1];

impl<C, T> Index<Range<usize>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

type Output = BitSlice<C, T>

The returned type after indexing.

impl<C, T> Index<RangeFrom<usize>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

type Output = BitSlice<C, T>

The returned type after indexing.

impl<C, T> Index<RangeFull> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

type Output = BitSlice<C, T>

The returned type after indexing.

impl<C, T> Index<RangeInclusive<usize>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

type Output = BitSlice<C, T>

The returned type after indexing.

impl<C, T> Index<RangeTo<usize>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

type Output = BitSlice<C, T>

The returned type after indexing.

impl<C, T> Index<RangeToInclusive<usize>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

type Output = BitSlice<C, T>

The returned type after indexing.

impl<C, T> IndexMut<Range<usize>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> IndexMut<RangeFrom<usize>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> IndexMut<RangeFull> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> IndexMut<RangeInclusive<usize>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> IndexMut<RangeTo<usize>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> IndexMut<RangeToInclusive<usize>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> Hash for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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

fn hash<H: Hasher>(&self, hasher: &mut H)[src]

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

Parameters

  • &self
  • hasher: The hashing pool into which the vector is written.

impl<C, T> FromIterator<bool> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

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

fn from_iter<I: IntoIterator<Item = bool>>(src: I) -> Self[src]

Collects an iterator of bool into a vector.

Examples

use bitvec::prelude::*;

use std::iter::repeat;
let bv: BitVec = repeat(true)
  .take(4)
  .chain(repeat(false).take(4))
  .collect();
assert_eq!(bv.as_slice()[0], 0xF0);

impl<C, T> Borrow<BitSlice<C, T>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

Signifies that BitSlice is the borrowed form of BitVec.

fn borrow(&self) -> &BitSlice<C, T>[src]

Borrows the BitVec as a BitSlice.

Parameters

  • &self

Returns

A borrowed BitSlice of the vector.

Examples

use bitvec::prelude::*;
use std::borrow::Borrow;

let bv = bitvec![0; 13];
let bs: &BitSlice = bv.borrow();
assert!(!bs[10]);

impl<C, T> BorrowMut<BitSlice<C, T>> for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

Signifies that BitSlice is the borrowed form of BitVec.

fn borrow_mut(&mut self) -> &mut BitSlice<C, T>[src]

Mutably borrows the BitVec as a BitSlice.

Parameters

  • &mut self

Returns

A mutably borrowed BitSlice of the vector.

Examples

use bitvec::prelude::*;
use std::borrow::BorrowMut;

let mut bv = bitvec![0; 13];
let bs: &mut BitSlice = bv.borrow_mut();
assert!(!bs[10]);
bs.set(10, true);
assert!(bs[10]);

impl<C, T> Write for BitVec<C, T> where
    C: Cursor,
    T: BitStore
[src]

impl<C, T> Serialize for BitVec<C, T> where
    C: Cursor,
    T: BitStore + Serialize
[src]

impl<'de, C, T> Deserialize<'de> for BitVec<C, T> where
    C: Cursor,
    T: 'de + BitStore + Deserialize<'de>, 
[src]

Auto Trait Implementations

impl<C, T> Unpin for BitVec<C, T> where
    C: Unpin,
    T: Unpin

impl<C, T> UnwindSafe for BitVec<C, T> where
    C: UnwindSafe,
    T: UnwindSafe

impl<C, T> RefUnwindSafe for BitVec<C, T> where
    C: RefUnwindSafe,
    T: RefUnwindSafe

Blanket Implementations

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> From<T> for T[src]

impl<I> IntoIterator for I where
    I: Iterator
[src]

type Item = <I as Iterator>::Item

The type of the elements being iterated over.

type IntoIter = I

Which kind of iterator are we turning this into?

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T> ToString for T where
    T: Display + ?Sized
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> DeserializeOwned for T where
    T: Deserialize<'de>, 
[src]