diff --git a/src/main.rs b/src/main.rs index d1561a1..600f762 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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::() { + 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::().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; + } } diff --git a/state.txt b/state.txt index 366c2a4..f2b330a 100644 --- a/state.txt +++ b/state.txt @@ -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