Macro utils::parser_literal_map

source ·
macro_rules! parser_literal_map {
    (
        $($($l:literal)|+ => $e:expr),+$(,)?
    ) => { ... };
    (@error $first:literal $($l:literal)+) => { ... };
    (@error $first:literal) => { ... };
}
Expand description

Macro to define a parser for one or more string literals, mapping the results.

This is a replacement for parser::one_of(("a".map(|_| Enum::A), "b".map(|_| Enum::b))) which produces more optimized assembly and is easier to read and write.

The string patterns are matched in the order provided, so strings should be ordered by length.

Using this makes 2017 day 11, which parses a sequence of literals separated by commas, over 2x faster.

§Examples


#[derive(Debug, PartialEq)]
enum Example {
    A,
    B,
    C,
}

let parser = parser::literal_map!(
    "A" | "a" => Example::A,
    "B" => Example::B,
    "C" => Example::C,
);
assert_eq!(parser.parse(b"A"), Ok((Example::A, &b""[..])));
assert_eq!(parser.parse(b"a"), Ok((Example::A, &b""[..])));
assert_eq!(parser.parse(b"B"), Ok((Example::B, &b""[..])));
assert_eq!(parser.parse(b"C"), Ok((Example::C, &b""[..])));
assert!(parser.parse(b"D").is_err());