From a84d09b42975fa7eae1d76da78366bd5511b2955 Mon Sep 17 00:00:00 2001 From: Jake McGinty Date: Thu, 25 Mar 2021 02:45:38 +0900 Subject: [PATCH] use rand's SmallRng for random number generation --- Cargo.toml | 2 +- src/util.rs | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2b008dacc..b217cf6ff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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] diff --git a/src/util.rs b/src/util.rs index aa76bb256..fda76762a 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,12 +1,22 @@ -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> = 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); @@ -14,7 +24,7 @@ fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString { // 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])))