Function winnow::binary::length_count

source ·
pub fn length_count<I, O, C, N, E, F, G>(f: F, g: G) -> impl Parser<I, C, E>
where I: Stream, N: ToUsize, C: Accumulate<O>, F: Parser<I, N, E>, G: Parser<I, O, E>, E: ParserError<I>,
Expand description

Gets a number from the first parser, then applies the second parser that many times.

§Arguments

  • f The parser to apply to obtain the count.
  • g The parser to apply repeatedly.

§Example

use winnow::Bytes;
use winnow::binary::u8;
use winnow::binary::length_count;
use winnow::token::tag;

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

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

fn parser(s: Stream<'_>) -> IResult<Stream<'_>, Vec<&[u8]>> {
  length_count(u8.map(|i| {
     println!("got number: {}", i);
     i
  }), "abc").parse_peek(s)
}

assert_eq!(parser(stream(b"\x02abcabcabc")), Ok((stream(b"abc"), vec![&b"abc"[..], &b"abc"[..]])));
assert_eq!(parser(stream(b"\x03123123123")), Err(ErrMode::Backtrack(InputError::new(stream(b"123123123"), ErrorKind::Tag))));