aboutsummaryrefslogtreecommitdiff
path: root/base/src/temp.rs
blob: 8da85f733f9ad6458e67186c06218873a80efa27 (plain)
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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2023 metamuffin <metamuffin.org>
*/
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")
    }
}