Skip to content

Commit

Permalink
Remove lazy_static dependancy
Browse files Browse the repository at this point in the history
  • Loading branch information
josephlr committed Jul 4, 2019
1 parent 442fb43 commit c199187
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 14 deletions.
4 changes: 0 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@ log = { version = "0.4", optional = true }
[target.'cfg(any(unix, target_os = "redox", 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 }
Expand Down
25 changes: 15 additions & 10 deletions src/use_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@
//! Implementations that just need to read from a file
extern crate std;

use crate::util_libc::LazyFd;
use crate::Error;
use core::mem::ManuallyDrop;
use core::num::NonZeroU32;
use lazy_static::lazy_static;
use std::os::unix::io::{FromRawFd, IntoRawFd, RawFd};
use std::{fs::File, io::Read};

#[cfg(target_os = "redox")]
Expand All @@ -29,28 +31,31 @@ 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<File, Error> = init_file();
}
let mut f = FILE.as_ref()?;
static FD: LazyFd = LazyFd::new();
let fd = FD.init(init_file).ok_or(Error::UNKNOWN)?;
let file = ManuallyDrop::new(unsafe { File::from_raw_fd(fd) });
let mut file_ref: &File = &file;

if cfg!(target_os = "emscripten") {
// `Crypto.getRandomValues` documents `dest` should be at most 65536 bytes.
for chunk in dest.chunks_mut(65536) {
f.read_exact(chunk)?;
file_ref.read_exact(chunk)?;
}
} else {
f.read_exact(dest)?;
file_ref.read_exact(dest)?;
}
Ok(())
}

fn init_file() -> Result<File, Error> {
fn init_file() -> Option<RawFd> {
if FILE_PATH == "/dev/urandom" {
// read one byte from "/dev/random" to ensure that OS RNG has initialized
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
File::open("/dev/random")
.ok()?
.read_exact(&mut [0u8; 1])
.ok()?;
}
Ok(File::open(FILE_PATH)?)
Some(File::open(FILE_PATH).ok()?.into_raw_fd())
}

#[inline(always)]
Expand Down

0 comments on commit c199187

Please sign in to comment.