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