1use std::fmt;
52use std::path::{Path, PathBuf};
53use std::sync::RwLock;
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub struct Compiler<'a> {
61 pub name: &'a str,
62 pub version: &'a str,
63}
64
65#[derive(Clone, Debug, Default, PartialEq, Eq)]
67pub struct Cache {
68 dir: Option<PathBuf>,
69}
70
71#[derive(Clone, Debug, PartialEq, Eq)]
74pub struct CacheError {
75 pub entry: PathBuf,
77 pub message: String,
78}
79
80impl fmt::Display for CacheError {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 write!(
83 f,
84 "cannot write the cache entry `{}`: {}",
85 self.entry.display(),
86 self.message
87 )
88 }
89}
90
91impl std::error::Error for CacheError {}
92
93const MAGIC: &str = "egui-pop-cache/1";
96
97impl Cache {
98 pub const fn off() -> Cache {
100 Cache { dir: None }
101 }
102
103 pub fn at(dir: impl Into<PathBuf>) -> Cache {
106 Cache {
107 dir: Some(dir.into()),
108 }
109 }
110
111 pub fn for_app(app_id: &str) -> Cache {
114 Cache {
115 dir: platform_dir(app_id),
116 }
117 }
118
119 pub fn dir(&self) -> Option<&Path> {
121 self.dir.as_deref()
122 }
123
124 pub fn is_on(&self) -> bool {
126 self.dir.is_some()
127 }
128
129 pub fn entry_path(&self, compiler: &Compiler<'_>, source: &Path) -> Option<PathBuf> {
133 let dir = self.dir.as_ref()?;
134 let source = std::path::absolute(source).unwrap_or_else(|_| source.to_path_buf());
135 let key = hash(source.as_os_str().as_encoded_bytes());
136 Some(
137 dir.join(folder_name(compiler.name))
138 .join(format!("{key:032x}")),
139 )
140 }
141
142 pub fn get(&self, compiler: &Compiler<'_>, source: &Path, contents: &[u8]) -> Option<Vec<u8>> {
146 let path = self.entry_path(compiler, source)?;
147 let mut bytes = std::fs::read(path).ok()?;
148 let end = bytes.iter().position(|b| *b == b'\n')?;
149 if bytes[..end] != *header(compiler, contents).as_bytes() {
150 return None;
151 }
152 bytes.drain(..=end);
153 Some(bytes)
154 }
155
156 pub fn put(
160 &self,
161 compiler: &Compiler<'_>,
162 source: &Path,
163 contents: &[u8],
164 compiled: &[u8],
165 ) -> Result<(), CacheError> {
166 let Some(path) = self.entry_path(compiler, source) else {
167 return Ok(());
168 };
169 let failed = |e: std::io::Error| CacheError {
170 entry: path.clone(),
171 message: e.to_string(),
172 };
173 if let Some(parent) = path.parent() {
174 std::fs::create_dir_all(parent).map_err(failed)?;
175 }
176 let mut bytes = header(compiler, contents).into_bytes();
177 bytes.push(b'\n');
178 bytes.extend_from_slice(compiled);
179 let tmp = path.with_extension(format!("tmp{}", std::process::id()));
180 std::fs::write(&tmp, &bytes).map_err(failed)?;
181 std::fs::rename(&tmp, &path).map_err(|e| {
182 std::fs::remove_file(&tmp).ok();
183 failed(e)
184 })
185 }
186}
187
188fn header(compiler: &Compiler<'_>, contents: &[u8]) -> String {
189 format!(
190 "{MAGIC} {} {} {:032x} {}",
191 folder_name(compiler.name),
192 compiler.version.replace(char::is_whitespace, "_"),
193 hash(contents),
194 contents.len()
195 )
196}
197
198fn folder_name(name: &str) -> String {
201 let clean: String = name
202 .chars()
203 .map(|c| {
204 if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
205 c
206 } else {
207 '_'
208 }
209 })
210 .collect();
211 match clean.trim_matches('.') {
212 "" => "_".into(),
213 _ => clean,
214 }
215}
216
217fn hash(bytes: &[u8]) -> u128 {
221 const OFFSET: u128 = 0x6c62_272e_07bb_0142_62b8_2175_6295_c58d;
222 const PRIME: u128 = 0x0000_0000_0100_0000_0000_0000_0000_013b;
223 bytes
224 .iter()
225 .fold(OFFSET, |h, b| (h ^ u128::from(*b)).wrapping_mul(PRIME))
226}
227
228pub fn platform_dir_with(app_id: &str, env: impl Fn(&str) -> Option<String>) -> Option<PathBuf> {
242 let absolute = |v: Option<String>| v.map(PathBuf::from).filter(|p| p.is_absolute());
243 let base = if cfg!(windows) {
244 absolute(env("LOCALAPPDATA"))?.join(app_id).join("cache")
245 } else if cfg!(target_os = "macos") {
246 absolute(env("HOME"))?.join("Library/Caches").join(app_id)
247 } else {
248 match absolute(env("XDG_CACHE_HOME")) {
249 Some(p) => p,
250 None => absolute(env("HOME"))?.join(".cache"),
251 }
252 .join(app_id)
253 };
254 Some(base.join("egui-pop"))
255}
256
257pub fn platform_dir(app_id: &str) -> Option<PathBuf> {
259 platform_dir_with(app_id, |name| std::env::var(name).ok())
260}
261
262static DEFAULT: RwLock<Option<Cache>> = RwLock::new(None);
263
264pub fn set_default(cache: Cache) {
268 *DEFAULT.write().unwrap_or_else(|e| e.into_inner()) = Some(cache);
269}
270
271pub fn default() -> Cache {
274 DEFAULT
275 .read()
276 .unwrap_or_else(|e| e.into_inner())
277 .clone()
278 .unwrap_or_default()
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 const C1: Compiler<'static> = Compiler {
286 name: "test",
287 version: "1",
288 };
289
290 fn temp(name: &str) -> PathBuf {
291 let dir =
292 std::env::temp_dir().join(format!("egui-pop-cache-{name}-{}", std::process::id()));
293 std::fs::remove_dir_all(&dir).ok();
294 dir
295 }
296
297 #[test]
298 fn a_hit_needs_the_same_path_contents_and_version() {
299 let dir = temp("key");
300 let cache = Cache::at(&dir);
301 let a = dir.join("a.yaml");
302 cache.put(&C1, &a, b"x", b"compiled").unwrap();
303 assert_eq!(cache.get(&C1, &a, b"x").as_deref(), Some(&b"compiled"[..]));
304 assert_eq!(cache.get(&C1, &a, b"y"), None, "changed contents");
305 assert_eq!(
306 cache.get(&C1, &dir.join("b.yaml"), b"x"),
307 None,
308 "other path"
309 );
310 let c2 = Compiler { version: "2", ..C1 };
311 assert_eq!(cache.get(&c2, &a, b"x"), None, "other version");
312 cache.put(&c2, &a, b"x", b"two").unwrap();
314 assert_eq!(cache.get(&c2, &a, b"x").as_deref(), Some(&b"two"[..]));
315 assert_eq!(cache.get(&C1, &a, b"x"), None);
316 assert_eq!(std::fs::read_dir(dir.join("test")).unwrap().count(), 1);
317 std::fs::remove_dir_all(&dir).ok();
318 }
319
320 #[test]
321 fn off_reads_and_writes_nothing() {
322 let cache = Cache::off();
323 assert!(!cache.is_on());
324 assert_eq!(cache.put(&C1, Path::new("/a"), b"x", b"y"), Ok(()));
325 assert_eq!(cache.get(&C1, Path::new("/a"), b"x"), None);
326 }
327
328 #[test]
329 fn an_unwritable_cache_says_so() {
330 let dir = temp("unwritable");
331 std::fs::create_dir_all(&dir).unwrap();
332 let file = dir.join("file");
333 std::fs::write(&file, "").unwrap();
334 let cache = Cache::at(file.join("cache"));
336 let err = cache.put(&C1, &dir.join("a"), b"x", b"y").unwrap_err();
337 assert!(err.to_string().contains("cannot write"), "{err}");
338 assert_eq!(cache.get(&C1, &dir.join("a"), b"x"), None);
339 std::fs::remove_dir_all(&dir).ok();
340 }
341
342 #[test]
343 fn a_damaged_entry_is_a_miss() {
344 let dir = temp("damaged");
345 let cache = Cache::at(&dir);
346 let a = dir.join("a");
347 cache.put(&C1, &a, b"x", b"y").unwrap();
348 std::fs::write(cache.entry_path(&C1, &a).unwrap(), "garbage").unwrap();
349 assert_eq!(cache.get(&C1, &a, b"x"), None);
350 std::fs::remove_dir_all(&dir).ok();
351 }
352
353 #[test]
354 fn compiler_names_are_folder_names() {
355 assert_eq!(folder_name("tokens"), "tokens");
356 assert_eq!(folder_name("../x y"), ".._x_y");
357 assert_eq!(folder_name(".."), "_");
358 }
359
360 #[test]
361 fn the_platform_dir_is_under_the_app_id() {
362 let dir = platform_dir_with("org.example.App", |name| match name {
363 "HOME" => Some("/home/u".into()),
364 "LOCALAPPDATA" => Some("C:\\Users\\u\\AppData\\Local".into()),
365 _ => None,
366 });
367 let dir = dir.expect("a home is enough");
368 assert!(dir.ends_with("egui-pop"));
369 assert!(dir.to_string_lossy().contains("org.example.App"));
370 assert_eq!(platform_dir_with("a", |_| None), None);
371 assert_eq!(
372 platform_dir_with("a", |_| Some("relative".into())),
373 None,
374 "a relative directory is not trusted"
375 );
376 }
377}