Skip to main content

rushdb_storage/
temp_path.rs

1//! Self-cleaning temporary locations for tests and benchmarks: each lives in
2//! its own fresh directory, removed with everything in it (a store's WAL and
3//! layout siblings included) when the guard drops, also while a failed test
4//! unwinds.
5
6use std::path::{Path, PathBuf};
7
8/// A temporary store file or directory; see the module docs.
9#[derive(Debug)]
10pub struct TempPath {
11    dir: PathBuf,
12    path: PathBuf,
13}
14
15impl TempPath {
16    /// A store file path (`<fresh dir>/store.redb`) named after `prefix`.
17    ///
18    /// # Panics
19    /// Panics when the temporary directory cannot be created.
20    #[must_use]
21    pub fn store(prefix: &str) -> Self {
22        let dir = Self::fresh(prefix);
23        let path = dir.join("store.redb");
24        Self { dir, path }
25    }
26
27    /// A fresh, empty directory named after `prefix`.
28    ///
29    /// # Panics
30    /// Panics when the temporary directory cannot be created.
31    #[must_use]
32    pub fn dir(prefix: &str) -> Self {
33        let dir = Self::fresh(prefix);
34        Self {
35            path: dir.clone(),
36            dir,
37        }
38    }
39
40    fn fresh(prefix: &str) -> PathBuf {
41        let dir = std::env::temp_dir().join(format!("rushdb-{prefix}-{}", uuid::Uuid::now_v7()));
42        std::fs::create_dir_all(&dir).expect("create a temporary directory");
43        dir
44    }
45
46    /// The path itself.
47    #[must_use]
48    pub fn path(&self) -> &Path {
49        &self.path
50    }
51}
52
53impl std::ops::Deref for TempPath {
54    type Target = Path;
55
56    fn deref(&self) -> &Path {
57        &self.path
58    }
59}
60
61impl AsRef<Path> for TempPath {
62    fn as_ref(&self) -> &Path {
63        &self.path
64    }
65}
66
67impl Drop for TempPath {
68    fn drop(&mut self) {
69        let _ = std::fs::remove_dir_all(&self.dir);
70    }
71}