Function winnow::binary::length_take

source ·
pub fn length_take<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

Get a length-prefixed slice (TLV)

To apply a parser to the returned slice, see length_and_then.

If the count is for something besides tokens, see length_repeat.

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_take;
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_take(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))));