Function take

fn take<UsizeLike, Input, Error>(token_count: UsizeLike) -> impl Parser<Input, <Input as Stream>::Slice, Error>
where
    Input: StreamIsPartial + Stream,
    UsizeLike: ToUsize,
    Error: ParserError<Input>

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

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

[Partial version][crate::_topic::partial]: 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)

Effective Signature

Assuming you are parsing a &str [Stream] with 0.. or 1.. ranges:

# use std::ops::RangeFrom;
# use winnow::prelude::*;
# use winnow::stream::ContainsToken;
# use winnow::error::ContextError;
pub fn take<'i>(token_count: usize) -> impl Parser<&'i str, &'i str, ContextError>
# {
#     winnow::token::take(token_count)
# }

Example

# use winnow::{error::ErrMode, error::ContextError, error::Needed};
# use winnow::prelude::*;
use winnow::token::take;

fn take6<'i>(s: &mut &'i str) -> ModalResult<&'i str> {
  take(6usize).parse_next(s)
}

assert_eq!(take6.parse_peek("1234567"), Ok(("7", "123456")));
assert_eq!(take6.parse_peek("things"), Ok(("", "things")));
assert!(take6.parse_peek("short").is_err());
assert!(take6.parse_peek("").is_err());

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::prelude::*;
use winnow::error::ContextError;
use winnow::token::take;

assert_eq!(take::<_, _, ContextError>(1usize).parse_peek("💙"), Ok(("", "💙")));
assert_eq!(take::<_, _, ContextError>(1usize).parse_peek("💙".as_bytes()), Ok((b"\x9F\x92\x99".as_ref(), b"\xF0".as_ref())));
# use winnow::prelude::*;
# use winnow::error::{ErrMode, ContextError, Needed};
# use winnow::Partial;
use winnow::token::take;

fn take6<'i>(s: &mut Partial<&'i str>) -> ModalResult<&'i str> {
  take(6usize).parse_next(s)
}

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