Function winnow::token::take

source ยท
pub fn take<C, I, Error: ParserError<I>>(
    count: C,
) -> impl Parser<I, <I as Stream>::Slice, Error>
Expand description

Recognize an input slice containing the first N input elements (I[..N]).

Complete version: It will return Err(ErrMode::Backtrack(InputError::new(_, ErrorKind::Slice))) if the input is shorter than the argument.

Partial version: if the input has less than N elements, take will return a ErrMode::Incomplete(Needed::new(M)) where M is the number of additional bytes the parser would need to succeed. It is well defined for &[u8] as the number of elements is the byte size, but for types like &str, we cannot know how many bytes correspond for the next few chars, so the result will be ErrMode::Incomplete(Needed::Unknown)

ยงExample

use winnow::token::take;

fn take6(s: &str) -> IResult<&str, &str> {
  take(6usize).parse_peek(s)
}

assert_eq!(take6("1234567"), Ok(("7", "123456")));
assert_eq!(take6("things"), Ok(("", "things")));
assert_eq!(take6("short"), Err(ErrMode::Backtrack(InputError::new("short", ErrorKind::Slice))));
assert_eq!(take6(""), Err(ErrMode::Backtrack(InputError::new("", ErrorKind::Slice))));

The units that are taken will depend on the input type. For example, for a &str it will take a number of charโ€™s, whereas for a &[u8] it will take that many u8โ€™s:

use winnow::error::InputError;
use winnow::token::take;

assert_eq!(take::<_, _, InputError<_>>(1usize).parse_peek("๐Ÿ’™"), Ok(("", "๐Ÿ’™")));
assert_eq!(take::<_, _, InputError<_>>(1usize).parse_peek("๐Ÿ’™".as_bytes()), Ok((b"\x9F\x92\x99".as_ref(), b"\xF0".as_ref())));
use winnow::token::take;

fn take6(s: Partial<&str>) -> IResult<Partial<&str>, &str> {
  take(6usize).parse_peek(s)
}

assert_eq!(take6(Partial::new("1234567")), Ok((Partial::new("7"), "123456")));
assert_eq!(take6(Partial::new("things")), Ok((Partial::new(""), "things")));
// `Unknown` as we don't know the number of bytes that `count` corresponds to
assert_eq!(take6(Partial::new("short")), Err(ErrMode::Incomplete(Needed::Unknown)));