Skip to content

Instantly share code, notes, and snippets.

@acdimalev
Created October 15, 2015 16:42
Show Gist options
  • Save acdimalev/faecbcc8b6744e4d3f6e to your computer and use it in GitHub Desktop.
Save acdimalev/faecbcc8b6744e4d3f6e to your computer and use it in GitHub Desktop.
extern crate combine;
use std::collections::HashMap;
use combine::primitives::{State, Stream, ParseResult};
use combine::{many, many1, token, satisfy, parser, sep_end_by1};
use combine::{Parser, ParserExt};
fn entry<I>(input: State<I>) -> ParseResult<(String, String), I>
where I: Stream<Item=char> {
(
many1(satisfy(|c| c != ':' && c != '\n')),
token(':'),
many(satisfy(|c| c != '\n'))
.map(|s: String| s.trim().to_owned()),
)
.map(|(key, _, value)| (key, value))
.parse_state(input)
}
fn entries<I>(input: State<I>) -> ParseResult<HashMap<String, String>, I>
where I: Stream<Item=char> {
sep_end_by1(parser(entry), token('\n')).parse_state(input)
}
fn parse_data(s: &str) -> Result<Data, String> {
let e = try!(
parser(entries).parse(s)
.map_err(|e| format!("{}", e))
).0;
Ok(Data {
this: try!(
e["this"].parse::<f32>()
.map_err(|e| format!("this: {}", e))
),
that: try!(
e["that"].parse::<f32>()
.map_err(|e| format!("that: {}", e))
),
})
}
#[derive(Debug)]
struct Data {
this: f32,
that: f32,
}
fn main() {
let input = "this: 3.2 \nthat: 6.2\nthe other thing:\n4:5";
println!("{}\n", input);
// let data = parse_data(input).expect("error parsing data");
let data = parse_data(input)
.unwrap_or_else(|e| panic!(format!("error parsing data: {}", e)));
println!("{:?}", data);
let value: bool = "false".parse().unwrap();
println!("{:?}", value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment