use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
static SEQ: AtomicU64 = AtomicU64::new(0);
pub fn unique_dir(label: &str) -> PathBuf {
let n = SEQ.fetch_add(1, Ordering::Relaxed);
let p = std::env::temp_dir().join(format!("kevy-{label}-{}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&p);
std::fs::create_dir_all(&p).expect("create temp dir");
p
}
#[derive(Debug)]
pub struct TmpDir(PathBuf);
impl TmpDir {
pub fn new(label: &str) -> Self {
Self(unique_dir(label))
}
pub fn path(&self) -> &Path {
&self.0
}
}
impl AsRef<Path> for TmpDir {
fn as_ref(&self) -> &Path {
&self.0
}
}
impl Drop for TmpDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[cfg(test)]
mod tests {
use super::TmpDir;
use std::collections::HashSet;
#[test]
fn two_dirs_in_one_process_are_different() {
let a = TmpDir::new("x");
let b = TmpDir::new("x");
assert_ne!(a.path(), b.path());
}
#[test]
fn threads_racing_for_a_name_all_get_their_own() {
let dirs: Vec<_> = std::thread::scope(|s| {
let handles: Vec<_> = (0..32)
.map(|_| s.spawn(|| TmpDir::new("race").path().to_path_buf()))
.collect();
handles.into_iter().map(|h| h.join().expect("thread")).collect()
});
let uniq: HashSet<_> = dirs.iter().collect();
assert_eq!(uniq.len(), 32, "two threads got the same directory");
}
#[test]
fn the_directory_exists_and_then_does_not() {
let p = {
let d = TmpDir::new("drop");
assert!(d.path().is_dir());
d.path().to_path_buf()
};
assert!(!p.exists(), "TmpDir did not clean up after itself");
}
}