| 1 |
use std::{ |
| 2 |
collections::hash_map::RandomState, |
| 3 |
fs::{remove_file, File, OpenOptions}, |
| 4 |
hash::{BuildHasher, Hasher}, |
| 5 |
io, os, |
| 6 |
path::{Path, PathBuf}, |
| 7 |
}; |
| 8 |
|
| 9 |
#[cfg(not(any(unix, target_os = "wasi", windows)))] |
| 10 |
compile_error!("Your system is not supported since cc cannot create named tempfile"); |
| 11 |
|
| 12 |
fn rand() -> u64 { |
| 13 |
RandomState::new().build_hasher().finish() |
| 14 |
} |
| 15 |
|
| 16 |
fn tmpname(suffix: &str) -> String { |
| 17 |
format!("{}{}", rand(), suffix) |
| 18 |
} |
| 19 |
|
| 20 |
fn create_named(path: &Path) -> io::Result<File> { |
| 21 |
let mut open_options = OpenOptions::new(); |
| 22 |
|
| 23 |
open_options.read(true).write(true).create_new(true); |
| 24 |
|
| 25 |
#[cfg(all(unix, not(target_os = "wasi")))] |
| 26 |
<OpenOptions as os::unix::fs::OpenOptionsExt>::mode(&mut open_options, 0o600); |
| 27 |
|
| 28 |
#[cfg(windows)] |
| 29 |
<OpenOptions as os::windows::fs::OpenOptionsExt>::custom_flags( |
| 30 |
&mut open_options, |
| 31 |
crate::windows::windows_sys::FILE_ATTRIBUTE_TEMPORARY, |
| 32 |
); |
| 33 |
|
| 34 |
open_options.open(path) |
| 35 |
} |
| 36 |
|
| 37 |
pub(super) struct NamedTempfile { |
| 38 |
path: PathBuf, |
| 39 |
file: Option<File>, |
| 40 |
} |
| 41 |
|
| 42 |
impl NamedTempfile { |
| 43 |
pub(super) fn new(base: &Path, suffix: &str) -> io::Result<Self> { |
| 44 |
for _ in 0..10 { |
| 45 |
let path = base.join(tmpname(suffix)); |
| 46 |
match create_named(&path) { |
| 47 |
Ok(file) => { |
| 48 |
return Ok(Self { |
| 49 |
file: Some(file), |
| 50 |
path, |
| 51 |
}) |
| 52 |
} |
| 53 |
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, |
| 54 |
Err(e) => return Err(e), |
| 55 |
}; |
| 56 |
} |
| 57 |
|
| 58 |
Err(io::Error::new( |
| 59 |
io::ErrorKind::AlreadyExists, |
| 60 |
format!( |
| 61 |
"too many temporary files exist in base `{}` with suffix `{}`", |
| 62 |
base.display(), |
| 63 |
suffix |
| 64 |
), |
| 65 |
)) |
| 66 |
} |
| 67 |
|
| 68 |
pub(super) fn path(&self) -> &Path { |
| 69 |
&self.path |
| 70 |
} |
| 71 |
|
| 72 |
pub(super) fn file(&self) -> &File { |
| 73 |
self.file.as_ref().unwrap() |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
impl Drop for NamedTempfile { |
| 78 |
fn drop(&mut self) { |
| 79 |
// On Windows you have to close all handle to it before |
| 80 |
// removing the file. |
| 81 |
self.file.take(); |
| 82 |
let _ = remove_file(&self.path); |
| 83 |
} |
| 84 |
} |