Skip to content

Commit

Permalink
feat: replace rand with fastrand
Browse files Browse the repository at this point in the history
  • Loading branch information
Joshua Li authored and Stebalien committed Jan 8, 2022
1 parent 3e439d3 commit f83a062
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 22 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
28 changes: 7 additions & 21 deletions src/util.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,18 @@
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)
buf.push(
repeat_with(fastrand::alphanumeric)
.take(rand_len)
.for_each(|b| buf.push(str::from_utf8_unchecked(&[b as u8])))
});
.collect::<String>(),
);
buf.push(suffix);
buf
}
Expand Down

0 comments on commit f83a062

Please sign in to comment.