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: &mut (Stream<'_>, usize)) -> ModalResult<u8> {
pattern(bits, count).parse_next(input)
}
// The lowest 4 bits of 0b00001111 match the lowest 4 bits of 0b11111111.
assert_eq!(
pattern::<_, usize, _, ContextError>(0b0000_1111, 4usize).parse_peek((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!(
pattern::<_, usize, _, ContextError>(0b00000001, 1usize).parse_peek((stream(&[0b11111111]), 0)),
Ok(((stream(&[0b11111111]), 1), 0b00000001))
);
// The lowest 2 bits of 0b11111111 and 0b00000001 are different.
assert!(pattern::<_, usize, _, ContextError>(0b000000_01, 2usize).parse_peek((stream(&[0b111111_11]), 0)).is_err());
// The lowest 8 bits of 0b11111111 and 0b11111110 are different.
assert!(pattern::<_, usize, _, ContextError>(0b11111110, 8usize).parse_peek((stream(&[0b11111111]), 0)).is_err());