winnow::binary

Function u16

Source
pub fn u16<Input, Error>(endian: Endianness) -> impl Parser<Input, u16, Error>
where Input: StreamIsPartial + Stream<Token = u8>, 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;

fn be_u16(input: &mut &[u8]) -> ModalResult<u16> {
    u16(winnow::binary::Endianness::Big).parse_next(input)
};

assert_eq!(be_u16.parse_peek(&b"\x00\x03abcefg"[..]), Ok((&b"abcefg"[..], 0x0003)));
assert!(be_u16.parse_peek(&b"\x01"[..]).is_err());

fn le_u16(input: &mut &[u8]) -> ModalResult<u16> {
    u16(winnow::binary::Endianness::Little).parse_next(input)
};

assert_eq!(le_u16.parse_peek(&b"\x00\x03abcefg"[..]), Ok((&b"abcefg"[..], 0x0300)));
assert!(le_u16.parse_peek(&b"\x01"[..]).is_err());
use winnow::binary::u16;

fn be_u16(input: &mut Partial<&[u8]>) -> ModalResult<u16> {
    u16(winnow::binary::Endianness::Big).parse_next(input)
};

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

fn le_u16(input: &mut Partial<&[u8]>) -> ModalResult< u16> {
    u16(winnow::binary::Endianness::Little).parse_next(input)
};

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