Function winnow::binary::length_data

source ·
pub fn length_data<I, N, E, F>(f: F) -> impl Parser<I, <I as Stream>::Slice, E>
where I: StreamIsPartial + Stream, N: ToUsize, F: Parser<I, N, E>, E: ParserError<I>,
Expand description

Gets a number from the parser and returns a subslice of the input of that size.

Complete version: Returns an error if there is not enough input data.

Partial version: Will return Err(winnow::error::ErrMode::Incomplete(_)) if there is not enough data.

§Arguments

  • f The parser to apply.

§Example

use winnow::Bytes;
use winnow::binary::be_u16;
use winnow::binary::length_data;
use winnow::token::tag;

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

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

fn parser(s: Stream<'_>) -> IResult<Stream<'_>, &[u8]> {
  length_data(be_u16).parse_peek(s)
}

assert_eq!(parser(stream(b"\x00\x03abcefg")), Ok((stream(&b"efg"[..]), &b"abc"[..])));
assert_eq!(parser(stream(b"\x00\x03a")), Err(ErrMode::Incomplete(Needed::new(2))));