Function nom::combinator::cond

source ·
pub fn cond<I, O, E: ParseError<I>, F>(
    b: bool,
    f: F
) -> impl FnMut(I) -> IResult<I, Option<O>, E>where
    F: Parser<I, O, E>,
Expand description

Calls the parser if the condition is met.

use nom::combinator::cond;
use nom::character::complete::alpha1;

fn parser(b: bool, i: &str) -> IResult<&str, Option<&str>> {
  cond(b, alpha1)(i)
}

assert_eq!(parser(true, "abcd;"), Ok((";", Some("abcd"))));
assert_eq!(parser(false, "abcd;"), Ok(("abcd;", None)));
assert_eq!(parser(true, "123;"), Err(Err::Error(Error::new("123;", ErrorKind::Alpha))));
assert_eq!(parser(false, "123;"), Ok(("123;", None)));