From e6ce2cf34d78405b0a756a24091b0602fd4a7660 Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Wed, 19 Oct 2022 22:23:52 -0700 Subject: [PATCH] then_ignore, ignore_then --- src/lib.rs | 26 +++++++++++++------------- src/parser.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 13 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 3069a71..f995968 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -52,21 +52,21 @@ mod tests { let digit = || one_of("1234567890"); assert_eq!(digit().parse("3"), Ok(("3", ""))); + let digits = || repeated(digit()).at_least(1); + let json_number_inner = choice(( - seq(( - repeated(digit()).at_least(1), - literal(".").then(repeated(digit())).optional(), - )) - .map(|(mut digits, maybe_more)| { - if let Some((point, more)) = maybe_more { - digits.push(point); - digits.extend(more.into_iter()); - } - digits.into_iter().collect::() - }), - seq((literal("."), repeated(digit()).at_least(1))).map(|(_point, digits)| { + seq((digits(), literal(".").ignore_then(digits()).optional())).map( + |(mut digits, maybe_decimal)| { + if let Some(decimal_digits) = maybe_decimal { + digits.push("."); + digits.extend(decimal_digits.into_iter()); + } + digits.into_iter().collect::() + }, + ), + literal(".").ignore_then(digits()).map(|decimal_digits| { let mut d = vec!["."]; - d.extend(digits.into_iter()); + d.extend(decimal_digits.into_iter()); d.into_iter().collect::() }), )) diff --git a/src/parser.rs b/src/parser.rs index 86c9908..e069cc4 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -44,6 +44,32 @@ pub trait Parser { BoxedParser::new(crate::sequence::tuple2(self, next_parser)) } + fn ignore_then<'a, P, O2>(self, next_parser: P) -> BoxedParser<'a, I, O2, E> + where + Self: Sized + 'a, + I: 'a, + O: 'a, + O2: 'a, + E: 'a, + P: Parser + 'a, + { + BoxedParser::new(crate::sequence::tuple2(self, next_parser)) + .map(|(_, next_output)| next_output) + } + + fn then_ignore<'a, P, O2>(self, next_parser: P) -> BoxedParser<'a, I, O, E> + where + Self: Sized + 'a, + I: 'a, + O: 'a, + O2: 'a, + E: 'a, + P: Parser + 'a, + { + BoxedParser::new(crate::sequence::tuple2(self, next_parser)) + .map(|(this_output, _)| this_output) + } + fn optional<'a>(self) -> BoxedParser<'a, I, Option, E> where I: Clone + 'a,