1use std::ffi::{OsStr, OsString};
2use std::path::{Path, PathBuf};
3use std::{io, iter::repeat_with};
4
5use crate::error::IoResultExt;
6
7fn tmpname(rng: &mut fastrand::Rng, prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
8 let capacity = prefix
9 .len()
10 .saturating_add(suffix.len())
11 .saturating_add(rand_len);
12 let mut buf = OsString::with_capacity(capacity);
13 buf.push(prefix);
14 let mut char_buf = [0u8; 4];
15 for c in repeat_with(|| rng.alphanumeric()).take(rand_len) {
16 buf.push(c.encode_utf8(&mut char_buf));
17 }
18 buf.push(suffix);
19 buf
20}
21
22pub fn create_helper<R>(
23 base: &Path,
24 prefix: &OsStr,
25 suffix: &OsStr,
26 random_len: usize,
27 mut f: impl FnMut(PathBuf) -> io::Result<R>,
28) -> io::Result<R> {
29 let mut base = base; let base_path_storage; if !base.is_absolute() {
34 let cur_dir = std::env::current_dir()?;
35 base_path_storage = cur_dir.join(base);
36 base = &base_path_storage;
37 }
38
39 let num_retries = if random_len != 0 {
40 crate::NUM_RETRIES
41 } else {
42 1
43 };
44
45 let mut rng = fastrand::Rng::new();
47 for i in 0..num_retries {
48 #[cfg(all(
57 feature = "getrandom",
58 any(windows, unix, target_os = "redox", target_os = "wasi")
59 ))]
60 if i == 3 {
61 if let Ok(seed) = getrandom::u64() {
62 rng.seed(seed);
63 }
64 }
65 let path = base.join(tmpname(&mut rng, prefix, suffix, random_len));
66 return match f(path) {
67 Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists && num_retries > 1 => continue,
68 Err(ref e) if e.kind() == io::ErrorKind::AddrInUse && num_retries > 1 => continue,
71 res => res,
72 };
73 }
74
75 Err(io::Error::new(
76 io::ErrorKind::AlreadyExists,
77 "too many temporary files exist",
78 ))
79 .with_err_path(|| base)
80}