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::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)
}
@@ -18,30 +20,54 @@ fn serialize_data(data: &[u32]) -> String {
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() {
// considered using mutable static array for data
// but that requires unsafe, so we just use non-static memory
let mut data : [u32; 26] = [0; 26];
// deserialize file contents into data structure
if let Ok(contents) = fs::read_to_string("state.txt") {
println!("deserializing...");
for line in contents.split('\n') {
if let Some((letter, val)) = line.split_once(' ') {
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;
}
}
if let Ok(contents) = fs::read_to_string(FILENAME) {
deserialize(&contents, &mut data);
} else {
println!("ERROR: failed to read file");
}
// generate random char and give to data structure
let mut rng = OsRng;
let index = random_lower_char(&mut rng) as usize;
let index = random_index(&mut rng);
data[index] += 1;
println!("generated new char {}", (index + 97) as u8 as char);
// write data structure to file
let s_data = serialize_data(&data);
fs::write("state.txt", s_data).expect("Should be able to write to `state.txt`");
println!("done")
println!("writing...");
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
c 1
d 0
e 0
e 1
f 2
g 2
h 1
i 1
j 0
k 1
l 0
l 1
m 4
n 0
o 2
n 2
o 3
p 1
q 1
r 0
s 1
q 3
r 1
s 2
t 3
u 0
v 1
w 4
x 0
y 0
y 1
z 0