From f83a062eb052271108f939494837d499003d6c52 Mon Sep 17 00:00:00 2001 From: Joshua Li Date: Wed, 17 Jun 2020 11:24:27 -0700 Subject: [PATCH 1/2] feat: replace rand with fastrand --- Cargo.toml | 2 +- src/util.rs | 28 +++++++--------------------- 2 files changed, 8 insertions(+), 22 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6682f83f3..4d476b936 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 = { 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] diff --git a/src/util.rs b/src/util.rs index 01beeedea..2bd00b249 100644 --- a/src/util.rs +++ b/src/util.rs @@ -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 = 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::(), + ); buf.push(suffix); buf } From e24fae3ac2857544c608ad4727710a70d7631a14 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Sat, 8 Jan 2022 10:46:37 -0800 Subject: [PATCH 2/2] chore: avoid allocation when generating temp names --- src/util.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/util.rs b/src/util.rs index 2bd00b249..8c91b9c69 100644 --- a/src/util.rs +++ b/src/util.rs @@ -8,11 +8,10 @@ use crate::error::IoResultExt; 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); - buf.push( - repeat_with(fastrand::alphanumeric) - .take(rand_len) - .collect::(), - ); + 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 }