use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::{io, iter::repeat_with};
use crate::error::IoResultExt;
fn tmpname(rng: &mut fastrand::Rng, prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
let capacity = prefix
.len()
.saturating_add(suffix.len())
.saturating_add(rand_len);
let mut buf = OsString::with_capacity(capacity);
buf.push(prefix);
let mut char_buf = [0u8; 4];
for c in repeat_with(|| rng.alphanumeric()).take(rand_len) {
buf.push(c.encode_utf8(&mut char_buf));
}
buf.push(suffix);
buf
}
pub fn create_helper<R>(
base: &Path,
prefix: &OsStr,
suffix: &OsStr,
random_len: usize,
mut f: impl FnMut(PathBuf) -> io::Result<R>,
) -> io::Result<R> {
let mut base = base; let base_path_storage; if !base.is_absolute() {
let cur_dir = std::env::current_dir()?;
base_path_storage = cur_dir.join(base);
base = &base_path_storage;
}
let num_retries = if random_len != 0 {
crate::NUM_RETRIES
} else {
1
};
let mut rng = fastrand::Rng::new();
for i in 0..num_retries {
#[cfg(all(
feature = "getrandom",
any(windows, unix, target_os = "redox", target_os = "wasi")
))]
if i == 3 {
if let Ok(seed) = getrandom::u64() {
rng.seed(seed);
}
}
let path = base.join(tmpname(&mut rng, prefix, suffix, random_len));
return match f(path) {
Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists && num_retries > 1 => continue,
Err(ref e) if e.kind() == io::ErrorKind::AddrInUse && num_retries > 1 => continue,
res => res,
};
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"too many temporary files exist",
))
.with_err_path(|| base)
}