Skip to main content

qubit_fs/temp/
managed_temp_resource_factory.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2026 Haixing Hu.
4 *
5 *    SPDX-License-Identifier: Apache-2.0
6 *
7 *    Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! Managed temporary resource factory.
11
12use std::sync::Arc;
13
14use crate::{
15    CreateDirOptions,
16    FileSystem,
17    FsResult,
18    ManagedTempDir,
19    ManagedTempFile,
20    TempDir,
21    TempDirOptions,
22    TempFile,
23    TempFileOptions,
24    TempResourceFactory,
25    WriteMode,
26    WriteOptions,
27};
28
29/// Default factory backed by generic [`FileSystem`] operations.
30#[derive(Debug)]
31pub struct ManagedTempResourceFactory;
32
33impl ManagedTempResourceFactory {
34    /// Returns the shared managed temporary resource factory.
35    ///
36    /// # Returns
37    /// Static managed temporary resource factory instance.
38    #[must_use]
39    pub fn shared() -> &'static Self {
40        static FACTORY: ManagedTempResourceFactory = ManagedTempResourceFactory;
41        &FACTORY
42    }
43}
44
45impl TempResourceFactory for ManagedTempResourceFactory {
46    fn create_file(&self, owner: Arc<dyn FileSystem>, options: &TempFileOptions) -> FsResult<Box<dyn TempFile>> {
47        let path = self.make_temp_path(options.parent.as_ref(), &options.prefix, &options.suffix)?;
48        let writer_options = WriteOptions {
49            create_parent: true,
50            mode: WriteMode::CreateNew,
51            ..WriteOptions::default()
52        };
53        owner.open_writer(&path, &writer_options)?.commit()?;
54        Ok(Box::new(ManagedTempFile::new(owner, path)))
55    }
56
57    fn create_dir(&self, owner: Arc<dyn FileSystem>, options: &TempDirOptions) -> FsResult<Box<dyn TempDir>> {
58        let path = self.make_temp_path(options.parent.as_ref(), &options.prefix, &options.suffix)?;
59        owner.create_dir(
60            &path,
61            &CreateDirOptions {
62                recursive: true,
63                ..CreateDirOptions::default()
64            },
65        )?;
66        Ok(Box::new(ManagedTempDir::new(owner, path)))
67    }
68}