Skip to content

Instantly share code, notes, and snippets.

@hsk
Created August 1, 2021 04:31
Show Gist options
  • Save hsk/cc1004ec60127cf4433b5e286f9f382c to your computer and use it in GitHub Desktop.
Save hsk/cc1004ec60127cf4433b5e286f9f382c to your computer and use it in GitHub Desktop.
nom with struct context
use nom::bytes::complete::tag;
use nom::character::complete::multispace0;
use nom::combinator::map;
use nom::error::VerboseError;
use nom::sequence::tuple;
use nom::IResult;
struct Ctx {
a: i32
}
impl Ctx {
pub fn new() -> Self {
Self {a: 0}
}
fn unit(&mut self) -> impl FnMut(&str) -> IResult<&str, i32, VerboseError<&str>> + '_{
move |i| {
let r = map(tuple((tag("("), multispace0, tag(")"))), |_| self.a)(i);
self.a = self.a+1;
r
}
}
}
fn main() {
let mut ctx = Ctx::new();
for n in 0..10 {
assert_eq!(Ok(("",n as i32)),ctx.unit()("()"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment