From 1acd65fbbd8bfaf0eaca32a22dbca1f5b04c3960 Mon Sep 17 00:00:00 2001 From: John Turner Date: Wed, 22 Oct 2025 17:13:54 -0400 Subject: impl Opt combinator --- src/lib.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index e0be671..2878185 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -770,6 +770,36 @@ where Not { parser } } +struct Opt

{ + parser: P, +} + +impl Parser for Opt

+where + I: Input, + P: Parser, +{ + type Output = Option; + + fn run>( + &mut self, + it: InputIter, + ) -> ParserResult { + match self.parser.run::(it.clone()) { + Ok((rest, output)) => Ok((rest, OM::map(output, |o| Some(o)))), + Err(_) => Ok((it, OM::bind(|| None))), + } + } +} + +pub fn opt(parser: P) -> impl Parser> +where + I: Input, + P: Parser, +{ + Opt { parser } +} + pub fn alpha() -> impl Parser where I: Input, -- cgit v1.2.3