Optional
This commit is contained in:
parent
bffaca4d68
commit
f2ff509748
@ -16,3 +16,13 @@ where
|
||||
Ok((results, acc))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn optional<I, O, E>(parser: impl Parser<I, O, E>) -> impl Parser<I, Option<O>, E>
|
||||
where
|
||||
I: Clone,
|
||||
{
|
||||
move |input: I| match parser.parse(input.clone()) {
|
||||
Ok((output, rest)) => Ok((Some(output), rest)),
|
||||
Err(_e) => Ok((None, input)),
|
||||
}
|
||||
}
|
||||
|
13
src/lib.rs
13
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"));
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user