Function winnow::bytes::take_while1
source · pub fn take_while1<T, I, Error: ParseError<I>>(
list: T
) -> impl Parser<I, <I as Stream>::Slice, Error>where
I: StreamIsPartial + Stream,
T: ContainsToken<<I as Stream>::Token>,
Expand description
Recognize the longest (at least 1) input slice that matches the pattern
It will return an Err(ErrMode::Backtrack(Error::new(_, ErrorKind::Slice)))
if the pattern wasn’t met.
Partial version will return a ErrMode::Incomplete(Needed::new(1))
or if the pattern reaches the end of the input.
To recognize a series of tokens, use many1
to Accumulate
into a ()
and then Parser::recognize
.
Example
use winnow::bytes::take_while1;
use winnow::stream::AsChar;
fn alpha(s: &[u8]) -> IResult<&[u8], &[u8]> {
take_while1(AsChar::is_alpha).parse_next(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(ErrMode::Backtrack(Error::new(&b"12345"[..], ErrorKind::Slice))));
fn hex(s: &str) -> IResult<&str, &str> {
take_while1("1234567890ABCDEF").parse_next(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(ErrMode::Backtrack(Error::new("", ErrorKind::Slice))));
use winnow::bytes::take_while1;
use winnow::stream::AsChar;
fn alpha(s: Partial<&[u8]>) -> IResult<Partial<&[u8]>, &[u8]> {
take_while1(AsChar::is_alpha).parse_next(s)
}
assert_eq!(alpha(Partial::new(b"latin123")), Ok((Partial::new(&b"123"[..]), &b"latin"[..])));
assert_eq!(alpha(Partial::new(b"latin")), Err(ErrMode::Incomplete(Needed::new(1))));
assert_eq!(alpha(Partial::new(b"12345")), Err(ErrMode::Backtrack(Error::new(Partial::new(&b"12345"[..]), ErrorKind::Slice))));
fn hex(s: Partial<&str>) -> IResult<Partial<&str>, &str> {
take_while1("1234567890ABCDEF").parse_next(s)
}
assert_eq!(hex(Partial::new("123 and voila")), Ok((Partial::new(" and voila"), "123")));
assert_eq!(hex(Partial::new("DEADBEEF and others")), Ok((Partial::new(" and others"), "DEADBEEF")));
assert_eq!(hex(Partial::new("BADBABEsomething")), Ok((Partial::new("something"), "BADBABE")));
assert_eq!(hex(Partial::new("D15EA5E")), Err(ErrMode::Incomplete(Needed::new(1))));
assert_eq!(hex(Partial::new("")), Err(ErrMode::Incomplete(Needed::new(1))));