bread gallery data and generator script

hash_dict.rs 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. use std::collections::HashMap;
  2. use std::fs::File;
  3. use std::io;
  4. use std::io::Read;
  5. use std::io::Write;
  6. use std::path::PathBuf;
  7. // file-stored hash map used to prevent needless image regenerating
  8. #[derive(Debug)]
  9. pub struct HashDict {
  10. hashes: HashMap<String, String>,
  11. path: PathBuf,
  12. any_change: bool,
  13. }
  14. impl HashDict {
  15. pub fn load(path: PathBuf) -> Result<HashDict, io::Error> {
  16. let mut hd = HashDict {
  17. hashes: HashMap::new(),
  18. path,
  19. any_change: false,
  20. };
  21. if !hd.path.exists() {
  22. return Ok(hd);
  23. }
  24. let mut f = File::open(&hd.path)?;
  25. let mut s = String::new();
  26. f.read_to_string(&mut s)?;
  27. let lines: Vec<&str> = s.split("\n").collect();
  28. for l in lines {
  29. let halves: Vec<&str> = l.split("\t").collect();
  30. if halves.len() == 2 {
  31. hd.hashes
  32. .insert(halves[0].to_string(), halves[1].to_string());
  33. }
  34. }
  35. Ok(hd)
  36. }
  37. pub fn get(&self, key: &str) -> Option<&String> {
  38. self.hashes.get(key)
  39. }
  40. pub fn put(&mut self, key: String, value: String) {
  41. self.hashes.insert(key, value);
  42. self.any_change = true;
  43. }
  44. pub fn save(&mut self) {
  45. if self.any_change || !self.path.exists() {
  46. let mut f = File::create(&self.path).unwrap();
  47. let mut buf = String::new();
  48. for (k, v) in &self.hashes {
  49. buf.push_str(&format!("{}\t{}\n", k, v));
  50. }
  51. f.write(buf.as_ref()).unwrap();
  52. self.any_change = false;
  53. }
  54. }
  55. }