Function winnow::binary::length_take

source ·
pub fn length_take<Input, Count, Error, CountParser>(
    count: CountParser,
) -> impl Parser<Input, <Input as Stream>::Slice, Error>
where Input: StreamIsPartial + Stream, Count: ToUsize, CountParser: Parser<Input, Count, Error>, Error: ParserError<Input>,
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.

§Example

use winnow::Bytes;
use winnow::binary::be_u16;
use winnow::binary::length_take;

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