From 439e982fec50bd8b1c0b99276b51c8f4a520f580 Mon Sep 17 00:00:00 2001 From: Joe Richey Date: Mon, 1 Jul 2019 16:08:57 -0700 Subject: [PATCH] Remove lazy_static dependancy --- Cargo.toml | 5 ----- src/use_file.rs | 13 +++++++------ src/wasm32_stdweb.rs | 11 ++++++----- 3 files changed, 13 insertions(+), 16 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9a4be7d0..fbf8e2b6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,14 +23,9 @@ log = { version = "0.4", optional = true } [target.'cfg(any(unix, target_os = "wasi"))'.dependencies] libc = "0.2.54" -# For holding file descriptors -[target.'cfg(any(unix, target_os = "redox"))'.dependencies] -lazy_static = "1.3.0" - [target.wasm32-unknown-unknown.dependencies] wasm-bindgen = { version = "0.2.29", optional = true } stdweb = { version = "0.4.9", optional = true } -lazy_static = "1.3.0" [features] std = [] diff --git a/src/use_file.rs b/src/use_file.rs index 5437a17a..2564e061 100644 --- a/src/use_file.rs +++ b/src/use_file.rs @@ -11,8 +11,7 @@ extern crate std; use crate::Error; use core::num::NonZeroU32; -use lazy_static::lazy_static; -use std::{fs::File, io::Read}; +use std::{fs::File, io::Read, sync::Once}; #[cfg(target_os = "redox")] const FILE_PATH: &str = "rand:"; @@ -29,10 +28,12 @@ const FILE_PATH: &str = "/dev/urandom"; const FILE_PATH: &str = "/dev/random"; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - lazy_static! { - static ref FILE: Result = init_file(); - } - let mut f = FILE.as_ref()?; + static ONCE: Once = Once::new(); + static mut FILE: Option> = None; + + // SAFETY: FILE is only written once, before being read. + ONCE.call_once(|| unsafe { FILE = Some(init_file()); }); + let mut f = unsafe { FILE.as_ref() }.unwrap().as_ref()?; if cfg!(target_os = "emscripten") { // `Crypto.getRandomValues` documents `dest` should be at most 65536 bytes. diff --git a/src/wasm32_stdweb.rs b/src/wasm32_stdweb.rs index aae12eb4..795cb5eb 100644 --- a/src/wasm32_stdweb.rs +++ b/src/wasm32_stdweb.rs @@ -15,7 +15,7 @@ use stdweb::web::error::Error as WebError; use stdweb::{_js_impl, js}; use crate::Error; -use lazy_static::lazy_static; +use std::sync::Once; #[derive(Clone, Copy, Debug)] enum RngSource { @@ -25,11 +25,12 @@ enum RngSource { pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { assert_eq!(mem::size_of::(), 4); + static ONCE: Once = Once::new(); + static mut RNG_SOURCE: Result = Err(Error::UNAVAILABLE); - lazy_static! { - static ref RNG_SOURCE: Result = getrandom_init(); - } - getrandom_fill((*RNG_SOURCE)?, dest) + // SAFETY: RNG_SOURCE is only written once, before being read. + ONCE.call_once(|| unsafe { RNG_SOURCE = getrandom_init(); }); + getrandom_fill(unsafe { RNG_SOURCE }?, dest) } fn getrandom_init() -> Result {