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
use std::{env, fs};
use std::ffi::CString;
use std::io::{Error, ErrorKind, Result};
#[cfg(unix)]
use libc::mkdtemp;
pub struct TempDir {
path: String,
}
impl TempDir {
pub fn new(prefix: &str) -> Result<TempDir> {
debug!("init new TempDir");
let tmp_dir = env::temp_dir();
debug!("found temp dir: {:?}", tmp_dir);
let ptr = match CString::new(format!("{}/{}XXXXXX", tmp_dir.display(), prefix)) {
Ok(p) => p.into_raw(),
Err(e) => return Err(Error::new(ErrorKind::Other, e)),
};
debug!("CString to raw done");
let ptr = unsafe { mkdtemp(ptr) };
if ptr.is_null() {
debug!("mkdtemp returned NULL pointer");
return Err(Error::last_os_error());
}
debug!("directory created");
let path = match unsafe { CString::from_raw(ptr) }.into_string() {
Ok(s) => s,
Err(e) => return Err(Error::new(ErrorKind::Other, e)),
};
debug!("raw to CString to String done");
debug!("got file path: {}", &path);
Ok(TempDir { path: path })
}
pub fn path(&self) -> &str {
&self.path
}
}
impl Drop for TempDir {
fn drop(&mut self) {
debug!("Dropping TempDir: {}", &self.path);
let _ = fs::remove_dir_all(&self.path);
}
}