diff options
author | metamuffin <metamuffin@disroot.org> | 2023-10-02 11:25:15 +0200 |
---|---|---|
committer | metamuffin <metamuffin@disroot.org> | 2023-10-02 11:25:15 +0200 |
commit | 50b66f818d3d890e2ee13c88c404031faaeea7ba (patch) | |
tree | c467d65450304e617854e55e87e2515bc2fcea9f /base/src/temp.rs | |
parent | 1a0463e1770561f1041e1cffdbbae9b468531c55 (diff) | |
download | jellything-50b66f818d3d890e2ee13c88c404031faaeea7ba.tar jellything-50b66f818d3d890e2ee13c88c404031faaeea7ba.tar.bz2 jellything-50b66f818d3d890e2ee13c88c404031faaeea7ba.tar.zst |
tempfile
Diffstat (limited to 'base/src/temp.rs')
-rw-r--r-- | base/src/temp.rs | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/base/src/temp.rs b/base/src/temp.rs new file mode 100644 index 0000000..90ee6a8 --- /dev/null +++ b/base/src/temp.rs @@ -0,0 +1,26 @@ +use anyhow::Context; +use jellycommon::AssetLocation; +use std::{fs::File, sync::atomic::AtomicUsize}; + +use crate::AssetLocationExt; + +static TEMP_COUNTER: AtomicUsize = AtomicUsize::new(0); + +pub struct TempFile(pub AssetLocation); + +impl TempFile { + pub fn new(generate: impl FnOnce(File) -> anyhow::Result<()>) -> anyhow::Result<Self> { + let i = TEMP_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let loc = AssetLocation::Temp(format!("jellything-temp-{i}").into()); + + let file = File::create(loc.path()).context("creating temp file")?; + generate(file).context("tempfile generation")?; + + Ok(Self(loc)) + } +} +impl Drop for TempFile { + fn drop(&mut self) { + std::fs::remove_file(self.0.path()).expect("cant unlink tempfile") + } +} |