Function winnow::binary::bits::take

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

Parse taking count bits

§Effective Signature

Assuming you are parsing a (&[u8], usize) bit Stream:

pub fn take<'i>(count: usize) -> impl Parser<(&'i [u8], usize), u8, ContextError>

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