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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
use crate::{AutoRemove, ContainingDirectory, ForksafeTempfile, Handle, NEXT_MAP_INDEX, REGISTER};
use std::{io, path::Path};
use tempfile::{NamedTempFile, TempPath};
#[derive(Debug)]
pub struct Writable;
#[derive(Debug)]
pub struct Closed;
pub(crate) enum Mode {
Writable,
Closed,
}
impl<T: std::fmt::Debug> Handle<T> {
fn at_path(
path: impl AsRef<Path>,
directory: ContainingDirectory,
cleanup: AutoRemove,
mode: Mode,
) -> io::Result<usize> {
let path = path.as_ref();
let tempfile = {
let mut builder = tempfile::Builder::new();
let dot_ext_storage;
match path.file_stem() {
Some(stem) => builder.prefix(stem),
None => builder.prefix(""),
};
if let Some(ext) = path.extension() {
dot_ext_storage = format!(".{}", ext.to_string_lossy());
builder.suffix(&dot_ext_storage);
}
let parent_dir = path.parent().expect("parent directory is present");
let parent_dir = directory.resolve(parent_dir)?;
ForksafeTempfile::new(builder.rand_bytes(0).tempfile_in(parent_dir)?, cleanup, mode)
};
let id = NEXT_MAP_INDEX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
expect_none(REGISTER.insert(id, Some(tempfile)));
Ok(id)
}
fn new_writable_inner(
containing_directory: impl AsRef<Path>,
directory: ContainingDirectory,
cleanup: AutoRemove,
mode: Mode,
) -> io::Result<usize> {
let containing_directory = directory.resolve(containing_directory.as_ref())?;
let id = NEXT_MAP_INDEX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
expect_none(REGISTER.insert(
id,
Some(ForksafeTempfile::new(
NamedTempFile::new_in(containing_directory)?,
cleanup,
mode,
)),
));
Ok(id)
}
}
impl Handle<Closed> {
pub fn at(path: impl AsRef<Path>, directory: ContainingDirectory, cleanup: AutoRemove) -> io::Result<Self> {
Ok(Handle {
id: Handle::<()>::at_path(path, directory, cleanup, Mode::Closed)?,
_marker: Default::default(),
})
}
pub fn take(self) -> Option<TempPath> {
let res = REGISTER.remove(&self.id);
std::mem::forget(self);
res.and_then(|(_k, v)| v.map(|v| v.into_temppath()))
}
}
impl Handle<Writable> {
pub fn at(path: impl AsRef<Path>, directory: ContainingDirectory, cleanup: AutoRemove) -> io::Result<Self> {
Ok(Handle {
id: Handle::<()>::at_path(path, directory, cleanup, Mode::Writable)?,
_marker: Default::default(),
})
}
pub fn new(
containing_directory: impl AsRef<Path>,
directory: ContainingDirectory,
cleanup: AutoRemove,
) -> io::Result<Self> {
Ok(Handle {
id: Handle::<()>::new_writable_inner(containing_directory, directory, cleanup, Mode::Writable)?,
_marker: Default::default(),
})
}
pub fn take(self) -> Option<NamedTempFile> {
let res = REGISTER.remove(&self.id);
std::mem::forget(self);
res.and_then(|(_k, v)| v.map(|v| v.into_tempfile().expect("correct runtime typing")))
}
}
impl Handle<Writable> {
pub fn with_mut<T>(&mut self, once: impl FnOnce(&mut NamedTempFile) -> T) -> std::io::Result<T> {
match REGISTER.remove(&self.id) {
Some((id, Some(mut t))) => {
let res = once(t.as_mut_tempfile().expect("correct runtime typing"));
expect_none(REGISTER.insert(id, Some(t)));
Ok(res)
}
None | Some((_, None)) => Err(std::io::Error::new(
std::io::ErrorKind::Interrupted,
format!("The tempfile with id {} wasn't available anymore", self.id),
)),
}
}
}
impl ContainingDirectory {
fn resolve(self, dir: &Path) -> std::io::Result<&Path> {
match self {
ContainingDirectory::Exists => Ok(dir),
ContainingDirectory::CreateAllRaceProof(retries) => crate::create_dir::all(dir, retries),
}
}
}
fn expect_none<T>(v: Option<T>) {
assert!(
v.is_none(),
"there should never be conflicts or old values as ids are never reused."
);
}
impl<T: std::fmt::Debug> Drop for Handle<T> {
fn drop(&mut self) {
if let Some((_id, Some(tempfile))) = REGISTER.remove(&self.id) {
tempfile.drop_impl();
}
}
}