Macro winnow::branch::dispatch

source ·
macro_rules! dispatch {
    ($match_parser: expr; $( $pat:pat $(if $pred:expr)? => $expr: expr ),+ $(,)? ) => { ... };
}
Expand description

match for parsers

When parsers have unique prefixes to test for, this offers better performance over alt though it might be at the cost of duplicating parts of your grammar if you needed to peek.

For tight control over the error in a catch-all case, use fail.

Example

use winnow::prelude::*;
use winnow::branch::dispatch;

fn escaped(input: &str) -> IResult<&str, char> {
    preceded('\\', escape_seq_char).parse_next(input)
}

fn escape_seq_char(input: &str) -> IResult<&str, char> {
    dispatch! {any;
        'b' => success('\u{8}'),
        'f' => success('\u{c}'),
        'n' => success('\n'),
        'r' => success('\r'),
        't' => success('\t'),
        '\\' => success('\\'),
        '"' => success('"'),
        _ => fail::<_, char, _>,
    }
    .parse_next(input)
}

assert_eq!(escaped.parse_next("\\nHello"), Ok(("Hello", '\n')));