use std::{
fmt::{self, Display},
fs::File,
io::{self, Error as IOError},
os::unix::io::FromRawFd,
};
#[derive(Debug)]
pub struct Mktemp {
pub file: File,
pub path: String,
}
impl Display for Mktemp {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.path) }
}
pub fn mkstemp(template: &str) -> io::Result<Mktemp> {
let mut template_cstr = {
let mut t = String::new();
t.push_str(template);
t.push('\0');
t
};
let fd = unsafe { libc::mkstemp(template_cstr.as_mut_ptr() as *mut libc::c_char) };
match fd {
-1 => Err(IOError::last_os_error()),
_ => {
template_cstr.pop();
Ok(Mktemp { file: unsafe { File::from_raw_fd(fd) }, path: template_cstr })
},
}
}
pub fn mkdtemp(template: &str) -> io::Result<String> {
let mut template_cstr = {
let mut t = String::new();
t.push_str(template);
t.push('\0');
t
};
let ptr = unsafe {
libc::mkdtemp(template_cstr.as_mut_ptr() as *mut libc::c_char) as *const libc::c_char
};
if ptr.is_null() {
Err(IOError::last_os_error())
} else {
template_cstr.pop();
Ok(template_cstr)
}
}