I'm trying to parse key value pairs encoded in a single into a hash map using combinators. So far I have come up with the following solution -- please see Rust Playground for a full example.
#!/usr/bin/env run-cargo-script
//! ```cargo
//! [dependencies]
//! scan-rules = { version = "0.1.1", features = ["regex"] }
//! ```
#[macro_use] extern crate scan_rules;
use std::collections::HashMap;
use scan_rules::scanner::re_str;
fn main() {
let mut input = String::new();
let _ = std::io::stdin().read_line(&mut input).unwrap();
let input = input.trim();
let_scan!(input; (
[let keys <| re_str("[^=]+"), "=", let values <| re_str("[^,]+")],*
));
let map: HashMap<_, _> = keys.into_iter().zip(values.into_iter()).collect();
println!("map: {:#?}", map);
}
Aside from the use of let_scan! (because I'm being lazy; normally, you'd use regular scan!) and that unwrap, the above should ensure the correct number of splits, and report a sort-of readable error if the input is malformed.
Thanks guys that was very quick and helpful. I'm glad I wasn't totally off with my solution, but I definitely like to use `collect()' instead of a side effect as well as assigning the the computation result to a immutable variable.