1use std::{env, fs};
2use std::ffi::CString;
3use std::io::{Error, ErrorKind, Result};
4
5#[cfg(unix)]
6use libc::mkdtemp;
7
8pub struct TempDir {
10 path: String,
11}
12
13impl TempDir {
14 pub fn new(prefix: &str) -> Result<TempDir> {
32 debug!("init new TempDir");
33 let tmp_dir = env::temp_dir();
35 debug!("found temp dir: {:?}", tmp_dir);
36
37 let ptr = match CString::new(format!("{}/{}XXXXXX", tmp_dir.display(), prefix)) {
39 Ok(p) => p.into_raw(),
40 Err(e) => return Err(Error::new(ErrorKind::Other, e)),
41 };
42 debug!("CString to raw done");
43
44 let ptr = unsafe { mkdtemp(ptr) };
46 if ptr.is_null() {
47 debug!("mkdtemp returned NULL pointer");
48 return Err(Error::last_os_error());
49 }
50 debug!("directory created");
51
52 let path = match unsafe { CString::from_raw(ptr) }.into_string() {
54 Ok(s) => s,
55 Err(e) => return Err(Error::new(ErrorKind::Other, e)),
56 };
57 debug!("raw to CString to String done");
58 debug!("got file path: {}", &path);
59
60 Ok(TempDir { path: path })
62 }
63
64 pub fn path(&self) -> &str {
66 &self.path
67 }
68}
69
70impl Drop for TempDir {
71 fn drop(&mut self) {
72 debug!("Dropping TempDir: {}", &self.path);
73 let _ = fs::remove_dir_all(&self.path);
74 }
75}