diff --git a/src/main.rs b/src/main.rs index b77fb4a..d6bbcf9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,12 @@ const FILENAME_WIP : &str = "state.wip"; struct LetterCounts([u32; 26]); // tuple +enum DeserializeError { + MissingLetter, + MissingCount(std::num::ParseIntError), + UnexpectedChar, +} + impl LetterCounts { fn add(&mut self, i : usize) { self.0[i] += 1; @@ -32,17 +38,17 @@ impl LetterCounts { } // todo: use serde? - fn deserialize(&mut self, s: &str) -> Result<(), Vec> { + fn deserialize(&mut self, s: &str) -> Result<(), Vec> { println!("deserializing..."); - let mut error_strings = Vec::new(); + let mut error_strings : Vec = Vec::new(); // todo: don't just assume no duplicate (and disagreeing) lines for line in s.lines() { if let Some((letter, val)) = line.split_once(' ') { let c = match letter.chars().next() { Some(c) => c, None => { - error_strings.push("ERROR: invalid line format, missing character.".to_string()); + error_strings.push(DeserializeError::MissingLetter); continue; } }; @@ -51,14 +57,13 @@ impl LetterCounts { let count = match val.parse::() { Ok(i) => i, Err(e) => { - // todo: don't store strings, unnecessary allocation - error_strings.push(format!("ERROR: invalid line format, missing count. ({})", e)); + error_strings.push(DeserializeError::MissingCount(e)); continue; } }; self.0[index] = count; } else { - error_strings.push("ERROR: encountered non-lowercase alphabetic char".to_string()); + error_strings.push(DeserializeError::UnexpectedChar); continue; // we just drop the char/line } } @@ -82,7 +87,14 @@ fn main() { // deserialize file contents into data structure if let Ok(contents) = fs::read_to_string(FILENAME) { if let Err(v) = data.deserialize(&contents) { - v.iter().for_each(|s| eprintln!("{}",s)); + v.iter().for_each(|e| { + let e_string = match e { + DeserializeError::MissingLetter => "ERROR: invalid line format, missing character.".to_string(), + DeserializeError::UnexpectedChar => "ERROR: unexpected character".to_string(), + DeserializeError::MissingCount(e) => format!("Error: missing count {}",e), + }; + eprintln!("{}", e_string) + }); } } else { eprintln!("ERROR: failed to read file"); diff --git a/state.txt b/state.txt index cd8f02c..b5f631e 100644 --- a/state.txt +++ b/state.txt @@ -5,7 +5,7 @@ d 1 e 2 f 3 g 3 -h 3 +h 4 i 1 j 0 k 1