Function kparse::combinators::map_res

source ·
pub fn map_res<PA, TR, I, O1, O2, E>(
    parser: PA,
    map: TR
) -> impl FnMut(I) -> Result<(I, O2), Err<E>>where
    PA: Parser<I, O1, E>,
    TR: Fn(O1) -> Result<O2, Err<E>>,
    O1: Clone,
    I: AsBytes + Clone,
Expand description

Takes a parser and a transformation of the parser result.

This is also available as postfix fn parser.map_res() for parsers.

use nom::character::complete::digit1;
use nom::combinator::consumed;
use nom::{AsChar, InputTakeAtPosition, Parser};
use nom::sequence::terminated;
use kparse::combinators::map_res;
use kparse::examples::ExCode::ExNumber;
use kparse::examples::{ExParserError, ExSpan, ExTokenizerError, ExTokenizerResult};

fn nom_number(i: ExSpan<'_>) -> ExTokenizerResult<'_, (ExSpan<'_>, u32)> {
    consumed(map_res(terminated(digit1, nom_ws), |v| {
        match (*v).parse::<u32>() {
            Ok(vv) => Ok(vv),
            Err(_) => Err(ExTokenizerError::new(ExNumber, v).failure()),
        }
    }))(i)
}

fn nom_ws(i: ExSpan<'_>) -> ExTokenizerResult<'_, ExSpan<'_>> {
    i.split_at_position_complete(|item| {
        let c = item.as_char();
        !(c == ' ' || c == '\t')
    })
}