use std::env::temp_dir;
use std::fs::{File, OpenOptions, remove_file};
use std::io;
use std::os::unix::fs::OpenOptionsExt;
use std::path::PathBuf;
use crate::rand::Rng;
pub struct TempFile {
file: File,
path: PathBuf,
}
impl TempFile {
pub fn new() -> io::Result<Self> {
Self::with_prefix("file")
}
pub fn get(&self) -> &File {
&self.file
}
pub fn with_prefix(prefix: &str) -> io::Result<Self> {
let mut rng = Rng::new();
for _ in 0..50 {
let tempfile = temp_dir()
.join(format!("{}.{}", prefix, rng.gen_int()));
if let Ok(file) = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.mode(0o600)
.open(&tempfile)
{
return Ok(Self {
file,
path: tempfile,
})
}
}
Err(io::Error::from(io::ErrorKind::AlreadyExists))
}
}
impl Drop for TempFile {
fn drop(&mut self) {
if let Err(error) = remove_file(&self.path) {
eprintln!("Cannot remove file: {}", error);
}
}
}
#[cfg(test)]
mod tests {
use std::io::Write;
use super::TempFile;
#[test]
fn test_temp_file_exists() {
let path;
{
let temp_file = TempFile::new().expect("new temp file");
path = temp_file.path.clone();
assert!(path.is_file());
writeln!(temp_file.get(), "test").expect("write");
}
assert!(!path.is_file());
assert!(!path.exists());
let path;
{
let temp_file = TempFile::with_prefix("mini-prefix").expect("new temp file");
path = temp_file.path.clone();
assert!(path.is_file());
}
assert!(!path.is_file());
assert!(!path.exists());
}
}