improve error handling
This commit is contained in:
+19
-7
@@ -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<String>> {
|
||||
fn deserialize(&mut self, s: &str) -> Result<(), Vec<DeserializeError>> {
|
||||
println!("deserializing...");
|
||||
|
||||
let mut error_strings = Vec::new();
|
||||
let mut error_strings : Vec<DeserializeError> = 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::<u32>() {
|
||||
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");
|
||||
|
||||
Reference in New Issue
Block a user