I am playing with Rust, and am trying to write a simple parser.
I need to parse the string:
"0123,456789"
into a stucture:
Passport { label : i8 = 0, body : i32 = 123456789 }
I am using parser_combinators
and my code is working, but very ugly.
How can I rewrite this code?
extern crate parser_combinators as pc;
use pc::*;
use pc::primitives::{State, Stream};
fn main() {
match parser(parse_passport).parse("a123,456") {
Ok((r,l)) => println!("{} {} {}", r.label, r.body, l),
Err(e) => println!("{}", e)
}
}
struct Passport {
label : i8,
body : i32,
}
fn parse_passport<I>(input: State<I>) -> ParseResult<Passport, I> where I: Stream<Item=char> {
let mut label = digit().map(|i : char| (i as i8) - ('0' as i8));
let mut fst = many1(digit()).map(|string : String| string.parse::<i32>().unwrap());
let (i,input) = match label.parse_state(input) {
Ok((x,n)) => (x,n.into_inner()),
Err(e) => return Err(e)
};
let (f,input) = match fst.parse_state(input) {
Ok((x,n)) => (x,n.into_inner()),
Err(e) => return Err(e)
};
let (_,input) = match satisfy(|c| c == ',').parse_state(input) {
Ok((x,n)) => (x,n.into_inner()),
Err(e) => return Err(e)
};
let (s,input) = match fst.parse_state(input) {
Ok((x,n)) => (x,n),
Err(e) => return Err(e)
};
let p = Passport { label : i, body : f * 1000000 + s };
Ok((p, input))
}
a123,456
, not0123,456
. – Shepmaster Apr 9 at 1:56