winnow::binary

Function length_repeat

Source
pub fn length_repeat<Input, Output, Accumulator, Count, Error, CountParser, ParseNext>(
    count: CountParser,
    parser: ParseNext,
) -> impl Parser<Input, Accumulator, Error>
where Input: Stream, Count: ToUsize, Accumulator: Accumulate<Output>, CountParser: Parser<Input, Count, Error>, ParseNext: Parser<Input, Output, Error>, Error: ParserError<Input>,
Expand description

Accumulate a length-prefixed sequence of values (TLV)

If the length represents token counts, see instead length_take

ยงExample

use winnow::Bytes;
use winnow::binary::u8;
use winnow::binary::length_repeat;

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

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

fn parser(s: Stream<'_>) -> IResult<Stream<'_>, Vec<&[u8]>> {
  length_repeat(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))));