pub fn pattern<Input, Output, Count, Error: ParserError<(Input, usize)>>(
pattern: Output,
count: Count
) -> impl Parser<(Input, usize), Output, Error>
Expand description
Parse taking count
bits and comparing them to pattern
§Effective Signature
Assuming you are parsing a (&[u8], usize)
bit Stream:
pub fn pattern<'i>(pattern: u8, count: usize) -> impl Parser<(&'i [u8], usize), u8, ContextError>
§Example
use winnow::binary::bits::pattern;
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(bits: u8, count: u8, input: (Stream<'_>, usize)) -> IResult<(Stream<'_>, usize), u8> {
pattern(bits, 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
)))
);