Function winnow::bytes::take_till1

source ·
pub fn take_till1<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 till a pattern is met.

It will return Err(ErrMode::Backtrack(Error::new(_, ErrorKind::Slice))) if the input is empty or the predicate matches the first input.

Partial version will return a ErrMode::Incomplete(Needed::new(1)) if the match reaches the end of input or if there was not match.

Example

use winnow::bytes::take_till1;

fn till_colon(s: &str) -> IResult<&str, &str> {
  take_till1(|c| c == ':').parse_next(s)
}

assert_eq!(till_colon("latin:123"), Ok((":123", "latin")));
assert_eq!(till_colon(":empty matched"), Err(ErrMode::Backtrack(Error::new(":empty matched", ErrorKind::Slice))));
assert_eq!(till_colon("12345"), Ok(("", "12345")));
assert_eq!(till_colon(""), Err(ErrMode::Backtrack(Error::new("", ErrorKind::Slice))));

fn not_space(s: &str) -> IResult<&str, &str> {
  take_till1(" \t\r\n").parse_next(s)
}

assert_eq!(not_space("Hello, World!"), Ok((" World!", "Hello,")));
assert_eq!(not_space("Sometimes\t"), Ok(("\t", "Sometimes")));
assert_eq!(not_space("Nospace"), Ok(("", "Nospace")));
assert_eq!(not_space(""), Err(ErrMode::Backtrack(Error::new("", ErrorKind::Slice))));
use winnow::bytes::take_till1;

fn till_colon(s: Partial<&str>) -> IResult<Partial<&str>, &str> {
  take_till1(|c| c == ':').parse_next(s)
}

assert_eq!(till_colon(Partial::new("latin:123")), Ok((Partial::new(":123"), "latin")));
assert_eq!(till_colon(Partial::new(":empty matched")), Err(ErrMode::Backtrack(Error::new(Partial::new(":empty matched"), ErrorKind::Slice))));
assert_eq!(till_colon(Partial::new("12345")), Err(ErrMode::Incomplete(Needed::new(1))));
assert_eq!(till_colon(Partial::new("")), Err(ErrMode::Incomplete(Needed::new(1))));

fn not_space(s: Partial<&str>) -> IResult<Partial<&str>, &str> {
  take_till1(" \t\r\n").parse_next(s)
}

assert_eq!(not_space(Partial::new("Hello, World!")), Ok((Partial::new(" World!"), "Hello,")));
assert_eq!(not_space(Partial::new("Sometimes\t")), Ok((Partial::new("\t"), "Sometimes")));
assert_eq!(not_space(Partial::new("Nospace")), Err(ErrMode::Incomplete(Needed::new(1))));
assert_eq!(not_space(Partial::new("")), Err(ErrMode::Incomplete(Needed::new(1))));