Skip to content

Commit

Permalink
Merge pull request #162 from Stebalien/ref/replace-rand-with-fastrand
Browse files Browse the repository at this point in the history
replace rand with fastrand
  • Loading branch information
Stebalien authored Jan 8, 2022
2 parents 3e439d3 + e24fae3 commit 09e0b4b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 23 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ description = "A library for managing temporary files and directories."

[dependencies]
cfg-if = "1"
rand = { version = "0.8", features = ["small_rng", "getrandom"], default_features = false }
fastrand = "1.2.3"
remove_dir_all = "0.5"

[target.'cfg(any(unix, target_os = "wasi"))'.dependencies]
Expand Down
29 changes: 7 additions & 22 deletions src/util.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,17 @@
use rand::{self, Rng, SeedableRng};
use rand::{distributions::Alphanumeric, rngs::SmallRng};
use fastrand;
use std::ffi::{OsStr, OsString};
use std::thread_local;
use std::{
cell::UnsafeCell,
path::{Path, PathBuf},
};
use std::{io, str};
use std::path::{Path, PathBuf};
use std::{io, iter::repeat_with};

use crate::error::IoResultExt;

thread_local! {
static THREAD_RNG: UnsafeCell<SmallRng> = UnsafeCell::new(SmallRng::from_entropy());
}

fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
let mut buf = OsString::with_capacity(prefix.len() + suffix.len() + rand_len);
buf.push(prefix);

// Push each character in one-by-one. Unfortunately, this is the only
// safe(ish) simple way to do this without allocating a temporary
// String/Vec.
THREAD_RNG.with(|rng| unsafe {
(&mut *rng.get())
.sample_iter(&Alphanumeric)
.take(rand_len)
.for_each(|b| buf.push(str::from_utf8_unchecked(&[b as u8])))
});
let mut char_buf = [0u8; 4];
for c in repeat_with(fastrand::alphanumeric).take(rand_len) {
buf.push(c.encode_utf8(&mut char_buf));
}
buf.push(suffix);
buf
}
Expand Down

0 comments on commit 09e0b4b

Please sign in to comment.