http1/common/
temp_file.rs

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use std::{
    fs::{File, OpenOptions},
    path::{Path, PathBuf},
};

/// Represents a temporal file which is deleted after drop.
#[derive(Debug)]
pub struct TempFile(PathBuf);

impl TempFile {
    pub fn with_dir(sub_dir: impl AsRef<Path>) -> std::io::Result<Self> {
        Self::create(Some(sub_dir))
    }

    pub fn random() -> std::io::Result<Self> {
        Self::create::<PathBuf>(None)
    }

    fn create<P: AsRef<Path>>(path: Option<P>) -> std::io::Result<Self> {
        let mut temp_path = std::env::temp_dir();
        let file_name = rng::sequence::<rng::Alphanumeric>()
            .take(20)
            .collect::<String>();

        if let Some(p) = path {
            let sub_path = p.as_ref().strip_prefix("/").unwrap_or(p.as_ref());
            temp_path.push(sub_path);

            std::fs::create_dir_all(&temp_path)?;
        }

        // Create the file
        temp_path.push(file_name);
        std::fs::File::create_new(&temp_path)?;

        Ok(TempFile(temp_path))
    }

    pub fn path(&self) -> &Path {
        &self.0
    }

    pub fn file(&self) -> TempFileOpen {
        TempFileOpen {
            path: &self.0,
            file: OpenOptions::new(),
        }
    }

    pub fn read(&self) -> std::io::Result<File> {
        self.file().read(true).open()
    }
}

pub struct TempFileOpen<'a> {
    path: &'a Path,
    file: OpenOptions,
}

impl<'a> TempFileOpen<'a> {
    pub fn append(mut self, append: bool) -> Self {
        self.file.append(append);
        self
    }

    pub fn read(mut self, read: bool) -> Self {
        self.file.read(read);
        self
    }

    pub fn write(mut self, write: bool) -> Self {
        self.file.write(write);
        self
    }

    pub fn truncate(mut self, write: bool) -> Self {
        self.file.truncate(write);
        self
    }

    pub fn open(self) -> std::io::Result<File> {
        self.file.open(self.path)
    }
}

impl Drop for TempFile {
    fn drop(&mut self) {
        std::fs::remove_file(&self.0).ok();
    }
}

#[cfg(test)]
mod tests {
    use super::TempFile;
    use std::io::{Seek, Write};

    #[test]
    fn should_exists_random_file() {
        let temp_file = TempFile::random().unwrap();

        let p = temp_file.path().to_path_buf();
        assert!(p.exists());
        assert!(p.is_file());
    }

    #[test]
    fn should_create_file_on_subdir() {
        let temp_file = TempFile::with_dir("/sub_dir").unwrap();

        let p = temp_file.path().to_path_buf();
        assert!(p.exists());
        assert!(p.is_file());

        drop(temp_file);
        assert!(!p.exists());
    }

    #[test]
    fn should_remove_file_after_drop() {
        let temp_file = TempFile::random().unwrap();

        let p = temp_file.path().to_path_buf();
        drop(temp_file);
        assert!(!p.exists());
    }

    #[test]
    fn should_write_and_read() {
        let temp_file = TempFile::random().unwrap();

        let mut f = temp_file.file().write(true).read(true).open().unwrap();
        write!(f, "Hello World!").unwrap();

        f.seek(std::io::SeekFrom::Start(0)).unwrap(); // Move the start of the file
        let text = std::io::read_to_string(f).unwrap();
        assert_eq!(text, "Hello World!");

        let p = temp_file.path().to_path_buf();

        drop(temp_file);
        assert!(!p.exists());
    }
}