this repo has no description
1use std::{
2 fs,
3 path::{Path, PathBuf},
4 time::{Duration, SystemTime},
5};
6
7const TTL: u16 = 60 * 60 * 12;
8
9#[derive(Clone)]
10pub struct Cache {
11 path: PathBuf,
12}
13
14impl Cache {
15 pub fn new(path: String) -> Self {
16 let _ = fs::create_dir_all(&path);
17 let path = Path::new(&path).to_owned();
18
19 Cache { path }
20 }
21
22 pub fn put(&self, key: &str, binary: &[u8]) {
23 let _ = fs::write(self.path.join(&format!("{}.bin", key)), binary);
24 }
25
26 pub fn get(&self, key: &str) -> Option<Vec<u8>> {
27 let path = self.path.join(&format!("{}.bin", key,));
28 if !fs::exists(&path).expect("check path") {
29 return None;
30 }
31
32 let crtime = fs::metadata(&path)
33 .expect("path metadata")
34 .created()
35 .expect("path crtime");
36
37 if SystemTime::now() >= crtime.checked_add(Duration::from_secs(TTL as u64))? {
38 fs::remove_file(path).expect("delete path");
39 return None;
40 };
41
42 Some(fs::read(path).expect("read path"))
43 }
44
45 pub fn cleanup(&self) {
46 let files = fs::read_dir(&self.path).expect("read dir");
47 for entry in files {
48 let entry = entry.expect("entry perms");
49 let crtime = entry
50 .metadata()
51 .expect("entry metadata")
52 .created()
53 .expect("entry crtime");
54
55 if SystemTime::now()
56 >= crtime
57 .checked_add(Duration::from_secs(TTL as u64))
58 .expect("crtime oob")
59 {
60 fs::remove_file(entry.path()).expect("delete entry");
61 }
62 }
63 }
64}