improved error handling

This commit is contained in:
2026-04-26 18:39:32 -04:00
parent 668c7b10b5
commit 4eccf5a9ec
2 changed files with 48 additions and 22 deletions
+39 -13
View File
@@ -2,7 +2,9 @@ use std::fs;
use rand::rngs::OsRng; use rand::rngs::OsRng;
use rand::Rng; use rand::Rng;
fn random_lower_char(rng: &mut OsRng) -> u8 { const FILENAME : &'static str = "state.txt";
fn random_index(rng: &mut OsRng) -> usize {
rng.gen_range(0..25) rng.gen_range(0..25)
} }
@@ -18,30 +20,54 @@ fn serialize_data(data: &[u32]) -> String {
serialization serialization
} }
fn deserialize(s: &str, data: &mut [u32]) {
println!("deserializing...");
// assumes no duplicate (and disgreeing) lines
for line in s.split('\n') {
if let Some((letter, val)) = line.split_once(' ') {
let c = match letter.chars().next() {
Some(c) => c,
None => {
println!("ERROR: invalid line format, missing character");
continue;
}
};
let index = (c as u32) - 97;
let count = match val.parse::<u32>() {
Ok(i) => i,
Err(_) => {
println!("ERROR: invalid line format, missing count");
continue;
}
};
data[index as usize] = count;
}
}
}
fn main() { fn main() {
// considered using mutable static array for data // considered using mutable static array for data
// but that requires unsafe, so we just use non-static memory // but that requires unsafe, so we just use non-static memory
let mut data : [u32; 26] = [0; 26]; let mut data : [u32; 26] = [0; 26];
// deserialize file contents into data structure // deserialize file contents into data structure
if let Ok(contents) = fs::read_to_string("state.txt") { if let Ok(contents) = fs::read_to_string(FILENAME) {
println!("deserializing..."); deserialize(&contents, &mut data);
for line in contents.split('\n') { } else {
if let Some((letter, val)) = line.split_once(' ') { println!("ERROR: failed to read file");
let index = (letter.chars().next().unwrap() as u32) - 97; // todo: handle failure
let count = val.parse::<u32>().unwrap(); // todo: handle failure
data[index as usize] = count;
}
}
} }
// generate random char and give to data structure // generate random char and give to data structure
let mut rng = OsRng; let mut rng = OsRng;
let index = random_lower_char(&mut rng) as usize; let index = random_index(&mut rng);
data[index] += 1; data[index] += 1;
println!("generated new char {}", (index + 97) as u8 as char);
// write data structure to file // write data structure to file
let s_data = serialize_data(&data); let s_data = serialize_data(&data);
fs::write("state.txt", s_data).expect("Should be able to write to `state.txt`"); println!("writing...");
println!("done") if let Err(_) = fs::write(FILENAME, s_data) {
println!("ERROR: Couldn't write to {}", FILENAME);
return;
}
} }
+9 -9
View File
@@ -1,26 +1,26 @@
a 0 a 1
b 2 b 2
c 1 c 1
d 0 d 0
e 0 e 1
f 2 f 2
g 2 g 2
h 1 h 1
i 1 i 1
j 0 j 0
k 1 k 1
l 0 l 1
m 4 m 4
n 0 n 2
o 2 o 3
p 1 p 1
q 1 q 3
r 0 r 1
s 1 s 2
t 3 t 3
u 0 u 0
v 1 v 1
w 4 w 4
x 0 x 0
y 0 y 1
z 0 z 0