tempfile/
util.rs

1use rand::distributions::Alphanumeric;
2use rand::{self, Rng};
3use std::ffi::{OsStr, OsString};
4use std::path::{Path, PathBuf};
5use std::{io, str};
6
7use crate::error::IoResultExt;
8
9fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
10    let mut buf = OsString::with_capacity(prefix.len() + suffix.len() + rand_len);
11    buf.push(prefix);
12
13    // Push each character in one-by-one. Unfortunately, this is the only
14    // safe(ish) simple way to do this without allocating a temporary
15    // String/Vec.
16    unsafe {
17        rand::thread_rng()
18            .sample_iter(&Alphanumeric)
19            .take(rand_len)
20            .for_each(|b| buf.push(str::from_utf8_unchecked(&[b as u8])))
21    }
22    buf.push(suffix);
23    buf
24}
25
26pub fn create_helper<F, R>(
27    base: &Path,
28    prefix: &OsStr,
29    suffix: &OsStr,
30    random_len: usize,
31    f: F,
32) -> io::Result<R>
33where
34    F: Fn(PathBuf) -> io::Result<R>,
35{
36    let num_retries = if random_len != 0 {
37        crate::NUM_RETRIES
38    } else {
39        1
40    };
41
42    for _ in 0..num_retries {
43        let path = base.join(tmpname(prefix, suffix, random_len));
44        return match f(path) {
45            Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
46            res => res,
47        };
48    }
49
50    Err(io::Error::new(
51        io::ErrorKind::AlreadyExists,
52        "too many temporary files exist",
53    ))
54    .with_err_path(|| base)
55}