flanker_temp/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//! Helper for working with temporary files.

use std::{fs, process};
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use tinyrand::Rand;
use tinyrand_std::thread_rand;

/// A path to a temporary file that will be deleted (if the file was created) when the path
/// is eventually dropped.
#[derive(Debug)]
pub struct TempPath {
    path_buf: PathBuf
}

impl TempPath {
    /// Returns a random path in the system's temp directory.
    #[allow(clippy::similar_names)]
    pub fn with_extension(extension: &str) -> Self {
        let path_buf = std::env::temp_dir();
        let mut rand = thread_rand();
        let pid = process::id();
        let tid = thread_id::get();
        let random = rand.next_u64();
        let path_buf = path_buf.join(format!("test-{pid}-{tid}-{random:X}.{extension}"));
        Self { path_buf }
    }
}

impl AsRef<Path> for TempPath {
    fn as_ref(&self) -> &Path {
        &self.path_buf
    }
}

impl Drop for TempPath {
    fn drop(&mut self) {
        let meta = fs::metadata(&self);
        if let Ok(meta) = meta {
            let _ignore = if meta.is_dir() {
                fs::remove_dir(self)
            } else {
                fs::remove_file(self)
            };
        }
    }
}

#[cfg(test)]
mod tests;