From f2ff5097488704fbc2c5efc88be2dfe1e2441c82 Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Fri, 26 Jan 2024 09:22:19 -0800 Subject: [PATCH] Optional --- src/combinators.rs | 10 ++++++++++ src/lib.rs | 13 +++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/combinators.rs b/src/combinators.rs index b48a512..a505427 100644 --- a/src/combinators.rs +++ b/src/combinators.rs @@ -16,3 +16,13 @@ where Ok((results, acc)) } } + +pub fn optional(parser: impl Parser) -> impl Parser, E> +where + I: Clone, +{ + move |input: I| match parser.parse(input.clone()) { + Ok((output, rest)) => Ok((Some(output), rest)), + Err(_e) => Ok((None, input)), + } +} diff --git a/src/lib.rs b/src/lib.rs index 795d9de..ad50a6b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -74,4 +74,17 @@ mod tests { let output = parser.parse("aaaaaaaabcd").unwrap(); assert_eq! {((10, 'b'), "cd"), output}; } + + #[test] + fn test_optional() { + let parser = sequence( + optional(literal("alpha")), + sequence(repeated(literal(" ")), literal("beta")), + ); + + let output1 = parser.parse(" beta").unwrap(); + assert_eq!(output1.0 .0, None); + let output2 = parser.parse("alpha beta").unwrap(); + assert_eq!(output2.0 .0, Some("alpha")); + } }