diff options
| author | John Turner <jturner.usa@gmail.com> | 2025-10-22 17:13:54 -0400 |
|---|---|---|
| committer | John Turner <jturner.usa@gmail.com> | 2025-10-22 17:13:54 -0400 |
| commit | 1acd65fbbd8bfaf0eaca32a22dbca1f5b04c3960 (patch) | |
| tree | d079621867383cfbcfd3c4518f089591d7c5c68a | |
| parent | bc0148a918dd7bf0adce2cf241da49398c86c4f5 (diff) | |
| download | mon-1acd65fbbd8bfaf0eaca32a22dbca1f5b04c3960.tar.gz | |
impl Opt combinator
| -rw-r--r-- | src/lib.rs | 30 |
1 files changed, 30 insertions, 0 deletions
@@ -770,6 +770,36 @@ where Not { parser } } +struct Opt<P> { + parser: P, +} + +impl<I, P> Parser<I> for Opt<P> +where + I: Input, + P: Parser<I>, +{ + type Output = Option<P::Output>; + + fn run<OM: Mode, EM: Mode, Tracer: Trace<I>>( + &mut self, + it: InputIter<I>, + ) -> ParserResult<I, Self::Output, OM, EM> { + match self.parser.run::<OM, EM, Tracer>(it.clone()) { + Ok((rest, output)) => Ok((rest, OM::map(output, |o| Some(o)))), + Err(_) => Ok((it, OM::bind(|| None))), + } + } +} + +pub fn opt<I, P>(parser: P) -> impl Parser<I, Output = Option<P::Output>> +where + I: Input, + P: Parser<I>, +{ + Opt { parser } +} + pub fn alpha<I>() -> impl Parser<I, Output = I> where I: Input, |
