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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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)
}
}