Function winnow::binary::bits::take

source ·
pub fn take<I, O, C, E: ParserError<(I, usize)>>(
    count: C,
) -> impl Parser<(I, usize), O, E>
where I: Stream<Token = u8> + AsBytes + StreamIsPartial + Clone, C: ToUsize, O: From<u8> + AddAssign + Shl<usize, Output = O> + Shr<usize, Output = O>,
Expand description

Parse taking count bits

§Example

use winnow::binary::bits::take;

type Stream<'i> = &'i Bytes;

fn stream(b: &[u8]) -> Stream<'_> {
    Bytes::new(b)
}

fn parser(input: (Stream<'_>, usize), count: usize)-> IResult<(Stream<'_>, usize), u8> {
 take(count).parse_peek(input)
}

// Consumes 0 bits, returns 0
assert_eq!(parser((stream(&[0b00010010]), 0), 0), Ok(((stream(&[0b00010010]), 0), 0)));

// Consumes 4 bits, returns their values and increase offset to 4
assert_eq!(parser((stream(&[0b00010010]), 0), 4), Ok(((stream(&[0b00010010]), 4), 0b00000001)));

// Consumes 4 bits, offset is 4, returns their values and increase offset to 0 of next byte
assert_eq!(parser((stream(&[0b00010010]), 4), 4), Ok(((stream(&[]), 0), 0b00000010)));

// Tries to consume 12 bits but only 8 are available
assert_eq!(parser((stream(&[0b00010010]), 0), 12), Err(winnow::error::ErrMode::Backtrack(InputError::new((stream(&[0b00010010]), 0), ErrorKind::Eof))));