1use std::{fs, io::Write, path::PathBuf};
11pub mod errors;
12
13pub struct Client {
14 cache_dir: PathBuf,
15 filename: String,
16}
17
18impl Client {
19 pub fn new(cache_dir: PathBuf, filename: String) -> Client {
20 Client {
21 cache_dir,
22 filename,
23 }
24 }
25
26 fn dirpath_by_keys(&self, keys: &[&str]) -> PathBuf {
27 let mut path = self.cache_dir.clone();
28 for key in keys {
29 path.push(key);
30 }
31 path
32 }
33
34 fn filepath_by_keys(&self, keys: &[&str]) -> PathBuf {
35 let mut path = self.dirpath_by_keys(keys);
36 path.push(&self.filename);
37 path
38 }
39
40 fn ensure_dir(&self, keys: &[&str]) -> Result<(), errors::Error> {
41 let path = self.dirpath_by_keys(keys);
42 fs::create_dir_all(path)?;
43 Ok(())
44 }
45
46 pub fn save(&self, keys: &[&str], data: &[u8]) -> Result<(), errors::Error> {
50 let path = self.filepath_by_keys(keys);
51 self.ensure_dir(keys)?;
52 let file = fs::File::create(path)?;
53 let mut writer = std::io::BufWriter::new(file);
54 writer.write_all(data)?;
55 Ok(())
56 }
57
58 pub fn load(&self, keys: &[&str]) -> Result<Vec<u8>, errors::Error> {
62 let path = self.filepath_by_keys(keys);
63 Ok(fs::read(path)?)
64 }
65
66 pub fn remove(&self, keys: &[&str]) -> Result<(), errors::Error> {
70 let path = self.filepath_by_keys(keys);
71 fs::remove_file(path)?;
72 Ok(())
73 }
74
75 pub fn has(&self, keys: &[&str]) -> bool {
79 let path = self.filepath_by_keys(keys);
80 path.exists()
81 }
82}