rust-parser-combinator/src/choice.rs

27 lines
627 B
Rust
Raw Normal View History

2022-10-16 19:21:43 -07:00
use crate::parser::Parser;
pub fn choice<P1, P2, I, O, E>(parser1: P1, parser2: P2) -> impl Parser<I, O, E>
where
P1: Parser<I, O, E>,
P2: Parser<I, O, E>,
I: Copy,
{
move |input| match parser1.parse(input) {
ok @ Ok(..) => ok,
Err(_e) => parser2.parse(input),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::combinators::one_or_more;
use crate::primitives::literal;
#[test]
fn test_choice() {
let p = choice(literal("gnostika").to(1), one_or_more(literal(" ")).to(2));
assert_eq!(p.parse("gnostika twentynine"), Ok((1, " twentynine")));
}
}