Created
March 31, 2017 08:37
-
-
Save demurgos/060829cc096b11bb7457d8ab334401ad to your computer and use it in GitHub Desktop.
Parametrized parsers for nom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use nom::IResult; | |
// Hard-coded | |
named!(pub balanced1<()>, do_parse!(take!(1) >> tag!("~") >> take!(1) >> ())); | |
named!(pub balanced2<()>, do_parse!(take!(2) >> tag!("~") >> take!(2) >> ())); | |
named!(pub balanced3<()>, do_parse!(take!(3) >> tag!("~") >> take!(3) >> ())); | |
// Parametrized (function) | |
fn balanced_fn(input: &[u8], n: usize) -> IResult<&[u8], ()> { | |
do_parse!(input, take!(n) >> tag!("~") >> take!(n) >> ()) | |
} | |
// Parametrized (macro) | |
named_args!(balanced_macro(n: usize) <()>, | |
do_parse!(take!(n) >> tag!("~") >> take!(n) >> ()) | |
); | |
// Combined (function) | |
named!(pub balanced5_fn<()>, apply!(balanced_macro, 5)); | |
// Combined (macro) | |
named!(pub balanced5_macro<()>, call!(balanced_macro, 5)); | |
#[cfg(test)] | |
mod tests { | |
use nom; | |
use super::*; | |
#[test] | |
fn test_balanced() { | |
assert_eq!(balanced1(&b"a~a"[..]), nom::IResult::Done(&[][..], ())); | |
assert_eq!(balanced2(&b"aa~aa"[..]), nom::IResult::Done(&[][..], ())); | |
assert_eq!(balanced3(&b"aaa~aaa"[..]), nom::IResult::Done(&[][..], ())); | |
assert_eq!(balanced_fn(&b"aaaaa~aaaaa"[..], 5), nom::IResult::Done(&[][..], ())); | |
assert_eq!(balanced_macro(&b"aaaaa~aaaaa"[..], 5), nom::IResult::Done(&[][..], ())); | |
assert_eq!(balanced5_fn(&b"aaaaa~aaaaa"[..]), nom::IResult::Done(&[][..], ())); | |
assert_eq!(balanced5_macro(&b"aaaaa~aaaaa"[..]), nom::IResult::Done(&[][..], ())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment