winnow::binary::bits

Function 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)
}

// Consumes 0 bits, returns 0
assert_eq!(take::<_, usize, _, ContextError>(0usize).parse_peek((stream(&[0b00010010]), 0)), Ok(((stream(&[0b00010010]), 0), 0)));

// Consumes 4 bits, returns their values and increase offset to 4
assert_eq!(take::<_, usize, _, ContextError>(4usize).parse_peek((stream(&[0b00010010]), 0)), Ok(((stream(&[0b00010010]), 4), 0b00000001)));

// Consumes 4 bits, offset is 4, returns their values and increase offset to 0 of next byte
assert_eq!(take::<_, usize, _, ContextError>(4usize).parse_peek((stream(&[0b00010010]), 4)), Ok(((stream(&[]), 0), 0b00000010)));

// Tries to consume 12 bits but only 8 are available
assert!(take::<_, usize, _, ContextError>(12usize).parse_peek((stream(&[0b00010010]), 0)).is_err());