pub fn take<C, Input, Error: ParseError<Input>, const STREAMING: bool>(
count: C
) -> impl Fn(Input) -> IResult<Input, <Input as IntoOutput>::Output, Error>where
Input: InputIter + InputLength + InputTake + InputIsStreaming<STREAMING> + IntoOutput,
C: ToUsize,
Expand description
Returns an input slice containing the first N input elements (Input[..N]).
Complete version: It will return Err(Err::Error((_, ErrorKind::Eof)))
if the input is shorter than the argument.
Streaming version: if the input has less than N elements, take
will
return a Err::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 Err::Incomplete(Needed::Unknown)
Example
use nom8::bytes::take;
fn take6(s: &str) -> IResult<&str, &str> {
take(6usize)(s)
}
assert_eq!(take6("1234567"), Ok(("7", "123456")));
assert_eq!(take6("things"), Ok(("", "things")));
assert_eq!(take6("short"), Err(Err::Error(Error::new("short", ErrorKind::Eof))));
assert_eq!(take6(""), Err(Err::Error(Error::new("", ErrorKind::Eof))));
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 nom8::error::Error;
use nom8::bytes::take;
assert_eq!(take::<_, _, Error<_>, false>(1usize)("💙"), Ok(("", "💙")));
assert_eq!(take::<_, _, Error<_>, false>(1usize)("💙".as_bytes()), Ok((b"\x9F\x92\x99".as_ref(), b"\xF0".as_ref())));
use nom8::bytes::take;
fn take6(s: Streaming<&str>) -> IResult<Streaming<&str>, &str> {
take(6usize)(s)
}
assert_eq!(take6(Streaming("1234567")), Ok((Streaming("7"), "123456")));
assert_eq!(take6(Streaming("things")), Ok((Streaming(""), "things")));
// `Unknown` as we don't know the number of bytes that `count` corresponds to
assert_eq!(take6(Streaming("short")), Err(Err::Incomplete(Needed::Unknown)));