1 use fastrand;
2 use std::ffi::{OsStr, OsString};
3 use std::path::{Path, PathBuf};
4 use std::{io, iter::repeat_with};
5
6 use crate::error::IoResultExt;
7
tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString8 fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
9 let mut buf = OsString::with_capacity(prefix.len() + suffix.len() + rand_len);
10 buf.push(prefix);
11 let mut char_buf = [0u8; 4];
12 for c in repeat_with(fastrand::alphanumeric).take(rand_len) {
13 buf.push(c.encode_utf8(&mut char_buf));
14 }
15 buf.push(suffix);
16 buf
17 }
18
create_helper<F, R>( base: &Path, prefix: &OsStr, suffix: &OsStr, random_len: usize, f: F, ) -> io::Result<R> where F: Fn(PathBuf) -> io::Result<R>,19 pub fn create_helper<F, R>(
20 base: &Path,
21 prefix: &OsStr,
22 suffix: &OsStr,
23 random_len: usize,
24 f: F,
25 ) -> io::Result<R>
26 where
27 F: Fn(PathBuf) -> io::Result<R>,
28 {
29 let num_retries = if random_len != 0 {
30 crate::NUM_RETRIES
31 } else {
32 1
33 };
34
35 for _ in 0..num_retries {
36 let path = base.join(tmpname(prefix, suffix, random_len));
37 return match f(path) {
38 Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
39 res => res,
40 };
41 }
42
43 Err(io::Error::new(
44 io::ErrorKind::AlreadyExists,
45 "too many temporary files exist",
46 ))
47 .with_err_path(|| base)
48 }
49