Function winnow::binary::bits::tag

source ·
pub fn tag<I, O, C, E: ParserError<(I, usize)>>(
    pattern: O,
    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> + PartialEq,
Expand description

Parse taking count bits and comparing them to pattern

§Example

use winnow::binary::bits::tag;

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

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

/// Compare the lowest `count` bits of `input` against the lowest `count` bits of `pattern`.
/// Return Ok and the matching section of `input` if there's a match.
/// Return Err if there's no match.
fn parser(pattern: u8, count: u8, input: (Stream<'_>, usize)) -> IResult<(Stream<'_>, usize), u8> {
    tag(pattern, count).parse_peek(input)
}

// The lowest 4 bits of 0b00001111 match the lowest 4 bits of 0b11111111.
assert_eq!(
    parser(0b0000_1111, 4, (stream(&[0b1111_1111]), 0)),
    Ok(((stream(&[0b1111_1111]), 4), 0b0000_1111))
);

// The lowest bit of 0b00001111 matches the lowest bit of 0b11111111 (both are 1).
assert_eq!(
    parser(0b00000001, 1, (stream(&[0b11111111]), 0)),
    Ok(((stream(&[0b11111111]), 1), 0b00000001))
);

// The lowest 2 bits of 0b11111111 and 0b00000001 are different.
assert_eq!(
    parser(0b000000_01, 2, (stream(&[0b111111_11]), 0)),
    Err(winnow::error::ErrMode::Backtrack(InputError::new(
        (stream(&[0b11111111]), 0),
        ErrorKind::Tag
    )))
);

// The lowest 8 bits of 0b11111111 and 0b11111110 are different.
assert_eq!(
    parser(0b11111110, 8, (stream(&[0b11111111]), 0)),
    Err(winnow::error::ErrMode::Backtrack(InputError::new(
        (stream(&[0b11111111]), 0),
        ErrorKind::Tag
    )))
);