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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
use std::ffi::{CString, OsStr};
use std::fs;
use std::fs::File;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::io::FromRawFd;
use std::path::{Path, PathBuf};
use libc;
use crate::errno::{errno_result, Error, Result};
pub struct TempFile {
path: PathBuf,
file: File,
}
impl TempFile {
pub fn new<P: AsRef<OsStr>>(prefix: P) -> Result<TempFile> {
let mut os_fname = prefix.as_ref().to_os_string();
os_fname.push("XXXXXX");
let raw_fname = CString::new(os_fname.into_vec()).unwrap().into_raw();
let fd = unsafe { libc::mkstemp(raw_fname) };
let c_tempname = unsafe { CString::from_raw(raw_fname) };
let os_tempname = OsStr::from_bytes(c_tempname.as_bytes());
if fd == -1 {
return errno_result();
}
let file = unsafe { File::from_raw_fd(fd) };
Ok(TempFile {
path: PathBuf::from(os_tempname),
file,
})
}
pub fn remove(&mut self) -> Result<()> {
fs::remove_file(&self.path).map_err(Error::from)
}
pub fn as_path(&self) -> &Path {
&self.path
}
pub fn as_file(&self) -> &File {
&self.file
}
}
impl Drop for TempFile {
fn drop(&mut self) {
let _ = self.remove();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
#[test]
fn test_create_file() {
fn between(lower: u8, upper: u8, to_check: u8) -> bool {
(to_check >= lower) && (to_check <= upper)
}
let tempname = "/tmp/asdf";
let t = TempFile::new(tempname).unwrap();
assert_eq!(tempname, "/tmp/asdf");
let path = t.as_path().to_owned();
assert!(path.is_file());
assert!(path.starts_with("/tmp"));
assert_eq!(path.as_os_str().len(), 15);
for n in &path.to_string_lossy().as_bytes()[5..] {
assert!(between(48, 57, *n) || between(65, 90, *n) || between(97, 122, *n));
}
let mut f = t.as_file();
f.write_all(b"hello world").unwrap();
f.sync_all().unwrap();
assert_eq!(f.metadata().unwrap().len(), 11);
}
#[test]
fn test_remove_file() {
let mut t = TempFile::new("/tmp/asdf").unwrap();
let path = t.as_path().to_owned();
assert!(path.starts_with("/tmp"));
assert!(t.remove().is_ok());
assert!(!path.exists());
assert!(t.remove().is_err());
}
#[test]
fn test_drop_file() {
let t = TempFile::new("/tmp/asdf").unwrap();
let path = t.as_path().to_owned();
assert!(path.starts_with("/tmp"));
drop(t);
assert!(!path.exists());
}
}