rustc_data_structures/
temp_dir.rs

1use std::mem::ManuallyDrop;
2use std::path::Path;
3
4use tempfile::TempDir;
5
6/// This is used to avoid TempDir being dropped on error paths unintentionally.
7#[derive(Debug)]
8pub struct MaybeTempDir {
9    dir: ManuallyDrop<TempDir>,
10    // Whether the TempDir should be deleted on drop.
11    keep: bool,
12}
13
14impl Drop for MaybeTempDir {
15    fn drop(&mut self) {
16        // SAFETY: We are in the destructor, and no further access will
17        // occur.
18        let dir = unsafe { ManuallyDrop::take(&mut self.dir) };
19        if self.keep {
20            let _ = dir.into_path();
21        }
22    }
23}
24
25impl AsRef<Path> for MaybeTempDir {
26    fn as_ref(&self) -> &Path {
27        self.dir.path()
28    }
29}
30
31impl MaybeTempDir {
32    pub fn new(dir: TempDir, keep_on_drop: bool) -> MaybeTempDir {
33        MaybeTempDir { dir: ManuallyDrop::new(dir), keep: keep_on_drop }
34    }
35}