sub_solver/
cache.rs

1use std::{
2    collections::{HashMap, HashSet},
3    error::Error,
4    fs::File,
5    io::{BufReader, BufWriter},
6};
7
8lazy_static! {
9    static ref CACHE_DIR: String = {
10        let mut path = dirs::cache_dir().unwrap();
11        path.push("sub-solver");
12        path.to_str().unwrap().to_string()
13    };
14}
15
16fn get_filename(content: &str) -> String {
17    format!("{}/{:x}.bin", *CACHE_DIR, md5::compute(content))
18}
19
20pub fn load_cached_dictionary(content: &str) -> Option<HashMap<String, HashSet<String>>> {
21    if let Ok(file) = File::open(get_filename(content)) {
22        let reader = BufReader::new(file);
23        bincode::deserialize_from(reader).ok()
24    } else {
25        None
26    }
27}
28
29pub fn save_cached_dictionary(
30    content: &str,
31    dictionary: &HashMap<String, HashSet<String>>,
32) -> Result<(), Box<dyn Error>> {
33    std::fs::create_dir_all(&*CACHE_DIR)?; // Create folder if doesn't exist
34    let mut file = BufWriter::new(File::create(get_filename(content))?);
35    bincode::serialize_into(&mut file, dictionary)?;
36    Ok(())
37}