1 | use std::ffi::{OsStr, OsString}; |
2 | use std::path::{Path, PathBuf}; |
3 | use std::{io, iter::repeat_with}; |
4 | |
5 | use crate::error::IoResultExt; |
6 | |
7 | fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString { |
8 | let capacity: usize = prefixusize |
9 | .len() |
10 | .saturating_add(suffix.len()) |
11 | .saturating_add(rand_len); |
12 | let mut buf: OsString = OsString::with_capacity(capacity); |
13 | buf.push(prefix); |
14 | let mut char_buf: [u8; 4] = [0u8; 4]; |
15 | for c: char in repeat_with(repeater:fastrand::alphanumeric).take(rand_len) { |
16 | buf.push(c.encode_utf8(&mut char_buf)); |
17 | } |
18 | buf.push(suffix); |
19 | buf |
20 | } |
21 | |
22 | pub fn create_helper<R>( |
23 | base: &Path, |
24 | prefix: &OsStr, |
25 | suffix: &OsStr, |
26 | random_len: usize, |
27 | permissions: Option<&std::fs::Permissions>, |
28 | mut f: impl FnMut(PathBuf, Option<&std::fs::Permissions>) -> io::Result<R>, |
29 | ) -> io::Result<R> { |
30 | let num_retries: u32 = if random_len != 0 { |
31 | crate::NUM_RETRIES |
32 | } else { |
33 | 1 |
34 | }; |
35 | |
36 | for _ in 0..num_retries { |
37 | let path: PathBuf = base.join(path:tmpname(prefix, suffix, rand_len:random_len)); |
38 | return match f(path, permissions) { |
39 | Err(ref e: &Error) if e.kind() == io::ErrorKind::AlreadyExists && num_retries > 1 => continue, |
40 | // AddrInUse can happen if we're creating a UNIX domain socket and |
41 | // the path already exists. |
42 | Err(ref e: &Error) if e.kind() == io::ErrorKind::AddrInUse && num_retries > 1 => continue, |
43 | res: Result => res, |
44 | }; |
45 | } |
46 | |
47 | ErrResult(io::Error::new( |
48 | kind:io::ErrorKind::AlreadyExists, |
49 | error:"too many temporary files exist" , |
50 | )) |
51 | .with_err_path(|| base) |
52 | } |
53 | |