1use std::{
2 fs::{self, File},
3 io::BufWriter,
4 path::Path,
5};
6
7use flux_config as config;
8use rustc_hash::FxHashMap;
9
10#[derive(Debug, serde::Serialize, serde::Deserialize)]
11struct QueryVal<R> {
12 constr_hash: u64,
13 result: R,
14}
15
16pub struct QueryCache<R> {
17 entries: FxHashMap<String, QueryVal<R>>,
18}
19
20impl<R> Default for QueryCache<R> {
21 fn default() -> Self {
22 Self::new()
23 }
24}
25
26impl<R> QueryCache<R> {
27 pub fn new() -> Self {
28 QueryCache { entries: FxHashMap::default() }
29 }
30
31 pub fn insert(&mut self, key: String, constr_hash: u64, result: R) {
32 let val = QueryVal { constr_hash, result };
33 self.entries.insert(key, val);
34 }
35
36 pub fn lookup(&self, key: &String, constr_hash: u64) -> Option<&R> {
37 let val = self.entries.get(key)?;
38 if val.constr_hash == constr_hash { Some(&val.result) } else { None }
39 }
40
41 pub fn lookup_by_key(&self, key: &str) -> Option<&R> {
43 self.entries.get(key).map(|e| &e.result)
44 }
45
46 pub fn update_result_by_key(&mut self, key: &str, f: impl FnOnce(&mut R)) {
48 if let Some(entry) = self.entries.get_mut(key) {
49 f(&mut entry.result);
50 }
51 }
52
53 fn path() -> Result<&'static Path, std::io::Error> {
54 if let Some(path) = config::cache_path()
55 && let Some(parent) = path.parent()
56 {
57 std::fs::create_dir_all(parent)?;
58 return Ok(path);
59 }
60
61 Err(Self::no_cache_err())
62 }
63
64 fn no_cache_err() -> std::io::Error {
65 std::io::Error::other("cache not enabled")
66 }
67}
68
69impl<R: std::fmt::Debug + serde::Serialize + serde::de::DeserializeOwned> QueryCache<R> {
70 pub fn save(&self) -> Result<(), std::io::Error> {
71 let path = Self::path()?;
72 let file = File::create(path).unwrap();
73 serde_json::to_writer(BufWriter::new(file), &self.entries).unwrap();
74 Ok(())
75 }
76
77 pub fn load() -> Self {
78 let path = Self::path();
79 if let Ok(path) = path
80 && let Ok(data) = fs::read(path)
81 {
82 let entries = serde_json::from_slice(&data);
83 if let Ok(entries) = entries {
84 return QueryCache { entries };
85 }
86 }
87 Self::default()
88 }
89}