Skip to content

Commit 3d02d96

Browse files
committed
Migrated OrDefaultParser to MapDecorator
1 parent 6dfc3d0 commit 3d02d96

2 files changed

Lines changed: 26 additions & 10 deletions

File tree

rusty_pc/src/map_decorator.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ where
1616

1717
/// Maps the successful result of the parser.
1818
fn map_ok(&self, ok: Self::OriginalOutput) -> Self::Output;
19+
20+
/// Maps the soft error of the parser.
21+
/// By default, the error is returned as-is. However, it is possible to override this behavior.
22+
fn map_soft_error(&self, err: Self::Error) -> Result<Self::Output, Self::Error> {
23+
Err(err)
24+
}
1925
}
2026

2127
/// Marker trait for `MapDecorator`.
@@ -33,6 +39,7 @@ where
3339
fn parse(&mut self, input: &mut I) -> Result<Self::Output, Self::Error> {
3440
match self.decorated().parse(input) {
3541
Ok(ok) => Ok(self.map_ok(ok)),
42+
Err(err) if err.is_soft() => self.map_soft_error(err),
3643
Err(err) => Err(err),
3744
}
3845
}

rusty_pc/src/or_default.rs

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,39 @@
1-
use crate::{InputTrait, Parser, ParserErrorTrait};
1+
use crate::map_decorator::{MapDecorator, MapDecoratorMarker};
2+
use crate::{InputTrait, Parser};
23

34
pub struct OrDefaultParser<P> {
45
parser: P,
56
}
7+
68
impl<P> OrDefaultParser<P> {
79
pub(crate) fn new(parser: P) -> Self {
810
Self { parser }
911
}
1012
}
11-
impl<I, C, P> Parser<I, C> for OrDefaultParser<P>
13+
14+
impl<I, C, P> MapDecorator<I, C> for OrDefaultParser<P>
1215
where
1316
I: InputTrait,
1417
P: Parser<I, C>,
1518
P::Output: Default,
1619
{
20+
type OriginalOutput = P::Output;
1721
type Output = P::Output;
1822
type Error = P::Error;
19-
fn parse(&mut self, input: &mut I) -> Result<Self::Output, Self::Error> {
20-
match self.parser.parse(input) {
21-
Ok(value) => Ok(value),
22-
Err(err) if err.is_soft() => Ok(P::Output::default()),
23-
Err(err) => Err(err),
24-
}
23+
24+
fn decorated(
25+
&mut self,
26+
) -> &mut impl Parser<I, C, Output = Self::OriginalOutput, Error = Self::Error> {
27+
&mut self.parser
2528
}
2629

27-
fn set_context(&mut self, ctx: &C) {
28-
self.parser.set_context(ctx)
30+
fn map_ok(&self, ok: Self::OriginalOutput) -> Self::Output {
31+
ok
32+
}
33+
34+
fn map_soft_error(&self, _err: Self::Error) -> Result<Self::Output, Self::Error> {
35+
Ok(P::Output::default())
2936
}
3037
}
38+
39+
impl<P> MapDecoratorMarker for OrDefaultParser<P> {}

0 commit comments

Comments
 (0)