winnow::token

Function one_of

Source
pub fn one_of<Input, Set, Error>(
    set: Set,
) -> impl Parser<Input, <Input as Stream>::Token, Error>
where Input: StreamIsPartial + Stream, <Input as Stream>::Token: Clone, Set: ContainsToken<<Input as Stream>::Token>, Error: ParserError<Input>,
Expand description

Recognize a token that matches a set of tokens

Note: Parser is implemented as a convenience (complete only) for

  • u8
  • char

Complete version: Will return an error if there’s not enough input data.

[Partial version][crate::_topic::partial]: Will return Err(winnow::error::ErrMode::Incomplete(_)) if there’s not enough input data.

§Effective Signature

Assuming you are parsing a &str Stream:

pub fn one_of<'i>(set: impl ContainsToken<char>) -> impl Parser<&'i str, char, ContextError>

§Example

assert_eq!(one_of::<_, _, InputError<_>>(['a', 'b', 'c']).parse_peek("b"), Ok(("", 'b')));
assert_eq!(one_of::<_, _, InputError<_>>('a').parse_peek("bc"), Err(ErrMode::Backtrack(InputError::new("bc", ErrorKind::Verify))));
assert_eq!(one_of::<_, _, InputError<_>>('a').parse_peek(""), Err(ErrMode::Backtrack(InputError::new("", ErrorKind::Token))));

fn parser_fn(i: &str) -> IResult<&str, char> {
    one_of(|c| c == 'a' || c == 'b').parse_peek(i)
}
assert_eq!(parser_fn("abc"), Ok(("bc", 'a')));
assert_eq!(parser_fn("cd"), Err(ErrMode::Backtrack(InputError::new("cd", ErrorKind::Verify))));
assert_eq!(parser_fn(""), Err(ErrMode::Backtrack(InputError::new("", ErrorKind::Token))));
assert_eq!(one_of::<_, _, InputError<_>>(['a', 'b', 'c']).parse_peek(Partial::new("b")), Ok((Partial::new(""), 'b')));
assert_eq!(one_of::<_, _, InputError<_>>('a').parse_peek(Partial::new("bc")), Err(ErrMode::Backtrack(InputError::new(Partial::new("bc"), ErrorKind::Verify))));
assert_eq!(one_of::<_, _, InputError<_>>('a').parse_peek(Partial::new("")), Err(ErrMode::Incomplete(Needed::new(1))));

fn parser_fn(i: Partial<&str>) -> IResult<Partial<&str>, char> {
    one_of(|c| c == 'a' || c == 'b').parse_peek(i)
}
assert_eq!(parser_fn(Partial::new("abc")), Ok((Partial::new("bc"), 'a')));
assert_eq!(parser_fn(Partial::new("cd")), Err(ErrMode::Backtrack(InputError::new(Partial::new("cd"), ErrorKind::Verify))));
assert_eq!(parser_fn(Partial::new("")), Err(ErrMode::Incomplete(Needed::new(1))));