#[repr(C)]pub struct BitVec<O = Lsb0, T = usize> where
O: BitOrder,
T: BitStore, { /* private fields */ }
Expand description
A contiguous growable array of bits.
This is a managed, heap-allocated, buffer that contains a BitSlice
region.
It is analagous to Vec<bool>
, and is written to be very nearly a drop-in
replacement for it. This type contains little interesting behavior in its own
right; most of its behavior is provided by dereferencing to its managed
BitSlice
buffer. It instead serves primarily as an interface to the
allocator, and has some specialized behaviors for its fully-owned memory buffer.
Documentation
All APIs that mirror something in the standard library will have an Original
section linking to the corresponding item. All APIs that have a different
signature or behavior than the original will have an API Differences
section
explaining what has changed, and how to adapt your existing code to the change.
These sections look like this:
Original
API Differences
The buffer type Vec<bool>
has no type parameters. BitVec<O, T>
has the
same two type parameters as BitSlice<O, T>
. Otherwise, BitVec
is able to implement the full API surface of Vec<bool>
.
Examples
Because BitVec
takes type parameters, but has default type arguments for them,
you will need to specify its type parameters when using its associated
functions. The easiest way to do this is to declare bindings type as : BitVec
,
which uses the default type arguments.
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);
// `BitVec` cannot yet support `[]=` write indexing.
*bv.get_mut(0).unwrap() = true;
assert_eq!(bv[0], true);
bv.extend(bits![0, 1, 0]);
for bit in &bv {
println!("{}", bit);
}
assert_eq!(bv, bits![1, 0, 1, 0]);
The bitvec!
macro is provided to make initialization more convenient:
use bitvec::prelude::*;
let mut bv = bitvec![0, 0, 1];
bv.push(true);
assert_eq!(bv, bits![0, 0, 1, 1]);
It has the same argument syntax as vec!
. In addition, it can take type
arguments for ordering and storage:
use bitvec::prelude::*;
let bv = bitvec![Msb0, u16; 1; 30];
assert!(bv.all());
assert_eq!(bv.len(), 30);
Indexing
The BitVec
type allows you to access bits by index, because it implements the
Index
trait. However, because IndexMut
requires producing an &mut bool
reference, it cannot implement []=
index assignment syntax. Instead, you must
use get_mut
or get_unchecked_mut
to produce proxy types that can serve
the same purpose.
Slicing
A BitVec
is resizable, while BitSlice
is a fixed-size view of a buffer.
Just as with ordinary Vec
s and slices, you can get a BitSlice
from a
BitVec
by borrowing it:
use bitvec::prelude::*;
fn read_bitslice(slice: &BitSlice) {
// …
}
let bv = bitvec![0; 30];
read_bitslice(&bv);
// … and that’s all!
// you can also do it like this:
let x: &BitSlice = &bv;
As with ordinary Rust types, you should prefer passing bit-slices rather than buffers when you just want to inspect the data, and not manage the underlying memory region.
Behavior
Because BitVec
is a fully-owned buffer, it is able to operate on its memory
without concern for any other views that may alias. This enables it to
specialize some BitSlice
behavior to be faster or more efficient. However,
BitVec
is not restricted to only using unaliased integer storage, and
technically permits the construction of BitVec<_, AtomicType>
.
This restriction is extremely awkward and constraining to write in the library,
and clients will probably never attempt to construct them, but the possibility
is still present. Be aware of this possibility when using generic code to
convert from BitSlice
to BitVec
. Fully-typed code does not need to be
concerned with this possibility.
Capacity and Reällocation
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 actual bits within the vector. If a vector’s length exceeds its capacity, its capacity will automatically be increased, but its buffer will have to be reällocated
For example, a bit-vector with capacity 64 and length 0 would be an empty vector
with space for 64 more bits. Pushing 64 or fewer bits onto the vector will not
change its capacity or cause reällocation to occur. However, if the vector’s
length is increased to 65, it may have to reällocate, which can be slow. For
this reason, it is recommended to use BitVec::with_capacity
whenever
possible to specify how big the vector is expected to get.
Safety
Like BitSlice
, BitVec
is exactly equal in size to Vec
, and is also
absolutely representation-incompatible with it. You must never attempt to
type-cast between Vec<T>
and BitVec
in any way, nor attempt to modify the
memory value of a BitVec
handle. Doing so will cause allocator and memory
errors in your program, likely inducing a panic.
Everything in the BitVec
public API, even the unsafe
parts, are guaranteed
to have no more unsafety than their equivalent items in the standard library.
All unsafe
APIs will have documentation explicitly detailing what the API
requires you to uphold in order for it to function safely and correctly. All
safe APIs will do so themselves.
Performance
The choice of BitStore
type parameter can impact your vector’s performance,
as the allocator operates in units of T
rather than in bits. This means that
larger register types will increase the amount of memory reserved in each call
to the allocator, meaning fewer calls to push
will actually cause a
reällocation. In addition, iteration over the vector is governed by the
BitSlice
characteristics on the type parameter. You are generally better off
using larger types when your vector is a data collection rather than a specific
I/O protocol buffer.
Macro Construction
Heap allocation can only occur at runtime, but the bitvec!
macro will
construct an appropriate BitSlice
buffer at compile-time, and at run-time,
only copy the buffer into a heap allocation.
Implementations
Port of the Vec<T>
inherent API.
Constructs a new, empty, BitVec<O, T>
with the specified capacity (in
bits).
The bit-vector will be able to hold at least capacity
bits without
reällocating. If capacity
is 0, the bit-vector will not allocate.
It is important to note that although the returned bit-vector has the capacity specified, the bit-vector will have a zero length. For an explanation of the difference between length and capacity, see Capacity and reällocation.
Original
Panics
Panics if the requested capacity exceeds the bit-vector’s limits.
Examples
use bitvec::prelude::*;
let mut bv: BitVec = BitVec::with_capacity(128);
// The bit-vector contains no bits, even
// though it has the capacity for more.
assert_eq!(bv.len(), 0);
assert!(bv.capacity() >= 128);
// These are all done
// without reällocating…
for i in 0 .. 128 {
bv.push(i & 0xC0 == i);
}
assert_eq!(bv.len(), 128);
assert!(bv.capacity() >= 128);
// …but this may make the
// bit-vector reällocate.
bv.push(false);
assert_eq!(bv.len(), 129);
assert!(bv.capacity() >= 129);
Decomposes a BitVec<O, T>
into its raw components.
Returns the raw bit-pointer to the underlying data, the length of the
bit-vector (in bits), and the allocated capacity of the buffer (in
bits). These are the same arguments in the same order as the arguments
to from_raw_parts
.
After calling this function, the caller is responsible for the memory
previously managed by the BitVec
. The only way to do this is to
convert the raw bit-pointer, length, and capacity back into a BitVec
with the from_raw_parts
function, allowing the destructor to perform
the cleanup.
Original
API Differences
This returns a BitPtr
, rather than a *mut T
. If you need the actual
memory address, BitPtr::pointer
will produce it.
Examples
use bitvec::prelude::*;
use core::cell::Cell;
let bv: BitVec = bitvec![0, 1, 0, 0, 1];
let (ptr, len, cap) = bv.into_raw_parts();
let rebuilt = unsafe {
// We can now make changes to the components, such
// as casting the pointer to a compatible type.
let ptr = ptr.cast::<Cell<usize>>();
BitVec::from_raw_parts(ptr, len, cap)
};
assert_eq!(rebuilt, bits![0, 1, 0, 0, 1]);
Creates a BitVec<O, T>
directly from the raw components of another
bit-vector.
Original
API Differences
This takes a BitPtr
, rather than a *mut T
. If you only have a
pointer, you can construct a BitPtr
to its zeroth bit before calling
this.
Safety
This is highly unsafe, due to the number of invariants that aren’t checked:
bitptr
needs to have been previously allocated byBitVec<O, T>
, or constructed from a pointer allocated byVec<T>
.T
needs to have the same size and alignment as whatbitptr
was allocated with. (T
having a less strict alignment is not sufficient; the alignment really needs to be equal to satisf thedealloc
requirement that memory must be allocated and deällocated with the same layout.) However, you can safely cast between bare integers,BitSafe
integers,Cell
wrappers, and atomic integers, as long as they all have the same width.length
needs to be less than or equal to capacity.capacity
needs to be the capacity (in bits) that the bit-pointer was allocated with (less any head offset inbitptr
).
Violating these will cause problems. For example, it is not safe
to build a BitVec<_, u8>
from a pointer to a u16
sequence and twice
its original length, because the allocator cares about the alignment,
and these two types have different alignments. The buffer was allocated
with alignment 2 (for u16
), but after turning it into a BitVec<_, u8>
, it’ll be deällocated with alignment 1.
The ownership of bitptr
is effectively transferred to the BitVec<O, T>
which may then deällocate, reällocate, or change the contents of
memory pointed to by the bit-pointer at will. Ensure that nothing else
uses the pointer after calling this function.
Examples
use bitvec::prelude::*;
use bitvec::ptr as bv_ptr;
use core::mem::ManuallyDrop;
let bv = bitvec![0, 1, 0, 0, 1];
let mut bv = ManuallyDrop::new(bv);
let bp = bv.as_mut_bitptr();
let len = bv.len();
let cap = bv.capacity();
unsafe {
// Overwrite memory with the inverse bits.
for i in 0 .. len {
let bp = bp.add(i);
bv_ptr::write(bp, !bv_ptr::read(bp.immut()));
}
// Put everything back together into a `BitVec`.
let rebuilt = BitVec::from_raw_parts(bp, len, cap);
assert_eq!(rebuilt, bits![1, 0, 1, 1, 0]);
}
Reserves capacity for at least additional
more bits to be inserted in
the given BitVec<O, T>
. The collection may reserve more space to avoid
frequent reällocations. After calling reserve
, capacity will be
greater than or equal to self.len() + additional
. Does nothing if
capacity is already sufficient.
Original
Panics
Panics if the new capacity exceeds the bit-vector’s limits.
Examples
use bitvec::prelude::*;
let mut bv = bitvec![1];
bv.reserve(100);
assert!(bv.capacity() >= 101);
Reserves the minimum capacity for exactly additional
more bits to be
inserted in the given BitVec<O, T>
. After calling reserve_exact
,
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, capacity can not be relied upon to be precisely
minimal. Prefer reserve
if future insertions are expected.
Original
Panics
Panics if the new capacity exceeds the vector’s limits.
Examples
use bitvec::prelude::*;
let mut bv = bitvec![1];
bv.reserve_exact(100);
assert!(bv.capacity() >= 101);
Shrinks the capacity of the bit-vector as much as possible.
It will drop down as close as possible to the length but the allocator may still inform the bit-vector that there is space for a few more bits.
Original
Examples
use bitvec::prelude::*;
let mut bv: BitVec = BitVec::with_capacity(100);
bv.extend([false, true, false].iter().copied());
assert!(bv.capacity() >= 100);
bv.shrink_to_fit();
assert!(bv.capacity() >= 3);
Shortens the bit-vector, keeping the first len
bits and dropping the
rest.
If len
is greater than the bit-vector’s current length, this has no
effect.
The drain
method can emulate truncate
, but causes the excess bits
to be returned instead of dropped.
Note that this method has no effect on the allocated capacity of the
bit-vector, nor does it erase truncated memory. Bits in the
allocated memory that are outside of the as_bitslice
view always
have unspecified values, and cannot be relied upon to be zero.
Original
Examples
Truncating a five-bit vector to two bits:
use bitvec::prelude::*;
let mut bv = bitvec![1; 5];
bv.truncate(2);
assert_eq!(bv.len(), 2);
assert!(bv.as_raw_slice()[0].count_ones() >= 5);
No truncation occurs when len
is greater than the vector’s current
length:
use bitvec::prelude::*;
let mut bv = bitvec![1; 3];
bv.truncate(8);
assert_eq!(bv.len(), 3);
Truncating when len == 0
is equivalent to calling the clear
method.
use bitvec::prelude::*;
let mut bv = bitvec![0; 3];
bv.truncate(0);
assert!(bv.is_empty());
Forces the length of the bit-vector to new_len
.
This is a low-level operation that maintains none of the normal
invariants of the type. Normall changing the length of a bit-vector is
done using one of the safe operations instead, such as truncate
,
resize
, extend
, or clear
.
Original
Safety
new_len
must be less than or equal toself.capacity()
.- The memory elements underlying
old_len .. new_len
must be initialized.
Examples
This method can be useful for situations in which the bit-vector is serving as a buffer for other code, particularly over FFI:
use bitvec::prelude::*;
// `bitvec` could pair with `rustler` for a better bitstream
type ErlBitstring = BitVec<Msb0, u8>;
let mut bits_read = 0;
// An imaginary Erlang function wants a large bit buffer.
let mut buf = ErlBitstring::with_capacity(32_768);
// SAFETY: When `erl_read_bits` returns `ERL_OK`, it holds that:
// 1. `bits_read` bits were initialized.
// 2. `bits_read` <= the capacity (32_768)
// which makes `set_len` safe to call.
unsafe {
// Make the FFI call…
let status = erl_read_bits(&mut buf, 10, &mut bits_read);
if status == ERL_OK {
// …and update the length to what was read in.
buf.set_len(bits_read);
}
}
Removes a bit from the bit-vector and returns it.
The removed bit is replaced by the last bit of the bit-vector.
This does not preserve ordering, but is O(1).
Original
Panics
Panics if index
is out of bounds.
Examples
use bitvec::prelude::*;
let mut bv = bitvec![0, 0, 1, 0, 1];
assert!(!bv.swap_remove(1));
assert_eq!(bv, bits![0, 1, 1, 0]);
assert!(!bv.swap_remove(0));
assert_eq!(bv, bits![0, 1, 1]);
Inserts a bit at position index
within the bit-vector, shifting all
bits after it to the right.
Original
Panics
Panics if index > len
.
Examples
use bitvec::prelude::*;
let mut bv = bitvec![0; 5];
bv.insert(4, true);
assert_eq!(bv, bits![0, 0, 0, 0, 1, 0]);
bv.insert(2, true);
assert_eq!(bv, bits![0, 0, 1, 0, 0, 1, 0]);
Retains only the bits specified by the predicate.
In other words, remove all bits b
such that func(idx(b), &b)
returns
false
. This method operates in place, visiting each bit exactly once
in the original order, and preserves the order of the retained bits.
Original
API Differences
In order to allow more than one bit of information for the retention decision, the predicate receives the index of each bit, as well as its value.
Examples
use bitvec::prelude::*;
let mut bv = bitvec![0, 1, 1, 0, 0, 1];
bv.retain(|i, b| (i % 2 == 0) ^ b);
assert_eq!(bv, bits![0, 1, 0, 1]);
Moves all the bits of other
into self
, leaving other
empty.
Original
API Differences
This permits other
to have different type parameters than self
, and
does not require that it be of literally Self
.
Panics
Panics if the number of bits overflows the maximum bit-vector capacity.
Examples
use bitvec::prelude::*;
let mut bv1 = bitvec![Msb0, u16; 0; 10];
let mut bv2 = bitvec![Lsb0, u32; 1; 10];
bv1.append(&mut bv2);
assert_eq!(bv1.count_ones(), 10);
assert!(bv2.is_empty());
Creates a draining iterator that removes the specified range in the bit-vector and yields the removed bits.
When the iterator is dropped, all bits in the range are removed from
the bit-vector, even if the iterator was not fully consumed. If the
iterator is not dropped (with mem::forget
for example), it is
unspecified how many bits are removed.
Original
Panics
Panics if the starting point is greater than the end point or if the end point is greater than the length of the bit-vector.
use bitvec::prelude::*;
let mut bv = bitvec![0, 1, 1];
let bv2: BitVec = bv.drain(1 ..).collect();
assert_eq!(bv, bits![0]);
assert_eq!(bv2, bits![1, 1]);
// A full range clears the vector
bv.drain(..);
assert_eq!(bv, bits![]);
Clears the bit-vector, removing all values.
Note that this method has no effect on the allocated capacity of the bit-vector.
use bitvec::prelude::*;
let mut bv = bitvec![0, 1, 0, 1];
bv.clear();
assert!(bv.is_empty());
Splits the collection into two at the given index.
Returns a newly allocated bit-vector containing the bits in range [at, len)
. After the call, the original bit-vector will be left containing
the bits [0, at)
with its previous capacity unchanged.
Original
Panics
Panics if at > len
.
Examples
use bitvec::prelude::*;
let mut bv = bitvec![0, 0, 1];
let bv2 = bv.split_off(1);
assert_eq!(bv, bits![0]);
assert_eq!(bv2, bits![0, 1]);
Resizes the BitVec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the BitVec
is extended by the
difference, with each additional slot filled with the result of calling
the closure func
. The return values from func
will end up in the
BitVec
in the order they have been generated.
If new_len
is less than len
, the BitVec
is simply truncated.
This method uses a closure to create new values on every push. If you’d
rather Clone
a given value, use resize
. If you want to use the
Default
trait to generate values, you can pass
Default::default()
as the second argument.
Original
Examples
use bitvec::prelude::*;
let mut bv = bitvec![1; 3];
bv.resize_with(5, Default::default);
assert_eq!(bv, bits![1, 1, 1, 0, 0]);
let mut bv = bitvec![];
let mut p = 0;
bv.resize_with(4, || { p += 1; p % 2 == 0 });
assert_eq!(bv, bits![0, 1, 0, 1]);
Consumes and leaks the BitVec
, returning a mutable reference to the
contents, &'a mut BitSlice<O, T>
. This lifetime may be chosen to be
'static
.
This function is similar to the leak
function on BitBox
.
This function is mainly useful for data that lives for the remainder of the program’s life. Dropping the returned reference will cause a memory leak.
Original
Examples
Simple usage:
use bitvec::prelude::*;
let x = bitvec![0, 0, 1];
let static_ref: &'static mut BitSlice = x.leak();
static_ref.set(0, true);
assert_eq!(static_ref, bits![1, 0, 1]);
Resizes the BitVec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the BitVec
is extended by the
difference, with each additional slot filled with value
. If new_len
is less than len
, the BitVec
is simply truncated.
This method requires a single bool
value. If you need more
flexibility, use resize_with
.
Original
Examples
use bitvec::prelude::*;
let mut bv = bitvec![1];
bv.resize(3, false);
assert_eq!(bv, bits![1, 0, 0]);
let mut bv = bitvec![1; 4];
bv.resize(2, false);
assert_eq!(bv, bits![1; 2]);
👎 Deprecated: Vec::resize_default
is deprecated
Vec::resize_default
is deprecated
Resizes the BitVec
in-place so that len
is equal to new_len
.
pub fn splice<R, I>(
&mut self,
range: R,
replace_with: I
) -> Splice<'_, O, T, I::IntoIter>ⓘ where
R: RangeBounds<usize>,
I: IntoIterator<Item = bool>,
pub fn splice<R, I>(
&mut self,
range: R,
replace_with: I
) -> Splice<'_, O, T, I::IntoIter>ⓘ where
R: RangeBounds<usize>,
I: IntoIterator<Item = bool>,
Creates a splicing iterator that replaces the specified range in the
bit-vector with the given replace_with
iterator and yields the removed
items. replace_with
does not need to be the same length as range
.
range
is removed even if the iterator is not consumed until the end.
It is unspecified how many bits are removed from the vector if the
Splice
value is leaked.
The input iterator replace_with
is only consumed when the Splice
value is dropped.
This is optimal if:
- the tail (bits in the vector after
range
) is empty - or
replace_with
yields fewer bits thanrange
’s length - or the lower bound of its
size_hint
is exact.
Otherwise, a temporary bit-vector is allocated and the tail is moved twice.
Original
Panics
Panics if the starting point is greater than the end point or if the end point is greater than the length of the bit-vector.
Examples
use bitvec::prelude::*;
let mut bv = bitvec![0, 1, 0];
let new = bits![1, 0];
let old: BitVec = bv.splice(.. 2, new.iter().by_val()).collect();
assert_eq!(bv, bits![1, 0, 0]);
assert_eq!(old, bits![0, 1]);
General-purpose functions not present on Vec<T>
.
Constructs a BitVec
from a value repeated many times.
This function is equivalent to the bitvec![O, T; bit; len]
macro
call, and is in fact the implementation of that macro syntax.
Parameters
bit
: The bit value to which alllen
allocated bits will be set.len
: The number of live bits in the constructedBitVec
.
Returns
A BitVec
with len
live bits, all set to bit
.
Examples
use bitvec::prelude::*;
let bv = BitVec::<Msb0, u8>::repeat(true, 20);
assert_eq!(bv, bits![1; 20]);
Copies the contents of a BitSlice
into a new allocation.
This is an exact copy: the newly-created bit-vector is initialized with
a direct copy of the slice
’s underlying contents, and its handle is
set to use slice
’s head index. Slices that do not begin at the zeroth
bit of the base element will thus create misaligned vectors.
You can move the bit-vector contents down to begin at the zero index of
the bit-vector’s buffer with force_align
.
Examples
use bitvec::prelude::*;
let bits = bits![0, 1, 0, 1, 1, 0, 1, 1];
let bv = BitVec::from_bitslice(&bits[2 ..]);
assert_eq!(bv, bits[2 ..]);
assert_eq!(bits.as_slice(), bv.as_raw_slice());
Converts a Vec<T>
into a BitVec<O, T>
without copying its buffer.
Parameters
vec
: A vector to view as bits.
Returns
A BitVec
over the vec
buffer.
Panics
This panics if vec
is too long to convert into a BitVec
. See
BitSlice::MAX_ELTS
.
Examples
use bitvec::prelude::*;
let vec = vec![0u8; 4];
let bv = BitVec::<LocalBits, _>::from_vec(vec);
assert_eq!(bv, bits![0; 32]);
Converts a Vec<T>
into a BitVec<O, T>
without copying its buffer.
This method takes ownership of a memory buffer and enables it to be used
as a bit-vector. Because Vec
can be longer than BitVec
s, this is a
fallible method, and the original vector will be returned if it cannot
be converted.
Parameters
vec
: Some vector of memory, to be viewed as bits.
Returns
If vec
is short enough to be viewed as a BitVec
, then this returns
a BitVec
over the vec
buffer. If vec
is too long, then this
returns vec
unmodified.
Examples
use bitvec::prelude::*;
let vec = vec![0u8; 4];
let bv = BitVec::<LocalBits, _>::try_from_vec(vec).unwrap();
assert_eq!(bv, bits![0; 32]);
An example showing this function failing would require an allocation
exceeding !0usize >> 3
bytes in size, which is infeasible to produce.
pub fn extend_from_bitslice<O2, T2>(&mut self, other: &BitSlice<O2, T2>) where
O2: BitOrder,
T2: BitStore,
pub fn extend_from_bitslice<O2, T2>(&mut self, other: &BitSlice<O2, T2>) where
O2: BitOrder,
T2: BitStore,
Copies all bits in a BitSlice
into the BitVec
.
Original
Type Parameters
This can extend from a BitSlice
of any type arguments. Where the
source &BitSlice
matches self
’s type parameters, the implementation
is able to attempt to accelerate the copy; however, if the type
parameters do not match, then the implementation falls back to a
bit-by-bit iteration and is equivalent to the Extend
implementation.
You should only use this method when the type parameters match and there
is a possibility of copy acceleration. Otherwise, .extend()
is the
correct API.
Examples
use bitvec::prelude::*;
let mut bv = bitvec![0, 1];
bv.extend_from_bitslice(bits![1, 1, 0, 1]);
assert_eq!(bv, bits![0, 1, 1, 1, 0, 1]);
Appends a slice of elements T
to the BitVec
.
The slice
is interpreted as a BitSlice<O, T>
, then appended directly
to the bit-vector.
Original
Gets the number of elements T
that contain live bits of the
bit-vector.
Examples
use bitvec::prelude::*;
let bv = bitvec![LocalBits, u16; 1; 50];
assert_eq!(bv.elements(), 4);
Converts the bit-vector into BitBox<O, T>
.
Note that this will drop any excess capacity.
Original
API Differences
This returns a bitvec
boxed bit-slice, not a standard boxed slice. To
convert the underlying buffer into a boxed element slice, use
.into_boxed_bitslice().into_boxed_slice()
.
Examples
use bitvec::prelude::*;
let bv = bitvec![0, 1, 0, 0, 1];
let bitslice = bv.into_boxed_slice();
Any excess capacity is removed:
use bitvec::prelude::*;
let mut bv: BitVec = BitVec::with_capacity(100);
bv.extend([0, 1, 0, 0, 1].iter().copied());
assert!(bv.capacity() >= 100);
let bs = bv.into_boxed_bitslice();
assert!(bs.into_bitvec().capacity() >= 5);
Writes a value into every element that the bit-vector considers live.
This unconditionally writes element
into each live location in the
backing buffer, without altering the BitVec
’s length or capacity.
It is unspecified what effects this has on the allocated but dead
elements in the buffer. You may not rely on them being zeroed or being
set to the value
integer.
Parameters
&mut self
element
: The value which will be written to each live location in the bit-vector’s buffer.
Examples
use bitvec::prelude::*;
let mut bv = bitvec![LocalBits, u8; 0; 10];
assert_eq!(bv.as_raw_slice(), [0, 0]);
bv.set_elements(0xA5);
assert_eq!(bv.as_raw_slice(), [0xA5, 0xA5]);
Sets the uninitialized bits of the bit-vector to a fixed value.
This method modifies all bits in the allocated buffer that are outside
the as_bitslice
view so that they have a consistent value. This can
be used to zero the uninitialized memory so that when viewed as a raw
memory slice, bits outside the live region have a predictable value.
Examples
use bitvec::prelude::*;
let mut bv = 220u8.view_bits::<Lsb0>().to_bitvec();
assert_eq!(bv.as_raw_slice(), &[220u8]);
bv.truncate(4);
assert_eq!(bv.count_ones(), 2);
assert_eq!(bv.as_raw_slice(), &[220u8]);
bv.set_uninitialized(false);
assert_eq!(bv.as_raw_slice(), &[12u8]);
bv.set_uninitialized(true);
assert_eq!(bv.as_raw_slice(), &[!3u8]);
Ensures that the live region of the bit-vector’s contents begins at the leading edge of the buffer.
Examples
use bitvec::prelude::*;
let data = 0x3Cu8;
let bits = data.view_bits::<Msb0>();
let mut bv = bits[2 .. 6].to_bitvec();
assert_eq!(bv, bits[2 .. 6]);
assert_eq!(bv.as_raw_slice()[0], data);
bv.force_align();
assert_eq!(bv, bits[2 .. 6]);
// It is not specified what happens
// to bits that are no longer used.
assert_eq!(bv.as_raw_slice()[0] & 0xF0, 0xF0);
Extracts a bit-slice containing the entire bit-vector.
Equivalent to &bv[..]
.
Original
API Differences
This returns a bitvec
bit-slice, not a standard slice. To view the
underlying element buffer, use as_raw_slice
.
Examples
use bitvec::prelude::*;
let bv = bitvec![0, 1, 0, 0, 1];
let bits = bv.as_bitslice();
pub fn as_mut_bitslice(&mut self) -> &mut BitSlice<O, T>ⓘ
pub fn as_mut_bitslice(&mut self) -> &mut BitSlice<O, T>ⓘ
Extracts a mutable bit-slice of the entire bit-vector.
Equivalent to &mut bv[..]
.
Original
API Differences
This returns a bitvec
bit-slice, not a standard slice. To view the
underlying element buffer, use as_mut_raw_slice
.
Examples
use bitvec::prelude::*;
let mut bv = bitvec![0, 1, 0, 0, 1];
let bits = bv.as_mut_bitslice();
Returns a raw pointer to the bit-vector’s buffer.
The caller must ensure that the bit-vector outlives the bit-pointer this function returns, or else it will end up pointing to garbage. Modifying the bit-vector may cause its buffer to be reällocated, which would also make any bit-pointers to it invalid.
The caller must also ensure that the memory the bit-pointer
(non-transitively) points to is never written to (except inside an
UnsafeCell
) using this bit-pointer or any bit-pointer derived from
it. If you need to mutate the contents of the buffer, use
as_mut_bitptr
.
Original
API Differences
This returns a bitvec
bit-pointer, not a standard pointer. To take the
address of the underlying element buffer, use as_raw_ptr
.
Examples
use bitvec::prelude::*;
let bv = bitvec![0, 1, 0, 0, 1];
let bp = bv.as_bitptr();
unsafe {
for i in 0 .. bv.len() {
assert_eq!(bp.add(i).read(), bv[i]);
}
}
Returns an unsafe mutable bit-pointer to the bit-vector’s region.
The caller must ensure that the bit-vector outlives the bit-pointer this function returns, or else it will end up pointing to garbage. Modifying the bit-vector may cause its buffer to be reällocated, which would also make any bit-pointers to it invalid.
Original
API Differences
This returns a bitvec
bit-pointer, not a standard pointer. To take the
address of the underlying element buffer, use as_mut_raw_ptr
.
Examples
use bitvec::prelude::*;
let mut bv = BitVec::<Msb0, u8>::with_capacity(4);
let bp = bv.as_mut_bitptr();
unsafe {
for i in 0 .. 4 {
bp.add(i).write(true);
}
bv.set_len(4);
}
assert_eq!(bv, bits![1; 4]);
Views the underlying buffer as a shared element slice.
Original
API Differences
This method is renamed in order to emphasize the semantic distinction between borrowing the bit-vector contents, and borrowing the memory that implements the collection contents.
Examples
use bitvec::prelude::*;
let bv = bitvec![Msb0, u8; 0, 1, 0, 0, 1, 1, 0, 1];
let raw = bv.as_raw_slice();
assert_eq!(raw, &[0x4D]);
Views the underlying buffer as an exclusive element slice.
Original
API Differences
This method is renamed in order to emphasize the semantic distinction between borrowing the bit-vector contents, and borrowing the memory that implements the collection contents.
Examples
use bitvec::prelude::*;
let mut bv = bitvec![Msb0, u8; 0, 1, 0, 0, 1, 1, 0, 1];
let raw = bv.as_mut_raw_slice();
assert_eq!(raw, &[0x4D]);
raw[0] = 0xD4;
assert_eq!(bv, bits![1, 1, 0, 1, 0, 1, 0, 0]);
Returns a raw pointer to the bit-vector’s buffer.
Original
API Differences
This method is renamed in order to emphasize the semantic distinction between taking a pointer to the start of the bit-vector contents, and taking a pointer to the underlying memory that implements the collection contents.
Examples
use bitvec::prelude::*;
let bv = bitvec![Msb0, u8; 0, 1, 0, 0, 1];
let addr = bv.as_raw_ptr();
Returns an unsafe mutable pointer to the bit-vector’s buffer.
Original
API Differences
This method is renamed in order to emphasize the semantic distinction between taking a pointer to the start of the bit-vector contents, and taking a pointer to the underlying memory that implements the collection contents.
Examples
use bitvec::prelude::*;
let mut bv = bitvec![0, 1, 0, 0, 1];
let addr = bv.as_mut_raw_ptr();
Methods from Deref<Target = BitSlice<O, T>>
Returns a mutable pointer to the first bit of the slice, or None
if it is empty.
Original
API Differences
This crate cannot manifest &mut bool
references, and must use the
BitRef
proxy type where &mut bool
exists in the standard library
API. The proxy value must be bound as mut
in order to write through
it.
Examples
use bitvec::prelude::*;
let x = bits![mut 0, 1, 0];
if let Some(mut first) = x.first_mut() {
*first = true;
}
assert_eq!(x, bits![1, 1, 0]);
Returns the first and all the rest of the bits of the slice, or
None
if it is empty.
Original
API Differences
This crate cannot manifest &mut bool
references, and must use the
BitRef
proxy type where &mut bool
exists in the standard library
API. The proxy value must be bound as mut
in order to write through
it.
Because the references are permitted to use the same memory address, they are marked as aliasing in order to satisfy Rust’s requirements about freedom from data races.
Examples
use bitvec::prelude::*;
let x = bits![mut 0, 0, 1];
if let Some((mut first, rest)) = x.split_first_mut() {
*first = true;
rest.set(0, true);
rest.set(1, false);
}
assert_eq!(x, bits![1, 1, 0]);
Returns the last and all the rest of the bits of the slice, or
None
if it is empty.
Original
API Differences
This crate cannot manifest &mut bool
references, and must use the
BitRef
proxy type where &mut bool
exists in the standard library
API. The proxy value must be bound as mut
in order to write through
it.
Because the references are permitted to use the same memory address, they are marked as aliasing in order to satisfy Rust’s requirements about freedom from data races.
Examples
use bitvec::prelude::*;
let x = bits![mut 1, 0, 0];
if let Some((mut last, rest)) = x.split_last_mut() {
*last = true;
rest.set(0, false);
rest.set(1, true);
}
assert_eq!(x, bits![0, 1, 1]);
Returns a mutable pointer to the last bit in the slice.
Original
API Differences
This crate cannot manifest &mut bool
references, and must use the
BitRef
proxy type where &mut bool
exists in the standard library
API. The proxy value must be bound as mut
in order to write through
it.
Examples
use bitvec::prelude::*;
let x = bits![mut 0, 1, 0];
if let Some(mut last) = x.last_mut() {
*last = true;
}
assert_eq!(x, bits![0, 1, 1]);
Returns a reference to a bit or subslice depending on the type of index.
- If given a position, returns a reference to the bit at that position
or
None
if out of bounds. - If given a range, returns the subslice corresponding to that range, or
None
if out of bounds.
Original
Examples
use bitvec::prelude::*;
let v = bits![0, 1, 0];
assert_eq!(Some(&true), v.get(1).as_deref());
assert_eq!(Some(bits![0, 1]), v.get(0 .. 2));
assert_eq!(None, v.get(3));
assert_eq!(None, v.get(0 .. 4));
pub fn get_mut<'a, I>(&'a mut self, index: I) -> Option<I::Mut> where
I: BitSliceIndex<'a, O, T>,
pub fn get_mut<'a, I>(&'a mut self, index: I) -> Option<I::Mut> where
I: BitSliceIndex<'a, O, T>,
Returns a mutable reference to a bit or subslice depending on the type
of index (see .get()
) or None
if the index is out of bounds.
Original
API Differences
This crate cannot manifest &mut bool
references, and must use the
BitRef
proxy type where &mut bool
exists in the standard library
API. The proxy value must be bound as mut
in order to write through
it.
Examples
use bitvec::prelude::*;
let x = bits![mut 0, 0, 1];
if let Some(mut bit) = x.get_mut(1) {
*bit = true;
}
assert_eq!(x, bits![0, 1, 1]);
pub unsafe fn get_unchecked<'a, I>(&'a self, index: I) -> I::Immut where
I: BitSliceIndex<'a, O, T>,
pub unsafe fn get_unchecked<'a, I>(&'a self, index: I) -> I::Immut where
I: BitSliceIndex<'a, O, T>,
Returns a reference to a bit or subslice, without doing bounds checking.
This is generally not recommended; use with caution! Calling this method
with an out-of-bounds index is undefined behavior even if the
resulting reference is not used. For a safe alternative, see .get()
.
Original
Examples
use bitvec::prelude::*;
let x = bits![0, 1, 0];
unsafe {
assert_eq!(x.get_unchecked(1), &true);
}
pub unsafe fn get_unchecked_mut<'a, I>(&'a mut self, index: I) -> I::Mut where
I: BitSliceIndex<'a, O, T>,
pub unsafe fn get_unchecked_mut<'a, I>(&'a mut self, index: I) -> I::Mut where
I: BitSliceIndex<'a, O, T>,
Returns a mutable reference to a bit or subslice, without doing bounds checking.
This is generally not recommended; use with caution! Calling this method
with an out-of-bounds index is undefined behavior even if the
resulting reference is not used. For a safe alternative, see
[.get_mut()
].
Original
API Differences
This crate cannot manifest &mut bool
references, and must use the
BitRef
proxy type where &mut bool
exists in the standard library
API. The proxy value must be bound as mut
in order to write through
it.
Examples
use bitvec::prelude::*;
let x = bits![mut 0; 3];
unsafe {
let mut bit = x.get_unchecked_mut(1);
*bit = true;
}
assert_eq!(x, bits![0, 1, 0]);
Returns an iterator over the slice.
Original
API Differences
This iterator yields BitRef
proxy references, rather than &bool
ordinary references. It does so in order to promote consistency in the
crate, and make switching between immutable and mutable single-bit
access easier.
The produced iterator has a by_ref
adapter that yields &bool
references, and a by_val
adapter that yields bool
values. Use
these methods to fit this iterator into APIs that expect ordinary bool
inputs.
Examples
use bitvec::prelude::*;
let x = bits![0, 0, 1];
let mut iterator = x.iter();
assert_eq!(iterator.next().as_deref(), Some(&false));
assert_eq!(iterator.next().as_deref(), Some(&false));
assert_eq!(iterator.next().as_deref(), Some(&true));
assert_eq!(iterator.next().as_deref(), None);
Returns an iterator that allows modifying each bit.
Original
API Differences
This crate cannot manifest &mut bool
references, and must use the
BitRef
proxy type where &mut bool
exists in the standard library
API. The proxy value must be bound as mut
in order to write through
it.
This iterator marks each yielded item as aliased, as iterators can be
used to yield multiple items into the same scope. If you are using
the iterator in a manner that ensures that all yielded items have
disjoint lifetimes, you can use the .remove_alias()
adapter on it to
remove the alias marker from the yielded subslices.
Examples
use bitvec::prelude::*;
let x = bits![mut 0, 0, 1];
for mut bit in x.iter_mut() {
*bit = !*bit;
}
assert_eq!(x, bits![1, 1, 0]);
Returns an iterator over all contiguous windows of length size
. The
windows overlap. If the slice is shorter than size
, the iterator
returns no values.
Original
Panics
Panics if size
is 0.
Examples
use bitvec::prelude::*;
let slice = bits![0, 0, 1, 1];
let mut iter = slice.windows(2);
assert_eq!(iter.next().unwrap(), bits![0; 2]);
assert_eq!(iter.next().unwrap(), bits![0, 1]);
assert_eq!(iter.next().unwrap(), bits![1; 2]);
assert!(iter.next().is_none());
If the slice is shorter than size
:
use bitvec::prelude::*;
let slice = bits![0; 3];
let mut iter = slice.windows(4);
assert!(iter.next().is_none());
Returns an iterator over chunk_size
bits of the slice at a time,
starting at the beginning of the slice.
The chunks are slices and do not overlap. If chunk_size
does not
divide the length of the slice, then the last chunk will not have length
chunk_size
.
See .chunks_exact()
for a variant of this iterator that returns
chunks of always exactly chunk_size
bits, and .rchunks()
for the
same iterator but starting at the end of the slice.
Original
Panics
Panics if chunk_size
is 0.
Examples
use bitvec::prelude::*;
let slice = bits![0, 1, 0, 0, 1];
let mut iter = slice.chunks(2);
assert_eq!(iter.next().unwrap(), bits![0, 1]);
assert_eq!(iter.next().unwrap(), bits![0, 0]);
assert_eq!(iter.next().unwrap(), bits![1]);
assert!(iter.next().is_none());
Returns an iterator over chunk_size
bits of the slice at a time,
starting at the beginning of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size
does
not divide the length of the slice, then the last chunk will not have
length chunk_size
.
See .chunks_exact_mut()
for a variant of this iterator that returns
chunks of always exactly chunk_size
bits, and .rchunks_mut()
for
the same iterator but starting at the end of the slice.
Original
API Differences
This iterator marks each yielded item as aliased, as iterators can be
used to yield multiple items into the same scope. If you are using
the iterator in a manner that ensures that all yielded items have
disjoint lifetimes, you can use the .remove_alias()
adapter on it to
remove the alias marker from the yielded subslices.
Panics
Panics if chunk_size
is 0.
Examples
use bitvec::prelude::*;
let v = bits![mut 0; 5];
let mut count = 1;
for chunk in v.chunks_mut(2) {
for mut bit in chunk.iter_mut() {
*bit = count % 2 == 0;
}
count += 1;
}
assert_eq!(v, bits![0, 0, 1, 1, 0]);
pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, O, T>ⓘNotable traits for ChunksExact<'a, O, T>impl<'a, O, T> Iterator for ChunksExact<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a BitSlice<O, T>;
pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, O, T>ⓘNotable traits for ChunksExact<'a, O, T>impl<'a, O, T> Iterator for ChunksExact<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a BitSlice<O, T>;
impl<'a, O, T> Iterator for ChunksExact<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a BitSlice<O, T>;
Returns an iterator over chunk_size
bits of the slice at a time,
starting at the beginning of the slice.
The chunks are slices and do not overlap. If chunk_size
does not
divide the length of the slice, then the last up to chunk_size-1
bits
will be omitted and can be retrieved from the .remainder()
method of
the iterator.
Due to each chunk having exactly chunk_size
bits, the compiler may be
able to optimize the resulting code better than in the case of
.chunks()
.
See .chunks()
for a variant of this iterator that also returns the
remainder as a smaller chunk, and .rchunks_exact()
for the same
iterator but starting at the end of the slice.
Original
Panics
Panics if chunk_size
is 0.
Examples
use bitvec::prelude::*;
let slice = bits![0, 1, 1, 0, 0];
let mut iter = slice.chunks_exact(2);
assert_eq!(iter.next().unwrap(), bits![0, 1]);
assert_eq!(iter.next().unwrap(), bits![1, 0]);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), bits![0]);
pub fn chunks_exact_mut(
&mut self,
chunk_size: usize
) -> ChunksExactMut<'_, O, T>ⓘNotable traits for ChunksExactMut<'a, O, T>impl<'a, O, T> Iterator for ChunksExactMut<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a mut BitSlice<O, T::Alias>;
pub fn chunks_exact_mut(
&mut self,
chunk_size: usize
) -> ChunksExactMut<'_, O, T>ⓘNotable traits for ChunksExactMut<'a, O, T>impl<'a, O, T> Iterator for ChunksExactMut<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a mut BitSlice<O, T::Alias>;
impl<'a, O, T> Iterator for ChunksExactMut<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a mut BitSlice<O, T::Alias>;
Returns an iterator over chunk_size
bits of the slice at a time,
starting at the beginning of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size
does
not divide the length of the slice, then the last up to chunk_size-1
bits will be omitted and can be retrieved from the .into_remainder()
method of the iterator.
Due to each chunk having exactly chunk_size
bits, the compiler may be
able to optimize the resulting code better than in the case of
.chunks_mut()
.
See .chunks_mut()
for a variant of this iterator that also returns
the remainder as a smaller chunk, and .rchunks_exact_mut()
for the
same iterator but starting at the end of the slice.
Original
API Differences
This iterator marks each yielded item as aliased, as iterators can be
used to yield multiple items into the same scope. If you are using
the iterator in a manner that ensures that all yielded items have
disjoint lifetimes, you can use the .remove_alias()
adapter on it to
remove the alias marker from the yielded subslices.
Panics
Panics if chunk_size
is 0.
Examples
use bitvec::prelude::*;
let v = bits![mut 0; 5];
for chunk in v.chunks_exact_mut(2) {
chunk.set_all(true);
}
assert_eq!(v, bits![1, 1, 1, 1, 0]);
Returns an iterator over chunk_size
bits of the slice at a time,
starting at the end of the slice.
The chunks are slices and do not overlap. If chunk_size
does not
divide the length of the slice, then the last chunk will not have length
chunk_size
.
See .rchunks_exact()
for a variant of this iterator that returns
chunks of always exactly chunk_size
bits, and .chunks()
for the
same iterator but starting at the beginning of the slice.
Original
Panics
Panics if chunk_size
is 0.
Examples
use bitvec::prelude::*;
let slice = bits![0, 1, 0, 0, 1];
let mut iter = slice.rchunks(2);
assert_eq!(iter.next().unwrap(), bits![0, 1]);
assert_eq!(iter.next().unwrap(), bits![1, 0]);
assert_eq!(iter.next().unwrap(), bits![0]);
assert!(iter.next().is_none());
pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, O, T>ⓘNotable traits for RChunksMut<'a, O, T>impl<'a, O, T> Iterator for RChunksMut<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a mut BitSlice<O, T::Alias>;
pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, O, T>ⓘNotable traits for RChunksMut<'a, O, T>impl<'a, O, T> Iterator for RChunksMut<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a mut BitSlice<O, T::Alias>;
impl<'a, O, T> Iterator for RChunksMut<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a mut BitSlice<O, T::Alias>;
Returns an iterator over chunk_size
bits of the slice at a time,
starting at the end of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size
does
not divide the length of the slice, then the last chunk will not have
length chunk_size
.
See .rchunks_exact_mut()
for a variant of this iterator that returns
chunks of always exactly chunk_size
bits, and .chunks_mut()
for
the same iterator but starting at the beginning of the slice.
Original
API Differences
This iterator marks each yielded item as aliased, as iterators can be
used to yield multiple items into the same scope. If you are using
the iterator in a manner that ensures that all yielded items have
disjoint lifetimes, you can use the .remove_alias()
adapter on it to
remove the alias marker from the yielded subslices.
Panics
Panics if chunk_size
is 0.
Examples
use bitvec::prelude::*;
let v = bits![mut 0; 5];
let mut count = 1;
for chunk in v.rchunks_mut(2) {
for mut bit in chunk.iter_mut() {
*bit = count % 2 == 0;
}
count += 1;
}
assert_eq!(v, bits![0, 1, 1, 0, 0]);
pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, O, T>ⓘNotable traits for RChunksExact<'a, O, T>impl<'a, O, T> Iterator for RChunksExact<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a BitSlice<O, T>;
pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, O, T>ⓘNotable traits for RChunksExact<'a, O, T>impl<'a, O, T> Iterator for RChunksExact<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a BitSlice<O, T>;
impl<'a, O, T> Iterator for RChunksExact<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a BitSlice<O, T>;
Returns an iterator over chunk_size
bits of the slice at a time,
starting at the end of the slice.
The chunks are slices and do not overlap. If chunk_size
does not
divide the length of the slice, then the last up to chunk_size-1
bits
will be omitted and can be retrieved from the .remainder()
method of
the iterator.
Due to each chunk having exactly chunk_size
bits, the compiler may be
able to optimize the resulting code better than in the case of
.rchunks()
.
See .rchunks()
for a variant of this iterator that also returns the
remainder as a smaller chunk, and .chunks_exact()
for the same
iterator but starting at the beginning of the slice.
Original
Panics
Panics if chunk_size
is 0.
Examples
use bitvec::prelude::*;
let slice = bits![0, 0, 1, 1, 0];
let mut iter = slice.rchunks_exact(2);
assert_eq!(iter.next().unwrap(), bits![1, 0]);
assert_eq!(iter.next().unwrap(), bits![0, 1]);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), bits![0]);
pub fn rchunks_exact_mut(
&mut self,
chunk_size: usize
) -> RChunksExactMut<'_, O, T>ⓘNotable traits for RChunksExactMut<'a, O, T>impl<'a, O, T> Iterator for RChunksExactMut<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a mut BitSlice<O, T::Alias>;
pub fn rchunks_exact_mut(
&mut self,
chunk_size: usize
) -> RChunksExactMut<'_, O, T>ⓘNotable traits for RChunksExactMut<'a, O, T>impl<'a, O, T> Iterator for RChunksExactMut<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a mut BitSlice<O, T::Alias>;
impl<'a, O, T> Iterator for RChunksExactMut<'a, O, T> where
O: BitOrder,
T: BitStore, type Item = &'a mut BitSlice<O, T::Alias>;
Returns an iterator over chunk_size
bits of the slice at a time,
starting at the end of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size
does
not divide the length of the slice, then the last up to chunk_size-1
bits will be omitted and can be retrieved from the .into_remainder()
method of the iterator.
Due to each chunk having exactly chunk_size
bits, the compiler may be
able to optimize the resulting code better than in the case of
.rchunks_mut()
.
See .rchunks_mut()
for a variant of this iterator that also returns
the remainder as a smaller chunk, and .chunks_exact_mut()
for the
same iterator but starting at the beginning of the slice.
Original
API Differences
This iterator marks each yielded item as aliased, as iterators can be
used to yield multiple items into the same scope. If you are using
the iterator in a manner that ensures that all yielded items have
disjoint lifetimes, you can use the .remove_alias()
adapter on it to
remove the alias marker from the yielded subslices.
Panics
Panics if chunk_size
is 0.
Examples
use bitvec::prelude::*;
let v = bits![mut 0; 5];
for chunk in v.rchunks_exact_mut(2) {
chunk.set_all(true);
}
assert_eq!(v, bits![0, 1, 1, 1, 1]);
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).
Original
Panics
Panics if mid > len
.
Behavior
When mid
is 0
or self.len()
, then the left or right return values,
respectively, are empty slices. Empty slice references produced by this
method are specified to have the address information you would expect:
a left empty slice has the same base address and start bit as self
,
and a right empty slice will have its address raised by self.len()
.
Examples
use bitvec::prelude::*;
let v = bits![0, 0, 0, 1, 1, 1];
{
let (left, right) = v.split_at(0);
assert_eq!(left, bits![]);
assert_eq!(right, v);
}
{
let (left, right) = v.split_at(2);
assert_eq!(left, bits![0, 0]);
assert_eq!(right, bits![0, 1, 1, 1]);
}
{
let (left, right) = v.split_at(6);
assert_eq!(left, v);
assert_eq!(right, bits![]);
}
Divides one mutable 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).
Original
API Differences
The partition index mid
may occur anywhere in the slice, and as a
result the two returned slices may both have write access to the memory
address containing mid
. As such, the returned slices must be marked
with T::Alias
in order to correctly manage memory access going
forward.
This marking is applied to all memory accesses in both slices,
regardless of whether any future accesses actually require it. To limit
the alias marking to only the addresses that need it, use
[.bit_domain()
] or [.bit_domain_mut()
] to split either slice into
its aliased and unaliased subslices.
Panics
Panics if mid > len
.
Behavior
When mid
is 0
or self.len()
, then the left or right return values,
respectively, are empty slices. Empty slice references produced by this
method are specified to have the address information you would expect:
a left empty slice has the same base address and start bit as self
,
and a right empty slice will have its address raised by self.len()
.
Examples
use bitvec::prelude::*;
let v = bits![mut 0, 0, 0, 1, 1, 1];
// scoped to restrict the lifetime of the borrows
{
let (left, right) = v.split_at_mut(2);
assert_eq!(left, bits![0, 0]);
assert_eq!(right, bits![0, 1, 1, 1]);
left.set(1, true);
right.set(1, false);
}
assert_eq!(v, bits![0, 1, 0, 0, 1, 1]);
Returns an iterator over subslices separated by bits that match pred
.
The matched bit is not contained in the subslices.
Original
API Differences
In order to allow more than one bit of information for the split decision, the predicate receives the index of each bit, as well as its value.
Examples
use bitvec::prelude::*;
let slice = bits![0, 1, 1, 0];
let mut iter = slice.split(|pos, _bit| pos % 3 == 2);
assert_eq!(iter.next().unwrap(), bits![0, 1]);
assert_eq!(iter.next().unwrap(), bits![0]);
assert!(iter.next().is_none());
If the first bit is matched, an empty slice will be the first item returned by the iterator. Similarly, if the last bit in the slice is matched, an empty slice will be the last item returned by the iterator:
use bitvec::prelude::*;
let slice = bits![0, 0, 1];
let mut iter = slice.split(|_pos, bit| *bit);
assert_eq!(iter.next().unwrap(), bits![0, 0]);
assert_eq!(iter.next().unwrap(), bits![]);
assert!(iter.next().is_none());
If two matched bits are directly adjacent, an empty slice will be present between them:
use bitvec::prelude::*;
let slice = bits![1, 0, 0, 1];
let mut iter = slice.split(|_pos, bit| !*bit);
assert_eq!(iter.next().unwrap(), bits![1]);
assert_eq!(iter.next().unwrap(), bits![]);
assert_eq!(iter.next().unwrap(), bits![1]);
assert!(iter.next().is_none());
Returns an iterator over mutable subslices separated by bits that match
pred
. The matched bit is not contained in the subslices.
Original
API Differences
In order to allow more than one bit of information for the split decision, the predicate receives the index of each bit, as well as its value.
This iterator marks each yielded item as aliased, as iterators can be
used to yield multiple items into the same scope. If you are using
the iterator in a manner that ensures that all yielded items have
disjoint lifetimes, you can use the .remove_alias()
adapter on it to
remove the alias marker from the yielded subslices.
Examples
use bitvec::prelude::*;
let v = bits![mut 0, 0, 1, 0, 1, 0];
for group in v.split_mut(|_pos, bit| *bit) {
group.set(0, true);
}
assert_eq!(v, bits![1, 0, 1, 1, 1, 1]);
Returns an iterator over subslices separated by bits that match pred
,
starting at the end of the slice and working backwards. The matched bit
is not contained in the subslices.
Original
API Differences
In order to allow more than one bit of information for the split decision, the predicate receives the index of each bit, as well as its value.
Examples
use bitvec::prelude::*;
let slice = bits![1, 1, 1, 0, 1, 1];
let mut iter = slice.rsplit(|_pos, bit| !*bit);
assert_eq!(iter.next().unwrap(), bits![1; 2]);
assert_eq!(iter.next().unwrap(), bits![1; 3]);
assert!(iter.next().is_none());
As with .split()
, if the first or last bit is matched, an empty
slice will be the first (or last) item returned by the iterator.
use bitvec::prelude::*;
let v = bits![1, 0, 0, 1, 0, 0, 1];
let mut it = v.rsplit(|_pos, bit| *bit);
assert_eq!(it.next().unwrap(), bits![]);
assert_eq!(it.next().unwrap(), bits![0; 2]);
assert_eq!(it.next().unwrap(), bits![0; 2]);
assert_eq!(it.next().unwrap(), bits![]);
assert!(it.next().is_none());
Returns an iterator over mutable subslices separated by bits that match
pred
, starting at the end of the slice and working backwards. The
matched bit is not contained in the subslices.
Original
API Differences
In order to allow more than one bit of information for the split decision, the predicate receives the index of each bit, as well as its value.
This iterator marks each yielded item as aliased, as iterators can be
used to yield multiple items into the same scope. If you are using
the iterator in a manner that ensures that all yielded items have
disjoint lifetimes, you can use the .remove_alias()
adapter on it to
remove the alias marker from the yielded subslices.
Examples
use bitvec::prelude::*;
let v = bits![mut 0, 0, 1, 0, 1, 0];
for group in v.rsplit_mut(|_pos, bit| *bit) {
group.set(0, true);
}
assert_eq!(v, bits![1, 0, 1, 1, 1, 1]);
Returns an iterator over subslices separated by bits that match pred
,
limited to returning at most n
items. The matched bit is not contained
in the subslices.
The last item returned, if any, will contain the remainder of the slice.
Original
API Differences
In order to allow more than one bit of information for the split decision, the predicate receives the index of each bit, as well as its value.
Examples
Print the slice split once by set bits (i.e., [0, 0,]
, [0, 1, 0]
):
use bitvec::prelude::*;
let v = bits![0, 0, 1, 0, 1, 0];
for group in v.splitn(2, |_pos, bit| *bit) {
println!("{:b}", group);
}
Returns an iterator over subslices separated by bits that match pred
,
limited to returning at most n
items. The matched bit is not contained
in the subslices.
The last item returned, if any, will contain the remainder of the slice.
Original
API Differences
In order to allow more than one bit of information for the split decision, the predicate receives the index of each bit, as well as its value.
This iterator marks each yielded item as aliased, as iterators can be
used to yield multiple items into the same scope. If you are using
the iterator in a manner that ensures that all yielded items have
disjoint lifetimes, you can use the .remove_alias()
adapter on it to
remove the alias marker from the yielded subslices.
Examples
use bitvec::prelude::*;
let v = bits![mut 0, 0, 1, 0, 1, 0];
for group in v.splitn_mut(2, |_pos, bit| *bit) {
group.set(0, true);
}
assert_eq!(v, bits![1, 0, 1, 1, 1, 0]);
Returns an iterator over subslices separated by bits that match pred
,
limited to returning at most n
items. This starts at the end of the
slice and works backwards. The matched bit is not contained in the
subslices.
The last item returned, if any, will contain the remainder of the slice.
Original
API Differences
In order to allow more than one bit of information for the split decision, the predicate receives the index of each bit, as well as its value.
Examples
Print the slice split once, starting from the end, by set bits (i.e.,
[0]
, [0, 0, 1, 0]
):
use bitvec::prelude::*;
let v = bits![0, 0, 1, 0, 1, 0];
for group in v.rsplitn(2, |_pos, bit| *bit) {
println!("{:b}", group);
}
pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, O, T, F>ⓘ where
F: FnMut(usize, &bool) -> bool,
pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, O, T, F>ⓘ where
F: FnMut(usize, &bool) -> bool,
Returns an iterator over subslices separated by bits that match pred
,
limited to returning at most n
items. This starts at the end of the
slice and works backwards. The matched bit is not contained in the
subslices.
The last item returned, if any, will contain the remainder of the slice.
Original
API Differences
In order to allow more than one bit of information for the split decision, the predicate receives the index of each bit, as well as its value.
This iterator marks each yielded item as aliased, as iterators can be
used to yield multiple items into the same scope. If you are using
the iterator in a manner that ensures that all yielded items have
disjoint lifetimes, you can use the .remove_alias()
adapter on it to
remove the alias marker from the yielded subslices.
Examples
use bitvec::prelude::*;
let v = bits![mut 0, 0, 1, 0, 1, 0];
for group in v.rsplitn_mut(2, |_pos, bit| *bit) {
group.set(0, true);
}
assert_eq!(v, bits![1, 0, 1, 0, 1, 1]);
Returns true
if the slice contains a subslice that matches the given
span.
Original
API Differences
This searches for a matching subslice (allowing different type
parameters) rather than for a specific bit. Searching for a contained
element with a given value is not as useful on a collection of bool
.
Furthermore, BitSlice
defines any
and not_all
, which are
optimized searchers for any true
or false
bit, respectively, in a
sequence.
Examples
use bitvec::prelude::*;
let data = 0b0101_1010u8;
let bits_msb = data.view_bits::<Msb0>();
let bits_lsb = data.view_bits::<Lsb0>();
assert!(bits_msb.contains(&bits_lsb[1 .. 5]));
This example uses a palindrome pattern to demonstrate that the slice being searched for does not need to have the same type parameters as the slice being searched.
Returns true
if needle
is a prefix of the slice.
Original
Examples
use bitvec::prelude::*;
let v = bits![0, 1, 0, 0];
assert!(v.starts_with(bits![0]));
assert!(v.starts_with(bits![0, 1]));
assert!(!v.starts_with(bits![1]));
assert!(!v.starts_with(bits![1, 0]));
Always returns true
if needle
is an empty slice:
use bitvec::prelude::*;
let v = bits![0, 1, 0];
assert!(v.starts_with(bits![]));
let v = bits![];
assert!(v.starts_with(bits![]));
Returns true
if needle
is a suffix of the slice.
Original
Examples
use bitvec::prelude::*;
let v = bits![0, 1, 0, 0];
assert!(v.ends_with(bits![0]));
assert!(v.ends_with(bits![0; 2]));
assert!(!v.ends_with(bits![1]));
assert!(!v.ends_with(bits![1, 0]));
Always returns true
if needle
is an empty slice:
use bitvec::prelude::*;
let v = bits![0, 1, 0];
assert!(v.ends_with(bits![]));
let v = bits![];
assert!(v.ends_with(bits![]));
Rotates the slice in-place such that the first by
bits of the slice
move to the end while the last self.len() - by
bits move to the
front. After calling .rotate_left()
, the bit previously at index by
will become the first bit in the slice.
Original
Panics
This function will panic if by
is greater than the length of the
slice. Note that by == self.len()
does not panic and is a noöp.
Complexity
Takes linear (in self.len()
) time.
Examples
use bitvec::prelude::*;
let a = bits![mut 0, 0, 1, 0, 1, 0];
a.rotate_left(2);
assert_eq!(a, bits![1, 0, 1, 0, 0, 0]);
Rotating a subslice:
use bitvec::prelude::*;
let a = bits![mut 0, 0, 1, 0, 1, 1];
a[1 .. 5].rotate_left(1);
assert_eq!(a, bits![0, 1, 0, 1, 0, 1]);
Rotates the slice in-place such that the first self.len() - by
bits of
the slice move to the end while the last by
bits move to the front.
After calling .rotate_right()
, the bit previously at index `self.len()
- by` will become the first bit in the slice.
Original
Panics
This function will panic if by
is greater than the length of the
slice. Note that by == self.len()
does not panic and is a noöp.
Complexity
Takes linear (in self.len()
) time.
Examples
use bitvec::prelude::*;
let a = bits![mut 0, 0, 1, 1, 1, 0];
a.rotate_right(2);
assert_eq!(a, bits![1, 0, 0, 0, 1, 1]);
Rotating a subslice:
use bitvec::prelude::*;
let a = bits![mut 0, 0, 1, 0, 1, 1];
a[1 .. 5].rotate_right(1);
assert_eq!(a, bits![0, 1, 0, 1, 0, 1]);
Copies bits from one part of the slice to another part of itself.
src
is the range within self
to copy from. dest
is the starting
index of the range within self
to copy to, which will have the same
length as src
. The two ranges may overlap. The ends of the two ranges
must be less than or equal to self.len()
.
Original
Panics
This function will panic if either range exceeds the end of the slice,
or if the end of src
is before the start.
Examples
Copying four bits within a slice:
use bitvec::prelude::*;
let bits = bits![mut 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0];
bits.copy_within(1 .. 5, 8);
assert_eq!(bits, bits![1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0]);
Transmute the bit-slice to a bit-slice of another type, ensuring alignment of the types is maintained.
Original
API Differences
Type U
is required to have the same BitStore
type family as
type T
. If T
is a fundamental integer, so must U
be; if T
is an
::Alias
type, then so must U
. Changing the type family with this
method is unsound and strictly forbidden. Unfortunately, this cannot
be encoded in the type system, so you are required to abide by this
limitation yourself.
Implementation
The algorithm used to implement this function attempts to create the
widest possible span for the middle slice. However, the slice divisions
must abide by the Domain
restrictions: the left and right slices
produced by this function will include the head and tail elements of the
domain (if present), as well as the left and right subslices (if any)
produced by calling slice::align_to
on the domain body (if present).
The standard library implementation currently maximizes the width of the center slice, but its API does not guarantee this property, and retains the right to produce pessimal slices. As such, this function cannot guarantee maximal center slice width either, and you cannot rely on this behavior for correctness of your work; it is only a possible performance improvement.
Safety
This method is essentially a mem::transmute
with respect to the
memory region in the retured middle slice, so all of the usual caveats
pertaining to mem::transmute::<T, U>
also apply here.
Examples
Basic usage:
use bitvec::prelude::*;
unsafe {
let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
let bits = bytes.view_bits::<LocalBits>();
let (prefix, shorts, suffix) = bits.align_to::<u16>();
match prefix.len() {
0 => {
assert_eq!(shorts, bits[.. 48]);
assert_eq!(suffix, bits[48 ..]);
},
8 => {
assert_eq!(prefix, bits[.. 8]);
assert_eq!(shorts, bits[8 ..]);
},
_ => unreachable!("This case will not occur")
}
}
Transmute the bit-slice to a bit-slice of another type, ensuring alignment of the types is maintained.
Original
API Differences
Type U
is required to have the same BitStore
type family as
type T
. If T
is a fundamental integer, so must U
be; if T
is an
::Alias
type, then so must U
. Changing the type family with this
method is unsound and strictly forbidden. Unfortunately, this cannot
be encoded in the type system, so you are required to abide by this
limitation yourself.
Implementation
The algorithm used to implement this function attempts to create the
widest possible span for the middle slice. However, the slice divisions
must abide by the DomainMut
restrictions: the left and right slices
produced by this function will include the head and tail elements of the
domain (if present), as well as the left and right subslices (if any)
produced by calling slice::align_to_mut
on the domain body (if
present).
The standard library implementation currently maximizes the width of the center slice, but its API does not guarantee this property, and retains the right to produce pessimal slices. As such, this function cannot guarantee maximal center slice width either, and you cannot rely on this behavior for correctness of your work; it is only a possible performance improvement.
Safety
This method is essentially a mem::transmute
with respect to the
memory region in the retured middle slice, so all of the usual caveats
pertaining to mem::transmute::<T, U>
also apply here.
Examples
Basic usage:
use bitvec::prelude::*;
unsafe {
let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
let bits = bytes.view_bits_mut::<LocalBits>();
let (prefix, shorts, suffix) = bits.align_to_mut::<u16>();
// same access and behavior as in `align_to`
}
Creates a vector by repeating a slice n
times.
Original
Panics
This function will panic if the capacity would overflow.
Examples
Basic usage:
use bitvec::prelude::*;
assert_eq!(bits![0, 1].repeat(3), bits![0, 1, 0, 1, 0, 1]);
A panic upon overflow:
use bitvec::prelude::*;
// this will panic at runtime
bits![0, 1].repeat(BitSlice::<LocalBits, usize>::MAX_BITS);
Writes a new bit at a given index.
Parameters
&mut self
index
: The bit index at which to write. It must be in the range0 .. self.len()
.value
: The value to be written;true
for1
orfalse
for0
.
Effects
If index
is valid, then the bit to which it refers is set to value
.
Panics
This method panics if index
is not less than self.len()
.
Examples
use bitvec::prelude::*;
let bits = bits![mut 0];
assert!(!bits[0]);
bits.set(0, true);
assert!(bits[0]);
This example panics when it attempts to set a bit that is out of bounds.
use bitvec::prelude::*;
let bits = bits![mut 0];
bits.set(1, false);
Writes a new bit at a given index.
This method supports writing through a shared reference to a bit that
may be observed by other BitSlice
handles. It is only present when the
T
type parameter supports such shared mutation (measured by the
Radium
trait).
Parameters
&self
index
: The bit index at which to write. It must be in the range0 .. self.len()
.value
: The value to be written;true
for1
orfalse
for0
.
Effects
If index
is valid, then the bit to which it refers is set to value
.
If T
is an atomic, this will lock the memory bus for the referent
address, and may cause stalls.
Panics
This method panics if index
is not less than self.len()
.
Examples
use bitvec::prelude::*;
use core::cell::Cell;
let byte = Cell::new(0u8);
let bits = byte.view_bits::<Msb0>();
let bits_2 = bits;
bits.set_aliased(1, true);
assert!(bits_2[1]);
This example panics when it attempts to set a bit that is out of bounds.
use bitvec::prelude::*;
use core::cell::Cell;
let byte = Cell::new(0u8);
let bits = byte.view_bits::<Lsb0>();
bits.set_aliased(8, false);
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 = bits![0, 1, 0, 0];
assert!(bits[.. 2].any());
assert!(!bits[2 ..].any());
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 = bits![1, 1, 0, 1];
assert!(bits[.. 2].all());
assert!(!bits[2 ..].all());
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 = bits![0, 1, 0, 0];
assert!(!bits[.. 2].not_any());
assert!(bits[2 ..].not_any());
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 = bits![1, 1, 0, 1];
assert!(!bits[.. 2].not_all());
assert!(bits[2 ..].not_all());
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 data = 0b111_000_10u8;
let bits = bits![1, 1, 0, 0, 1, 0];
assert!(!bits[.. 2].some());
assert!(!bits[2 .. 4].some());
assert!(bits.some());
Counts the number of bits set to 1
in the slice contents.
Parameters
&self
Returns
The number of bits in the slice domain that are set to 1
.
Examples
Basic usage:
use bitvec::prelude::*;
let bits = bits![1, 1, 0, 0];
assert_eq!(bits[.. 2].count_ones(), 2);
assert_eq!(bits[2 ..].count_ones(), 0);
Counts the number of bits cleared to 0
in the slice contents.
Parameters
&self
Returns
The number of bits in the slice domain that are cleared to 0
.
Examples
Basic usage:
use bitvec::prelude::*;
let bits = bits![1, 1, 0, 0];
assert_eq!(bits[.. 2].count_zeros(), 0);
assert_eq!(bits[2 ..].count_zeros(), 2);
Enumerates all bits in a BitSlice
that are set to 1
.
Examples
use bitvec::prelude::*;
let bits = bits![0, 1, 0, 0, 1, 0, 0, 0, 1];
let mut indices = [1, 4, 8].iter().copied();
let mut iter_ones = bits.iter_ones();
let mut compose = bits.iter()
.copied()
.enumerate()
.filter_map(|(idx, bit)| if bit { Some(idx) } else { None });
for ((a, b), c) in iter_ones.zip(compose).zip(indices) {
assert_eq!(a, b);
assert_eq!(b, c);
}
Enumerates all bits in a BitSlice
that are cleared to 0
.
Examples
use bitvec::prelude::*;
let bits = bits![1, 0, 1, 1, 0, 1, 1, 1, 0];
let mut indices = [1, 4, 8].iter().copied();
let mut iter_zeros = bits.iter_zeros();
let mut compose = bits.iter()
.copied()
.enumerate()
.filter_map(|(idx, bit)| if !bit { Some(idx) } else { None });
for ((a, b), c) in iter_zeros.zip(compose).zip(indices) {
assert_eq!(a, b);
assert_eq!(b, c);
}
Gets the index of the first bit in the bit-slice set to 1
.
Examples
use bitvec::prelude::*;
assert!(bits![].first_one().is_none());
assert_eq!(bits![0, 0, 1].first_one().unwrap(), 2);
Gets the index of the first bit in the bit-slice set to 0
.
Examples
use bitvec::prelude::*;
assert!(bits![].first_zero().is_none());
assert_eq!(bits![1, 1, 0].first_zero().unwrap(), 2);
Gets the index of the last bit in the bit-slice set to 1
.
Examples
use bitvec::prelude::*;
assert!(bits![].last_one().is_none());
assert_eq!(bits![1, 0, 0, 1].last_one().unwrap(), 3);
Gets the index of the last bit in the bit-slice set to 0
.
Examples
use bitvec::prelude::*;
assert!(bits![].last_zero().is_none());
assert_eq!(bits![0, 1, 1, 0].last_zero().unwrap(), 3);
Counts the number of bits from the start of the bit-slice to the first
bit set to 0
.
This returns 0
if the bit-slice is empty.
Examples
use bitvec::prelude::*;
assert_eq!(bits![].leading_ones(), 0);
assert_eq!(bits![0].leading_ones(), 0);
assert_eq!(bits![1, 0, 1, 1].leading_ones(), 1);
assert_eq!(bits![1, 1, 1, 1].leading_ones(), 4);
Counts the number of bits from the start of the bit-slice to the first
bit set to 1
.
This returns 0
if the bit-slice is empty.
Examples
use bitvec::prelude::*;
assert_eq!(bits![].leading_zeros(), 0);
assert_eq!(bits![1].leading_zeros(), 0);
assert_eq!(bits![0, 1, 0, 0].leading_zeros(), 1);
assert_eq!(bits![0, 0, 0, 0].leading_zeros(), 4);
Counts the number of bits from the end of the bit-slice to the last bit
set to 0
.
This returns 0
if the bit-slice is empty.
Examples
use bitvec::prelude::*;
assert_eq!(bits![].trailing_ones(), 0);
assert_eq!(bits![0].trailing_ones(), 0);
assert_eq!(bits![1, 0, 1, 1].trailing_ones(), 2);
Counts the number of bits from the end of the bit-slice to the last bit
set to 1
.
This returns 0
if the bit-slice is empty.
Examples
use bitvec::prelude::*;
assert_eq!(bits![].trailing_zeros(), 0);
assert_eq!(bits![1].trailing_zeros(), 0);
assert_eq!(bits![0, 1, 0, 0].trailing_zeros(), 2);
pub fn clone_from_bitslice<O2, T2>(&mut self, src: &BitSlice<O2, T2>) where
O2: BitOrder,
T2: BitStore,
pub fn clone_from_bitslice<O2, T2>(&mut self, src: &BitSlice<O2, T2>) where
O2: BitOrder,
T2: BitStore,
Copies the bits from src
into self
.
The length of src
must be the same as `self.
If src
has the same type arguments as self
, it can be more
performant to use .copy_from_bitslice()
.
Original
API Differences
This method is renamed, as it takes a bit slice rather than an element slice.
Panics
This function will panic if the two slices have different lengths.
Examples
Cloning two bits from a slice into another:
use bitvec::prelude::*;
let src = bits![Msb0, u16; 1; 4];
let dst = bits![mut Lsb0, u8; 0; 2];
dst.clone_from_bitslice(&src[2 ..]);
assert_eq!(dst, bits![1; 2]);
Rust enforces that there can only be one mutable reference with no immutable references to a particular piece of data in a particular scope. Because of this, attempting to use clone_from_slice on a single slice will result in a compile failure:
use bitvec::prelude::*;
let slice = bits![mut 0, 0, 0, 1, 1];
slice[.. 2].clone_from_bitslice(&slice[3 ..]); // compile fail!
To work around this, we can use .split_at_mut()
to create two
distinct sub-slices from a slice:
use bitvec::prelude::*;
let slice = bits![mut 0, 0, 0, 1, 1];
{
let (left, right) = slice.split_at_mut(2);
left.clone_from_bitslice(&right[1 ..]);
}
assert_eq!(slice, bits![1, 1, 0, 1, 1]);
Performance
If self
and src
use the same type arguments, this specializes to
.copy_from_bitslice()
; if you know statically that this is the case,
prefer to call that method directly and avoid the cost of detection at
runtime. Otherwise, this is a bit-by-bit crawl across both slices, which
is a slow process.
Copies all bits from src
into self
, using a memcpy wherever
possible.
The length of src
must be same as self
.
If src
does not use the same type arguments as self
, use
.clone_from_bitslice()
.
Original
API Differences
This method is renamed, as it takes a bit slice rather than an element slice.
Panics
This function will panic if the two slices have different lengths.
Examples
Copying two bits from a slice into another:
use bitvec::prelude::*;
let src = bits![1; 4];
let dst = bits![mut 0; 2];
// Because the slices have to be the same length,
// we slice the source slice from four bits to
// two. It will panic if we don't do this.
dst.clone_from_bitslice(&src[2..]);
Rust enforces that there can only be one mutable reference with no immutable references to a particular piece of data in a particular scope. Because of this, attempting to use [.copy_from_slice()] on a single slice will result in a compile failure:
use bitvec::prelude::*;
let slice = bits![mut 0, 0, 0, 1, 1];
slice[.. 2].copy_from_bitslice(&bits[3 ..]); // compile fail!
To work around this, we can use .split_at_mut()
to create two
distinct sub-slices from a slice:
use bitvec::prelude::*;
let slice = bits![mut 0, 0, 0, 1, 1];
{
let (left, right) = slice.split_at_mut(2);
left.copy_from_bitslice(&right[1 ..]);
}
assert_eq!(slice, bits![1, 1, 0, 1, 1]);
pub fn swap_with_bitslice<O2, T2>(&mut self, other: &mut BitSlice<O2, T2>) where
O2: BitOrder,
T2: BitStore,
pub fn swap_with_bitslice<O2, T2>(&mut self, other: &mut BitSlice<O2, T2>) where
O2: BitOrder,
T2: BitStore,
Swaps all bits in self
with those in other
.
The length of other
must be the same as self
.
Original
API Differences
This method is renamed, as it takes a bit slice rather than an element slice.
Panics
This function will panic if the two slices have different lengths.
Examples
use bitvec::prelude::*;
let mut one = [0xA5u8, 0x69];
let mut two = 0x1234u16;
let one_bits = one.view_bits_mut::<Msb0>();
let two_bits = two.view_bits_mut::<Lsb0>();
one_bits.swap_with_bitslice(two_bits);
assert_eq!(one, [0x2C, 0x48]);
assert_eq!(two, 0x96A5);
Shifts the contents of a bit-slice left (towards index 0
).
This moves the contents of the slice from by ..
down to
0 .. len - by
, and erases len - by ..
to 0
. As this is a
destructive (and linearly expensive) operation, you may prefer instead
to use range subslicing.
Parameters
&mut self
by
: The distance by which to shift the slice contents.
Panics
This panics if by
is not less than self.len()
.
Examples
use bitvec::prelude::*;
let bits = bits![mut 1; 6];
bits.shift_left(2);
assert_eq!(bits, bits![1, 1, 1, 1, 0, 0]);
Shifts the contents of a bit-slice right (towards index self.len()
).
This moves the contents of the slice from .. len - by
up to by ..
,
and erases .. by
to 0
. As this is a destructive (and linearly
expensive) operation, you may prefer instead to use range subslicing.
Parameters
&mut self
by
: The distance by which to shift the slice contents.
Panics
This panics if by
is not less than self.len()
.
Examples
use bitvec::prelude::*;
let bits = bits![mut 1; 6];
bits.shift_right(2);
assert_eq!(bits, bits![0, 0, 1, 1, 1, 1]);
Sets 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.view_bits_mut::<Msb0>();
bits[2 .. 6].set_all(true);
assert_eq!(bits.as_slice(), &[0b0011_1100]);
bits[3 .. 5].set_all(false);
assert_eq!(bits.as_slice(), &[0b0010_0100]);
bits[.. 1].set_all(true);
assert_eq!(bits.as_slice(), &[0b1010_0100]);
Applies a function to each bit in the slice.
BitSlice
cannot implement IndexMut
, as it cannot manifest &mut bool
references, and the BitRef
proxy reference has an unavoidable
overhead. This method bypasses both problems, by applying a function to
each pair of index and value in the slice, without constructing a proxy
reference. Benchmarks indicate that this method is about 2–4 times
faster than the .iter_mut().enumerate()
equivalent.
Parameters
&mut self
func
: A function which receives two arguments,index: usize
andvalue: bool
, and returns abool
.
Effects
For each index in the slice, the result of invoking func
with the
index number and current bit value is written into the slice.
Examples
use bitvec::prelude::*;
let mut data = 0u8;
let bits = data.view_bits_mut::<Msb0>();
bits.for_each(|idx, _bit| idx % 3 == 0);
assert_eq!(data, 0b100_100_10);
Produces the absolute offset in bits between two slice heads.
While this method is sound for any two arbitrary bit slices, the answer it produces is meaningful only when one argument is a strict subslice of the other. If the two slices are created from different buffers entirely, a comparison is undefined; if the two slices are disjoint regions of the same buffer, then the semantically correct distance is between the tail of the lower and the head of the upper, which this does not measure.
Visual Description
Consider the following sequence of bits:
[ 0 1 2 3 4 5 6 7 8 9 a b ]
| ^^^^^^^ |
^^^^^^^^^^^^^^^^^^^^^^^
It does not matter whether there are bits between the tail of the smaller and the larger slices. The offset is computed from the bit distance between the two heads.
Behavior
This function computes the semantic distance between the heads, rather
than the *electrical. It does not take into account the BitOrder
implementation of the slice.
Safety and Soundness
One of self
or other
must contain the other for this comparison to
be meaningful.
Parameters
&self
other
: Another bit slice. This must be either a strict subregion or a strict superregion ofself
.
Returns
The distance in (semantic) bits betwen the heads of each region. The
value is positive when other
is higher in the address space than
self
, and negative when other
is lower in the address space than
self
.
Writes a new bit at a given index, without doing bounds checking.
This is generally not recommended; use with caution! Calling this method
with an out-of-bounds index is undefined behavior. For a safe
alternative, see .set()
.
Parameters
&mut self
index
: The bit index at which to write. It must be in the range0 .. self.len()
.value
: The value to be written;true
for1
orfalse
for0
.
Effects
The bit at index
is set to value
. If index
is out of bounds, then
the memory access is incorrect, and its behavior is unspecified.
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 bits = bits![mut 0; 2];
let (first, _) = bits.split_at_mut(1);
unsafe {
first.set_unchecked(1, true);
}
assert_eq!(bits, bits![0, 1]);
Writes a new bit at a given index, without doing bounds checking.
This method supports writing through a shared reference to a bit that
may be observed by other BitSlice
handles. It is only present when the
T
type parameter supports such shared mutation (measured by the
Radium
trait).
Effects
The bit at index
is set to value
. If index
is out of bounds, then
the memory access is incorrect, and its behavior is unspecified. If T
is an atomic, this will lock the memory bus for the referent
address, and may cause stalls.
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
use bitvec::prelude::*;
use core::cell::Cell;
let byte = Cell::new(0u8);
let bits = byte.view_bits::<Msb0>();
let bits_2 = bits;
let (first, _) = bits.split_at(1);
assert_eq!(first.len(), 1);
unsafe { first.set_aliased_unchecked(2, true); }
assert!(bits_2[2]);
Divides one slice into two at an index, without performing any bounds checking.
See .split_at()
.
Safety
mid
must not be greater than self.len()
. If this condition is
violated, the function behavior is unspecified.
Examples
use bitvec::prelude::*;
let bits = bits![0, 0, 0, 1, 1, 1];
let (l, r) = unsafe { bits.split_at_unchecked(3) };
assert!(l.not_any());
assert!(r.all());
let (l, r) = unsafe { bits.split_at_unchecked(6) };
assert_eq!(l, bits);
assert!(r.is_empty());
Divides one mutable slice into two at an index.
See .split_at_mut()
.
Safety
mid
must not be greater than self.len()
.
pub unsafe fn copy_within_unchecked<R>(&mut self, src: R, dest: usize) where
R: RangeBounds<usize>,
pub unsafe fn copy_within_unchecked<R>(&mut self, src: R, dest: usize) where
R: RangeBounds<usize>,
Copies bits from one part of the slice to another part of itself, without doing bounds checks.
The ranges are allowed to overlap.
Parameters
&mut self
src
: The range withinself
from which to copy.dst
: The starting index withinself
at which to paste.
Effects
self[src]
is copied to self[dest .. dest + src.end() - src.start()]
.
Safety
src
and dest .. dest + src.len()
must be entirely within
self.len()
.
Returns a raw bit-pointer to the base of the bit-slice’s region.
The caller must ensure that the bit-slice outlives the bit-pointer this function returns, or else it will end up pointing to garbage.
The caller must also ensure that the memory the bit-pointer
(non-transitively) points to is never written to using this bit-pointer
or any bit-pointer derived from it. If you need to mutate the contents
of the slice, use .as_mut_bitptr()
.
Modifying the container referenced by this bit-slice may cause its buffer to be reällocated, which would also make any bit-pointers to it invalid.
Original
API Differences
This returns a structure, BitPtr
, rather than an actual raw pointer
*Bit
. The information required to address a bit within a memory
element cannot be encoded into a single pointer.
This structure can be converted back into a &BitSlice
with the
function from_raw_parts
.
Examples
use bitvec::prelude::*;
let x = bits![0, 0, 1];
let x_ptr = x.as_ptr();
unsafe {
for i in 0 .. x.len() {
assert_eq!(*x.get_unchecked(i), (&*x)[i]);
}
}
Returns an unsafe mutable bit-pointer to the bit-slice’s region.
The caller must ensure that the bit-slice outlives the bit-pointer this function returns, or else it will end up pointing to garbage.
Modifying the container referenced by this bit-slice may cause its buffer to be reällocated, which would also make any bit-pointers to it invalid.
Original
API Differences
This returns *mut BitSlice
, which is the equivalont of *mut [T]
instead of *mut T
. The pointer encoding used requires more than one
CPU word of space to address a single bit, so there is no advantage to
removing the length information from the encoded pointer value.
Examples
use bitvec::prelude::*;
let bits = bits![mut Lsb0, u8; 0; 8];
let bits_ptr = bits.as_mut_ptr();
for i in 0 .. bits.len() {
unsafe {
bits_ptr.add(i).write(i % 3 == 0);
}
}
assert_eq!(bits.as_slice()[0], 0b0100_1001);
pub fn as_bitptr_range(&self) -> BitPtrRange<Const, O, T>ⓘNotable traits for BitPtrRange<M, O, T>impl<M, O, T> Iterator for BitPtrRange<M, O, T> where
M: Mutability,
O: BitOrder,
T: BitStore, type Item = BitPtr<M, O, T>;
pub fn as_bitptr_range(&self) -> BitPtrRange<Const, O, T>ⓘNotable traits for BitPtrRange<M, O, T>impl<M, O, T> Iterator for BitPtrRange<M, O, T> where
M: Mutability,
O: BitOrder,
T: BitStore, type Item = BitPtr<M, O, T>;
impl<M, O, T> Iterator for BitPtrRange<M, O, T> where
M: Mutability,
O: BitOrder,
T: BitStore, type Item = BitPtr<M, O, T>;
Returns the two raw bit-pointers spanning the bit-slice.
The returned range is half-open, which means that the end bit-pointer points one past the last bit of the bit-slice. This way, an empty bit-slice is represented by two equal bit-pointers, and the difference between the two bit-pointers represents the size of the bit-slice.
See as_bitptr
for warnings on using these bit-pointers. The end
bit-pointer requires extra caution, as it does not point to a valid bit
in the bit-slice.
This function allows a more direct access to bit-pointers, without
paying the cost of encoding into a *BitSlice
, at the cost of no longer
fitting into ordinary Rust interfaces.
Original
API Differences
This returns a dedicated structure, rather than a range of BitPtr
s,
because the traits needed for non-core
types to correctly operate in
ranges are still unstable. The structure can be converted into a range,
but that range will not be an iterator.
Examples
use bitvec::prelude::*;
let bits = bits![0, 1, 0, 0, 1];
let mid_ptr = bits.get(2).unwrap().into_bitptr();
let mut range = bits.as_bitptr_range();
assert!(range.contains(&mid_ptr));
unsafe {
assert!(!range.next().unwrap().read());
assert!(range.next_back().unwrap().read())
}
pub fn as_mut_bitptr_range(&mut self) -> BitPtrRange<Mut, O, T>ⓘNotable traits for BitPtrRange<M, O, T>impl<M, O, T> Iterator for BitPtrRange<M, O, T> where
M: Mutability,
O: BitOrder,
T: BitStore, type Item = BitPtr<M, O, T>;
pub fn as_mut_bitptr_range(&mut self) -> BitPtrRange<Mut, O, T>ⓘNotable traits for BitPtrRange<M, O, T>impl<M, O, T> Iterator for BitPtrRange<M, O, T> where
M: Mutability,
O: BitOrder,
T: BitStore, type Item = BitPtr<M, O, T>;
impl<M, O, T> Iterator for BitPtrRange<M, O, T> where
M: Mutability,
O: BitOrder,
T: BitStore, type Item = BitPtr<M, O, T>;
Returns the two unsafe mutable bit-pointers spanning the bit-slice.
The returned range is half-open, which means that the end bit-pointer points one past the last bitt of the bit-slice. This way, an empty bit-slice is represented by two equal bit-pointers, and the difference between the two bit-pointers represents the size of the bit-slice.
See as_mut_bitptr
for warnings on using these bit-pointers. The end
bit-pointer requires extra caution, as it does not point to a valid bit
in the bit-slice.
Original
API Differences
This returns a dedicated structure, rather than a range of BitPtr
s,
because the traits needed for non-core
types to correctly operate in
ranges are still unstable. The structure can be converted into a range,
but that range will not be an iterator.
Examples
use bitvec::prelude::*;
use bitvec::ptr as bv_ptr;
let mut data = 0u8;
let bits = data.view_bits_mut::<Msb0>();
for mut bitptr in bits.as_mut_bitptr_range() {
unsafe { bv_ptr::write(bitptr, true); }
}
assert_eq!(data, !0);
Splits the slice into subslices at alias boundaries.
This splits self
into the memory locations that it partially fills and
the memory locations that it completely fills. The locations that are
completely filled may be accessed without any bitvec
-imposed alias
conditions, while the locations that are only partially filled are left
unchanged.
You can read more about the BitDomain
splitting in its
documentation.
Examples
use bitvec::prelude::*;
let mut data = [0u16; 3];
let all = data.view_bits_mut::<Msb0>();
let (_, rest) = all.split_at_mut(8);
let bits: &BitSlice<Msb0, <u16 as BitStore>::Alias> = &rest[.. 32];
let (head, body, tail) = bits
.bit_domain()
.region()
.unwrap();
assert_eq!(head.len(), 8);
assert_eq!(tail.len(), 8);
let _: &BitSlice<Msb0, <u16 as BitStore>::Alias> = head;
let _: &BitSlice<Msb0, <u16 as BitStore>::Alias> = tail;
let _: &BitSlice<Msb0, u16> = body;
Splits the slice into subslices at alias boundaries.
This splits self
into the memory locations that it partially fills and
the memory locations that it completely fills. The locations that are
completely filled may be accessed without any bitvec
-imposed alias
conditions, while the locations that are only partially filled are left
unchanged.
You can read more about the BitDomainMut
splitting in its
documentation.
Examples
use bitvec::prelude::*;
let mut data = [0u16; 3];
let all = data.view_bits_mut::<Msb0>();
let (_, rest) = all.split_at_mut(8);
let bits: &mut BitSlice<Msb0, <u16 as BitStore>::Alias>
= &mut rest[.. 32];
let (head, body, tail) = bits
.bit_domain_mut()
.region()
.unwrap();
assert_eq!(head.len(), 8);
assert_eq!(tail.len(), 8);
let _: &mut BitSlice<Msb0, <u16 as BitStore>::Alias> = head;
let _: &mut BitSlice<Msb0, <u16 as BitStore>::Alias> = tail;
let _: &mut BitSlice<Msb0, u16> = body;
Views the underlying memory containing the slice, split at alias boundaries.
This splits self
into the memory locations that it partially fills and
the memory locatinos that it completely fills. The locations that are
completely filled may be accessed without any bitvec
-imposed alias
conditions, while the locations that are only partially filled are left
unchanged.
You can read more about the Domain
splitting in its documentation.
Examples
use bitvec::prelude::*;
let mut data = [0u16; 3];
let all = data.view_bits_mut::<Msb0>();
let (_, rest) = all.split_at_mut(8);
let bits: &BitSlice<Msb0, <u16 as BitStore>::Alias> = &rest[.. 32];
let (head, body, tail) = bits
.domain()
.region()
.unwrap();
assert_eq!(body.len(), 1);
let _: &<u16 as BitStore>::Alias = head.unwrap().1;
let _: &<u16 as BitStore>::Alias = tail.unwrap().0;
let _: &[u16] = body;
Views the underlying memory containing the slice, split at alias boundaries.
This splits self
into the memory locations that it partially fills and
the memory locations that it completely fills. The locations that are
completely filled may be accessed without any bitvec
-imposed alias
conditions, while the locations that are only partially filled are left
unchanged.
You can read more about the DomainMut
splitting in its
documentation.
Examples
use bitvec::prelude::*;
let mut data = [0u16; 3];
let all = data.view_bits_mut::<Msb0>();
let (_, rest) = all.split_at_mut(8);
let bits: &mut BitSlice<Msb0, <u16 as BitStore>::Alias> = &mut rest[.. 32];
let (head, body, tail) = bits
.domain_mut()
.region()
.unwrap();
assert_eq!(body.len(), 1);
let _: &<<u16 as BitStore>::Alias as BitStore>::Access = head.unwrap().1;
let _: &<<u16 as BitStore>::Alias as BitStore>::Access = tail.unwrap().0;
let _: &mut [u16] = body;
Views the underlying memory containing the slice.
The returned slice handle views all elements touched by self
, and
marks them all with self
’s current aliasing state. For a more precise
view, or one that permits mutation, use .domain()
or
.domain_mut()
.
Splits a mutable slice at some mid-point.
This method has the same behavior as .split_at_mut()
, except that it
does not apply an aliasing marker to the partitioned subslices.
Safety
Because this method is defined only on BitSlice
s whose T
type is
alias-safe, the subslices do not need to be additionally marked.
Trait Implementations
Performs the conversion.
Performs the conversion.
impl<O, T, Rhs> BitAndAssign<Rhs> for BitVec<O, T> where
O: BitOrder,
T: BitStore,
BitSlice<O, T>: BitAndAssign<Rhs>,
impl<O, T, Rhs> BitAndAssign<Rhs> for BitVec<O, T> where
O: BitOrder,
T: BitStore,
BitSlice<O, T>: BitAndAssign<Rhs>,
Performs the &=
operation. Read more
Loads from self
, using little-endian element T
ordering. Read more
Loads from self
, using big-endian element T
ordering. Read more
Stores into self
, using little-endian element ordering. Read more
Stores into self
, using big-endian element ordering. Read more
Loads the bits in the self
region into a local value. Read more
impl<O, T, Rhs> BitOrAssign<Rhs> for BitVec<O, T> where
O: BitOrder,
T: BitStore,
BitSlice<O, T>: BitOrAssign<Rhs>,
impl<O, T, Rhs> BitOrAssign<Rhs> for BitVec<O, T> where
O: BitOrder,
T: BitStore,
BitSlice<O, T>: BitOrAssign<Rhs>,
Performs the |=
operation. Read more
impl<O, T, Rhs> BitXorAssign<Rhs> for BitVec<O, T> where
O: BitOrder,
T: BitStore,
BitSlice<O, T>: BitXorAssign<Rhs>,
impl<O, T, Rhs> BitXorAssign<Rhs> for BitVec<O, T> where
O: BitOrder,
T: BitStore,
BitSlice<O, T>: BitXorAssign<Rhs>,
Performs the ^=
operation. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Extends a collection with the contents of an iterator. Read more
extend_one
)Extends a collection with exactly one element.
extend_one
)Reserves capacity in a collection for the given number of additional elements. Read more
Extends a collection with the contents of an iterator. Read more
extend_one
)Extends a collection with exactly one element.
extend_one
)Reserves capacity in a collection for the given number of additional elements. Read more
Extends a collection with the contents of an iterator. Read more
extend_one
)Extends a collection with exactly one element.
extend_one
)Reserves capacity in a collection for the given number of additional elements. Read more
Extends a collection with the contents of an iterator. Read more
extend_one
)Extends a collection with exactly one element.
extend_one
)Reserves capacity in a collection for the given number of additional elements. Read more
Extends a collection with the contents of an iterator. Read more
extend_one
)Extends a collection with exactly one element.
extend_one
)Reserves capacity in a collection for the given number of additional elements. Read more
Creates a value from an iterator. Read more
Creates a value from an iterator. Read more
Creates a value from an iterator. Read more
Collect a sequence of memory elements into a bit-vector.
This is a short-hand for, and implemented as, iter.collect::<Vec<_>>().into()
.
This is not a standard-library API, and was added for Issue #83.
Creates a value from an iterator. Read more
Creates a value from an iterator. Read more
type IntoIter = <&'a mut BitSlice<O, T> as IntoIterator>::IntoIter
type IntoIter = <&'a mut BitSlice<O, T> as IntoIterator>::IntoIter
Which kind of iterator are we turning this into?
type Item = <&'a mut BitSlice<O, T> as IntoIterator>::Item
type Item = <&'a mut BitSlice<O, T> as IntoIterator>::Item
The type of the elements being iterated over.
This implementation inverts all elements in the live buffer. You cannot rely
on the value of bits in the buffer that are outside the domain of
BitVec::as_mit_bitslice
.
This method returns an ordering between self
and other
values if one exists. Read more
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 returns an ordering between self
and other
values if one exists. Read more
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 returns an ordering between self
and other
values if one exists. Read more
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
impl<O, T, Rhs> PartialOrd<Rhs> for BitVec<O, T> where
O: BitOrder,
T: BitStore,
Rhs: ?Sized + PartialOrd<BitSlice<O, T>>,
impl<O, T, Rhs> PartialOrd<Rhs> for BitVec<O, T> where
O: BitOrder,
T: BitStore,
Rhs: ?Sized + PartialOrd<BitSlice<O, T>>,
This method returns an ordering between self
and other
values if one exists. Read more
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
Mirrors the implementation on Vec<u8>
(found here).
The implementation copies bytes from buf
into the tail end of self
. The
performance characteristics of this operation are dependent on the type
parameters of the BitVec
, and the position of its tail.
Write a buffer into this writer, returning how many bytes were written. Read more
Flush this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
can_vector
)Determines if this Write
r has an efficient write_vectored
implementation. Read more
Attempts to write an entire buffer into this writer. Read more
write_all_vectored
)Attempts to write multiple buffers into this writer. Read more
Writes a formatted string into this writer, returning any error encountered. Read more
Auto Trait Implementations
impl<O, T> RefUnwindSafe for BitVec<O, T> where
O: RefUnwindSafe,
T: RefUnwindSafe,
impl<O, T> UnwindSafe for BitVec<O, T> where
O: UnwindSafe,
T: RefUnwindSafe,
Blanket Implementations
Mutably borrows from an owned value. Read more
Causes self
to use its Binary
implementation when Debug
-formatted.
Causes self
to use its Display
implementation when
Debug
-formatted. Read more
Causes self
to use its LowerExp
implementation when
Debug
-formatted. Read more
Causes self
to use its LowerHex
implementation when
Debug
-formatted. Read more
Causes self
to use its Octal
implementation when Debug
-formatted.
Causes self
to use its Pointer
implementation when
Debug
-formatted. Read more
Causes self
to use its UpperExp
implementation when
Debug
-formatted. Read more
Causes self
to use its UpperHex
implementation when
Debug
-formatted. Read more
Pipes by value. This is generally the method you want to use. Read more
Borrows self
and passes that borrow into the pipe function. Read more
Mutably borrows self
and passes that borrow into the pipe function. Read more
Borrows self
, then passes self.borrow()
into the pipe function. Read more
Mutably borrows self
, then passes self.borrow_mut()
into the pipe
function. Read more
Borrows self
, then passes self.as_ref()
into the pipe function.
Mutably borrows self
, then passes self.as_mut()
into the pipe
function. Read more
Borrows self
, then passes self.deref()
into the pipe function.
fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R where
Self: AsRef<T>,
T: 'a,
R: 'a,
fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R where
Self: AsRef<T>,
T: 'a,
R: 'a,
Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more
fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R where
Self: Borrow<T>,
T: 'a,
R: 'a,
fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R where
Self: Borrow<T>,
T: 'a,
R: 'a,
Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more
fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where
Self: Deref,
R: 'a,
fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where
Self: Deref,
R: 'a,
Pipes a dereference into a function that cannot normally be called in suffix position. Read more
Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more
Immutable access to the Borrow<B>
of a value. Read more
Mutable access to the BorrowMut<B>
of a value. Read more
Immutable access to the AsRef<R>
view of a value. Read more
Mutable access to the AsMut<R>
view of a value. Read more
Immutable access to the Deref::Target
of a value. Read more
Mutable access to the Deref::Target
of a value. Read more
Calls .tap()
only in debug builds, and is erased in release builds.
Calls .tap_mut()
only in debug builds, and is erased in release
builds. Read more
Calls .tap_borrow()
only in debug builds, and is erased in release
builds. Read more
Calls .tap_borrow_mut()
only in debug builds, and is erased in release
builds. Read more
Calls .tap_ref()
only in debug builds, and is erased in release
builds. Read more
Calls .tap_ref_mut()
only in debug builds, and is erased in release
builds. Read more
Calls .tap_deref()
only in debug builds, and is erased in release
builds. Read more
Provides immutable access to the reference for inspection.
Calls tap_ref
in debug builds, and does nothing in release builds.
Provides mutable access to the reference for modification.
Calls tap_ref_mut
in debug builds, and does nothing in release builds.
Provides immutable access to the borrow for inspection. Read more
Calls tap_borrow
in debug builds, and does nothing in release builds.
fn tap_borrow_mut<F, R>(self, func: F) -> Self where
Self: BorrowMut<T>,
F: FnOnce(&mut T) -> R,
fn tap_borrow_mut<F, R>(self, func: F) -> Self where
Self: BorrowMut<T>,
F: FnOnce(&mut T) -> R,
Provides mutable access to the borrow for modification.
Immutably dereferences self
for inspection.
fn tap_deref_dbg<F, R>(self, func: F) -> Self where
Self: Deref,
F: FnOnce(&Self::Target) -> R,
fn tap_deref_dbg<F, R>(self, func: F) -> Self where
Self: Deref,
F: FnOnce(&Self::Target) -> R,
Calls tap_deref
in debug builds, and does nothing in release builds.
fn tap_deref_mut<F, R>(self, func: F) -> Self where
Self: DerefMut,
F: FnOnce(&mut Self::Target) -> R,
fn tap_deref_mut<F, R>(self, func: F) -> Self where
Self: DerefMut,
F: FnOnce(&mut Self::Target) -> R,
Mutably dereferences self
for modification.