nom::combinator

Function map_opt

Source
pub fn map_opt<I: Clone, O, E: ParseError<I>, F, G>(
    parser: F,
    f: G,
) -> impl Parser<I, Output = O, Error = E>
where F: Parser<I, Error = E>, G: FnMut(<F as Parser<I>>::Output) -> Option<O>,
Expand description

Applies a function returning an Option over the result of a parser.

use nom::character::complete::digit1;
use nom::combinator::map_opt;

let mut parse = map_opt(digit1, |s: &str| s.parse::<u8>().ok());

// the parser will convert the result of digit1 to a number
assert_eq!(parse.parse("123"), Ok(("", 123)));

// this will fail if digit1 fails
assert_eq!(parse.parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));

// this will fail if the mapped function fails (a `u8` is too small to hold `123456`)
assert_eq!(parse.parse("123456"), Err(Err::Error(("123456", ErrorKind::MapOpt))));