use std::collections::HashMap; use std::fs::File; use std::io; use std::io::Read; use std::io::Write; use std::path::PathBuf; // file-stored hash map used to prevent needless image regenerating #[derive(Debug)] pub struct HashDict { hashes: HashMap, path: PathBuf, any_change: bool, } impl HashDict { pub fn load(path: PathBuf) -> Result { let mut hd = HashDict { hashes: HashMap::new(), path, any_change: false, }; if !hd.path.exists() { return Ok(hd); } let mut f = File::open(&hd.path)?; let mut s = String::new(); f.read_to_string(&mut s)?; let lines: Vec<&str> = s.split("\n").collect(); for l in lines { let halves: Vec<&str> = l.split("\t").collect(); if halves.len() == 2 { hd.hashes .insert(halves[0].to_string(), halves[1].to_string()); } } Ok(hd) } pub fn get(&self, key: &str) -> Option<&String> { self.hashes.get(key) } pub fn put(&mut self, key: String, value: String) { self.hashes.insert(key, value); self.any_change = true; } pub fn save(&mut self) { if self.any_change || !self.path.exists() { let mut f = File::create(&self.path).unwrap(); let mut buf = String::new(); for (k, v) in &self.hashes { buf.push_str(&format!("{}\t{}\n", k, v)); } f.write(buf.as_ref()).unwrap(); self.any_change = false; } } }