use std::mem::ManuallyDrop;
use std::path::{Path, PathBuf};
pub struct TempDir {
inner: ManuallyDrop<tempfile::TempDir>,
clean_on_drop: bool,
}
impl TempDir {
pub fn new(clean_on_drop: bool) -> std::io::Result<Self> {
Ok(Self {
inner: ManuallyDrop::new(tempfile::tempdir()?),
clean_on_drop,
})
}
pub fn new_in(parent: impl AsRef<Path>, clean_on_drop: bool) -> std::io::Result<Self> {
Ok(Self {
inner: ManuallyDrop::new(tempfile::tempdir_in(parent)?),
clean_on_drop,
})
}
pub fn path(&self) -> &Path {
self.inner.path()
}
pub fn set_clean_on_drop(&mut self, clean_on_drop: bool) {
self.clean_on_drop = clean_on_drop;
}
fn into_inner(mut self) -> tempfile::TempDir {
let inner = unsafe { ManuallyDrop::take(&mut self.inner) };
std::mem::forget(self);
inner
}
pub fn into_path(self) -> PathBuf {
self.into_inner().into_path()
}
pub fn close(self) -> std::io::Result<()> {
self.into_inner().close()
}
}
impl Drop for TempDir {
fn drop(&mut self) {
if self.clean_on_drop {
unsafe { ManuallyDrop::drop(&mut self.inner) }
}
}
}