Compare commits

..

2 Commits

Author SHA1 Message Date
Greg Shuflin
477fc50b65 Add justfile 2024-01-26 09:22:52 -08:00
Greg Shuflin
f2ff509748 Optional 2024-01-26 09:22:19 -08:00
3 changed files with 29 additions and 0 deletions

6
justfile Normal file
View File

@ -0,0 +1,6 @@
_default:
just --list
test:
cargo nextest run

View File

@ -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)),
}
}

View File

@ -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"));
}
}