From 7e539632dd32b55d98382d38421962bc103d3830 Mon Sep 17 00:00:00 2001 From: Joe Richey Date: Thu, 7 Feb 2019 03:47:41 -0800 Subject: [PATCH] Use spin instead of lazy_static I agree to license my contributions to each file under the terms given at the top of each file I changed. --- Cargo.toml | 5 ----- src/rand.rs | 40 +++++++++++++--------------------------- 2 files changed, 13 insertions(+), 32 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4a66b38f77..eb4250c33c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -304,11 +304,6 @@ libc = { version = "0.2.48", default_features = false } [target.'cfg(not(target_os = "ios"))'.dependencies] spin = { version = "0.5.0" } -[target.'cfg(any(target_os = "android", target_os = "linux"))'.dependencies] - -[target.'cfg(any(target_os = "redox", all(unix, not(any(target_os = "macos", target_os = "ios")))))'.dependencies] -lazy_static = "1.2" - [target.'cfg(target_os = "windows")'.dependencies] winapi = { version = "0.3.6", default_features = false, features = ["ntsecapi", "wtypesbase"] } diff --git a/src/rand.rs b/src/rand.rs index b6fb6bc4ca..8f246a08d2 100644 --- a/src/rand.rs +++ b/src/rand.rs @@ -208,23 +208,19 @@ mod sysrand { ))] mod urandom { use crate::error; + use spin::Once; use std; pub fn fill(dest: &mut [u8]) -> Result<(), error::Unspecified> { - use lazy_static::lazy_static; + static OPEN: Once> = Once::new(); #[cfg(target_os = "redox")] static RANDOM_PATH: &str = "rand:"; #[cfg(unix)] static RANDOM_PATH: &str = "/dev/urandom"; - lazy_static! { - static ref FILE: Result = - std::fs::File::open(RANDOM_PATH); - } - - match *FILE { - Ok(ref file) => { + match OPEN.call_once(|| std::fs::File::open(RANDOM_PATH)) { + Ok(file) => { use std::io::Read; (&*file).read_exact(dest).map_err(|_| error::Unspecified) }, @@ -237,29 +233,19 @@ mod urandom { #[cfg(all(target_os = "linux", feature = "dev_urandom_fallback"))] mod sysrand_or_urandom { use crate::error; + use spin::Once; - enum Mechanism { - Sysrand, - DevURandom, + fn sysrand_supported() -> bool { + let mut dummy = [0u8; 1]; + super::sysrand_chunk::chunk(&mut dummy[..]).is_ok() } pub fn fill(dest: &mut [u8]) -> Result<(), error::Unspecified> { - use lazy_static::lazy_static; - - lazy_static! { - static ref MECHANISM: Mechanism = { - let mut dummy = [0u8; 1]; - if super::sysrand_chunk::chunk(&mut dummy[..]).is_err() { - Mechanism::DevURandom - } else { - Mechanism::Sysrand - } - }; - } - - match *MECHANISM { - Mechanism::Sysrand => super::sysrand::fill(dest), - Mechanism::DevURandom => super::urandom::fill(dest), + static SYSRAND_SUPPORTED: Once = Once::new(); + if *SYSRAND_SUPPORTED.call_once(sysrand_supported) { + super::sysrand::fill(dest) + } else { + super::urandom::fill(dest) } } }