1use std::{fs, process};
4use std::fmt::Debug;
5use std::path::{Path, PathBuf};
6use tinyrand::Rand;
7use tinyrand_std::thread_rand;
8
9#[derive(Debug)]
12pub struct TempPath {
13 path_buf: PathBuf
14}
15
16impl TempPath {
17 #[allow(clippy::similar_names)]
19 pub fn with_extension(extension: &str) -> Self {
20 let path_buf = std::env::temp_dir();
21 let mut rand = thread_rand();
22 let pid = process::id();
23 let tid = thread_id::get();
24 let random = rand.next_u64();
25 let path_buf = path_buf.join(format!("test-{pid}-{tid}-{random:X}.{extension}"));
26 Self { path_buf }
27 }
28}
29
30impl AsRef<Path> for TempPath {
31 fn as_ref(&self) -> &Path {
32 &self.path_buf
33 }
34}
35
36impl Drop for TempPath {
37 fn drop(&mut self) {
38 let meta = fs::metadata(&self);
39 if let Ok(meta) = meta {
40 let _ignore = if meta.is_dir() {
41 fs::remove_dir(self)
42 } else {
43 fs::remove_file(self)
44 };
45 }
46 }
47}
48
49#[cfg(test)]
50mod tests;