From 50b66f818d3d890e2ee13c88c404031faaeea7ba Mon Sep 17 00:00:00 2001 From: metamuffin Date: Mon, 2 Oct 2023 11:25:15 +0200 Subject: tempfile --- base/src/temp.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 base/src/temp.rs (limited to 'base/src/temp.rs') 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 { + 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") + } +} -- cgit v1.2.3-70-g09d2