#bits #iterator #bit #byte-stream

biterator

A crate for iterating over individual bits in a byte stream

3 releases (breaking)

0.3.0 Jan 21, 2022
0.2.0 Jan 17, 2022
0.1.0 Jan 17, 2022

#53 in #byte-stream

MIT license

11KB
170 lines

biterator

Crates.io Documentation

This crate provides Biterator, an iterator over individual bits in a source of bytes.

Example

use biterator::{Biterator, Bit::*};

let bytes = [0b00001111, 0b10101011];
let b = Biterator::new(&bytes);

assert_eq!(
    b.collect::<Vec<_>>(),
    vec![
        Zero, Zero, Zero, Zero, One, One,  One, One,
        One,  Zero, One,  Zero, One, Zero, One, One,
    ]
);

lib.rs:

This crate provides Biterator, a type for iterating over individual bits in a stream of bytes.

Examples

use biterator::{Biterator, Bit::*};

let bytes = [0b00001111, 0b10101011];
let bits: Vec<_> = Biterator::new(&bytes).collect();

assert_eq!(
    bits,
    vec![
        Zero, Zero, Zero, Zero, One, One,  One, One,
        One,  Zero, One,  Zero, One, Zero, One, One,
    ]
);

Use it to find which bits are set in a stream:

use biterator::{Biterator, Bit, BiteratorExt};

let bytes = [0b00110101];
let set_bits: Vec<_> = bytes
    .iter()
    .bits()
    .enumerate()
    .filter(|(_, bit)| bit.is_one())
    .collect();

assert_eq!(
    set_bits,
    vec![(2, Bit::One), (3, Bit::One), (5, Bit::One), (7, Bit::One)]
);

Count the number of bits that are 0 in a buffer:

use biterator::BiteratorExt;

// There are 10 zeros here
let buf = [0b00110011, 0b11001111, 0b01010101];

let zero_bit_count = buf.iter().bits().filter(|&b| b.is_zero()).count();
assert_eq!(zero_bit_count, 10);

No runtime deps