summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorJohn Turner <jturner.usa@gmail.com>2025-10-22 17:13:54 -0400
committerJohn Turner <jturner.usa@gmail.com>2025-10-22 17:13:54 -0400
commit1acd65fbbd8bfaf0eaca32a22dbca1f5b04c3960 (patch)
treed079621867383cfbcfd3c4518f089591d7c5c68a /src
parentbc0148a918dd7bf0adce2cf241da49398c86c4f5 (diff)
downloadmon-1acd65fbbd8bfaf0eaca32a22dbca1f5b04c3960.tar.gz
impl Opt combinator
Diffstat (limited to 'src')
-rw-r--r--src/lib.rs30
1 files changed, 30 insertions, 0 deletions
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<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,