Function nom8::bytes::take_while1

source ·
pub fn take_while1<T, Input, Error: ParseError<Input>, const STREAMING: bool>(
    list: T
) -> impl Fn(Input) -> IResult<Input, <Input as IntoOutput>::Output, Error>where
    Input: InputTakeAtPosition + InputIsStreaming<STREAMING> + IntoOutput,
    T: FindToken<<Input as InputTakeAtPosition>::Item>,
Expand description

Returns the longest (at least 1) input slice that matches the pattern

It will return an Err(Err::Error((_, ErrorKind::TakeWhile1))) if the pattern wasn’t met.

Streaming version will return a Err::Incomplete(Needed::new(1)) or if the pattern reaches the end of the input.

Example

use nom8::bytes::take_while1;
use nom8::input::AsChar;

fn alpha(s: &[u8]) -> IResult<&[u8], &[u8]> {
  take_while1(AsChar::is_alpha)(s)
}

assert_eq!(alpha(b"latin123"), Ok((&b"123"[..], &b"latin"[..])));
assert_eq!(alpha(b"latin"), Ok((&b""[..], &b"latin"[..])));
assert_eq!(alpha(b"12345"), Err(Err::Error(Error::new(&b"12345"[..], ErrorKind::TakeWhile1))));

fn hex(s: &str) -> IResult<&str, &str> {
  take_while1("1234567890ABCDEF")(s)
}

assert_eq!(hex("123 and voila"), Ok((" and voila", "123")));
assert_eq!(hex("DEADBEEF and others"), Ok((" and others", "DEADBEEF")));
assert_eq!(hex("BADBABEsomething"), Ok(("something", "BADBABE")));
assert_eq!(hex("D15EA5E"), Ok(("", "D15EA5E")));
assert_eq!(hex(""), Err(Err::Error(Error::new("", ErrorKind::TakeWhile1))));
use nom8::bytes::take_while1;
use nom8::input::AsChar;

fn alpha(s: Streaming<&[u8]>) -> IResult<Streaming<&[u8]>, &[u8]> {
  take_while1(AsChar::is_alpha)(s)
}

assert_eq!(alpha(Streaming(b"latin123")), Ok((Streaming(&b"123"[..]), &b"latin"[..])));
assert_eq!(alpha(Streaming(b"latin")), Err(Err::Incomplete(Needed::new(1))));
assert_eq!(alpha(Streaming(b"12345")), Err(Err::Error(Error::new(Streaming(&b"12345"[..]), ErrorKind::TakeWhile1))));

fn hex(s: Streaming<&str>) -> IResult<Streaming<&str>, &str> {
  take_while1("1234567890ABCDEF")(s)
}

assert_eq!(hex(Streaming("123 and voila")), Ok((Streaming(" and voila"), "123")));
assert_eq!(hex(Streaming("DEADBEEF and others")), Ok((Streaming(" and others"), "DEADBEEF")));
assert_eq!(hex(Streaming("BADBABEsomething")), Ok((Streaming("something"), "BADBABE")));
assert_eq!(hex(Streaming("D15EA5E")), Err(Err::Incomplete(Needed::new(1))));
assert_eq!(hex(Streaming("")), Err(Err::Incomplete(Needed::new(1))));