From 81acfc65ededd306a8c2b46d483caee8244c52ca Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Wed, 26 Dec 2018 15:51:08 +0100 Subject: Use serde_derive to deserialize primstav data into a struct. This makes it much easier to work with the data. Adds some restrictions on the yaml data though, all elements must be present, even if empty. --- src/main.rs | 40 ++++++++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index 60d04bc..f6ea539 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,11 +15,12 @@ // along with this program. If not, see . use chrono; +use serde_derive::Deserialize; use serde_yaml; +use std::collections::BTreeMap; use std::io::BufReader; use std::iter::Iterator; use std::fs::File; -use std::str::FromStr; use std::string::ToString; mod locale; @@ -41,28 +42,39 @@ fn test_capitalize() { assert_eq!("", capitalize("")); } -fn print_entry(d: &serde_yaml::Value) { - let name = d.get("name").unwrap(); - println!("{}", capitalize(name.as_str().unwrap())); +#[allow(dead_code)] +#[derive(Deserialize)] +struct Mark { + name: String, + alternative_names: Vec, + symbols: Vec, + links: Vec>, +} + +struct Primstav { + marks: BTreeMap, +} - if let Some(alt_names) = d.get("alternative_names") { - let names = alt_names.as_sequence().unwrap().iter() - .map(|v| capitalize(v.as_str().unwrap())) +fn print_entry(m: &Mark) { + println!("{}", capitalize(&m.name)); + + if !m.alternative_names.is_empty() { + let names = m.alternative_names.iter() + .map(|v| capitalize(&v)) .collect::>(); println!("({})", names.join(", ")); } - if let Some(syms) = d.get("symbols") { - let s = syms.as_sequence().unwrap().iter() - .map(|v| v.as_str().unwrap()) - .collect::>(); - println!("Symboler: {}", s.join(", ")); + if !m.symbols.is_empty() { + println!("Symboler: {}", m.symbols.join(", ")); } } fn main() { let f = BufReader::new(File::open("data/primstav.yml").unwrap()); - let data: serde_yaml::Value = serde_yaml::from_reader(f).unwrap(); + let p = Primstav { + marks: serde_yaml::from_reader(f).unwrap(), + }; let mut args = std::env::args().skip(1); let local_date = match args.next() { @@ -74,7 +86,7 @@ fn main() { println!("{}", capitalize(&locale.format_date(&local_date))); let key = local_date.format("%d%m").to_string(); - match data.get(serde_yaml::Value::Number(u32::from_str(&key).unwrap().into())) { + match p.marks.get(&key) { Some(d) => print_entry(&d), None => () } -- cgit v1.2.3