init simple project that reads a file, generates a random lowercase character and writes counts so far to a file
This commit is contained in:
+47
@@ -0,0 +1,47 @@
|
||||
use std::fs;
|
||||
use rand::rngs::OsRng;
|
||||
use rand::Rng;
|
||||
|
||||
fn random_lower_char(rng: &mut OsRng) -> u8 {
|
||||
rng.gen_range(0..25)
|
||||
}
|
||||
|
||||
fn serialize_data(data: &[u32]) -> String {
|
||||
println!("serializing...");
|
||||
let mut serialization = String::new();
|
||||
for (i, count) in data.iter().enumerate() {
|
||||
let c = (i as u8 + 97) as char;
|
||||
let s = format!("{} {}\n", c, count.to_string());
|
||||
serialization.push_str(&s)
|
||||
}
|
||||
// only stack object (ptr, len, capacity) is copied on the way out
|
||||
serialization
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// generate random char and give to data structure
|
||||
let mut rng = OsRng;
|
||||
let index = random_lower_char(&mut rng) as usize;
|
||||
data[index] += 1;
|
||||
|
||||
// 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")
|
||||
}
|
||||
Reference in New Issue
Block a user