Function winnow::binary::u16

source ·
pub fn u16<Input, Error>(endian: Endianness) -> impl Parser<Input, u16, Error>
where Input: StreamIsPartial + Stream<Token = u8>, <Input as Stream>::Slice: AsBytes, Error: ParserError<Input>,
Expand description

Recognizes an unsigned 2 bytes integer

If the parameter is winnow::binary::Endianness::Big, parse a big endian u16 integer, otherwise if winnow::binary::Endianness::Little parse a little endian u16 integer.

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

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

§Example

use winnow::binary::u16;

let be_u16 = |s| {
    u16(winnow::binary::Endianness::Big).parse_peek(s)
};

assert_eq!(be_u16(&b"\x00\x03abcefg"[..]), Ok((&b"abcefg"[..], 0x0003)));
assert_eq!(be_u16(&b"\x01"[..]), Err(ErrMode::Backtrack(InputError::new(&[0x01][..], ErrorKind::Slice))));

let le_u16 = |s| {
    u16(winnow::binary::Endianness::Little).parse_peek(s)
};

assert_eq!(le_u16(&b"\x00\x03abcefg"[..]), Ok((&b"abcefg"[..], 0x0300)));
assert_eq!(le_u16(&b"\x01"[..]), Err(ErrMode::Backtrack(InputError::new(&[0x01][..], ErrorKind::Slice))));
use winnow::binary::u16;

let be_u16 = |s| {
    u16::<_, InputError<_>>(winnow::binary::Endianness::Big).parse_peek(s)
};

assert_eq!(be_u16(Partial::new(&b"\x00\x03abcefg"[..])), Ok((Partial::new(&b"abcefg"[..]), 0x0003)));
assert_eq!(be_u16(Partial::new(&b"\x01"[..])), Err(ErrMode::Incomplete(Needed::new(1))));

let le_u16 = |s| {
    u16::<_, InputError<_>>(winnow::binary::Endianness::Little).parse_peek(s)
};

assert_eq!(le_u16(Partial::new(&b"\x00\x03abcefg"[..])), Ok((Partial::new(&b"abcefg"[..]), 0x0300)));
assert_eq!(le_u16(Partial::new(&b"\x01"[..])), Err(ErrMode::Incomplete(Needed::new(1))));