Skip to content

Commit

Permalink
use rand's SmallRng for random number generation
Browse files Browse the repository at this point in the history
  • Loading branch information
mcginty committed Mar 24, 2021
1 parent b375460 commit a84d09b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 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 = "0.8"
rand = { version = "0.8", features = ["small_rng", "getrandom"], default_features = false }
remove_dir_all = "0.5"

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

use crate::error::IoResultExt;

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

fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
let rng = THREAD_RNG_KEY.with(|t| t.clone());
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.
unsafe {
rand::thread_rng()
(&mut *rng.get())
.sample_iter(&Alphanumeric)
.take(rand_len)
.for_each(|b| buf.push(str::from_utf8_unchecked(&[b as u8])))
Expand Down

0 comments on commit a84d09b

Please sign in to comment.