Skip to content

Commit

Permalink
Run Rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
josephlr committed Jun 10, 2019
1 parent 16444be commit 26af4ae
Show file tree
Hide file tree
Showing 21 changed files with 165 additions and 134 deletions.
7 changes: 3 additions & 4 deletions benches/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
#![feature(test)]
extern crate test;
extern crate getrandom;
extern crate test;

#[bench]
fn bench_64(b: &mut test::Bencher) {
let mut buf = [0u8; 64];
b.iter(|| {
getrandom::getrandom(&mut buf[..]).unwrap();
test::black_box(&buf);
test::black_box(&buf);
});
b.bytes = buf.len() as u64;
}
Expand All @@ -17,8 +17,7 @@ fn bench_65536(b: &mut test::Bencher) {
let mut buf = [0u8; 65536];
b.iter(|| {
getrandom::getrandom(&mut buf[..]).unwrap();
test::black_box(&buf);
test::black_box(&buf);
});
b.bytes = buf.len() as u64;
}

6 changes: 4 additions & 2 deletions src/cloudabi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
// except according to those terms.

//! Implementation for CloudABI
use core::num::NonZeroU32;
use crate::Error;
use core::num::NonZeroU32;

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
let errno = unsafe { cloudabi::random_get(dest) };
Expand All @@ -22,4 +22,6 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
6 changes: 4 additions & 2 deletions src/dummy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@

//! A dummy implementation for unsupported targets which always returns
//! `Err(Error::UNAVAILABLE)`
use core::num::NonZeroU32;
use crate::Error;
use core::num::NonZeroU32;

pub fn getrandom_inner(_: &mut [u8]) -> Result<(), Error> {
error!("no support for this platform");
Err(Error::UNAVAILABLE)
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
14 changes: 5 additions & 9 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::num::NonZeroU32;
use core::convert::From;
use core::fmt;
use core::num::NonZeroU32;

// A randomly-chosen 24-bit prefix for our codes
pub(crate) const CODE_PREFIX: u32 = 0x57f4c500;
Expand All @@ -22,14 +22,10 @@ pub struct Error(pub(crate) NonZeroU32);

impl Error {
/// An unknown error.
pub const UNKNOWN: Error = Error(unsafe {
NonZeroU32::new_unchecked(CODE_UNKNOWN)
});
pub const UNKNOWN: Error = Error(unsafe { NonZeroU32::new_unchecked(CODE_UNKNOWN) });

/// No generator is available.
pub const UNAVAILABLE: Error = Error(unsafe {
NonZeroU32::new_unchecked(CODE_UNAVAILABLE)
});
pub const UNAVAILABLE: Error = Error(unsafe { NonZeroU32::new_unchecked(CODE_UNAVAILABLE) });

/// Extract the error code.
///
Expand All @@ -48,7 +44,7 @@ impl Error {
match *self {
Error::UNKNOWN => Some("getrandom: unknown error"),
Error::UNAVAILABLE => Some("getrandom: unavailable"),
_ => None
_ => None,
}
}
}
Expand Down Expand Up @@ -80,8 +76,8 @@ impl From<NonZeroU32> for Error {

#[cfg(test)]
mod tests {
use core::mem::size_of;
use super::Error;
use core::mem::size_of;

#[test]
fn test_size() {
Expand Down
6 changes: 3 additions & 3 deletions src/error_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
// except according to those terms.
extern crate std;

use std::{io, error};
use crate::error::Error;
use core::convert::From;
use core::num::NonZeroU32;
use crate::error::Error;
use std::{error, io};

impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Expand All @@ -31,4 +31,4 @@ impl From<Error> for io::Error {
}
}

impl error::Error for Error { }
impl error::Error for Error {}
16 changes: 11 additions & 5 deletions src/freebsd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
extern crate std;

use crate::Error;
use std::io;
use core::ptr;
use core::num::NonZeroU32;
use core::ptr;
use std::io;

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
let mib = [libc::CTL_KERN, libc::KERN_ARND];
Expand All @@ -21,8 +21,12 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
let mut len = chunk.len();
let ret = unsafe {
libc::sysctl(
mib.as_ptr(), mib.len() as libc::c_uint,
chunk.as_mut_ptr() as *mut _, &mut len, ptr::null(), 0,
mib.as_ptr(),
mib.len() as libc::c_uint,
chunk.as_mut_ptr() as *mut _,
&mut len,
ptr::null(),
0,
)
};
if ret == -1 || len != chunk.len() {
Expand All @@ -34,4 +38,6 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
6 changes: 4 additions & 2 deletions src/fuchsia.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
// except according to those terms.

//! Implementation for Fuchsia Zircon
use core::num::NonZeroU32;
use crate::Error;
use core::num::NonZeroU32;

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
fuchsia_cprng::cprng_draw(dest);
Ok(())
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
33 changes: 17 additions & 16 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@
//! features are activated for this crate. Note that if both features are
//! enabled `wasm-bindgen` will be used. If neither feature is enabled,
//! `getrandom` will always fail.
//!
//!
//! The WASI target `wasm32-wasi` uses the `__wasi_random_get` function defined
//! by the WASI standard.
//!
//!
//!
//! ## Early boot
//!
Expand Down Expand Up @@ -115,23 +115,28 @@
//! [16]: #support-for-webassembly-and-amsjs
//! [17]: https://github.com/CraneStation/wasmtime/blob/master/docs/WASI-api.md#__wasi_random_get
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://rust-random.github.io/rand/")]
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://rust-random.github.io/rand/"
)]
#![no_std]
#![cfg_attr(feature = "stdweb", recursion_limit="128")]
#![cfg_attr(feature = "stdweb", recursion_limit = "128")]

#[cfg(feature = "log")]
#[macro_use]
extern crate log;
#[cfg(not(feature = "log"))]
#[allow(unused)]
macro_rules! error { ($($x:tt)*) => () }
macro_rules! error {
($($x:tt)*) => {};
}

// temp fix for stdweb
#[cfg(target_arch = "wasm32")]
extern crate std;

mod error;
#[cfg(any(
target_os = "android",
target_os = "netbsd",
Expand All @@ -141,13 +146,9 @@ extern crate std;
target_os = "dragonfly",
target_os = "haiku",
target_os = "linux",
all(
target_arch = "wasm32",
not(target_os = "wasi")
),
all(target_arch = "wasm32", not(target_os = "wasi")),
))]
mod utils;
mod error;
pub use crate::error::Error;

// System-specific implementations.
Expand All @@ -159,13 +160,14 @@ macro_rules! mod_use {
#[$cond]
mod $module;
#[$cond]
use crate::$module::{getrandom_inner, error_msg_inner};
}
use crate::$module::{error_msg_inner, getrandom_inner};
};
}

#[cfg(any(
feature = "std",
windows, unix,
windows,
unix,
target_os = "cloudabi",
target_os = "redox",
target_arch = "wasm32",
Expand Down Expand Up @@ -246,7 +248,6 @@ mod_use!(
dummy
);


/// Fill `dest` with random bytes from the system's preferred random number
/// source.
///
Expand Down
58 changes: 33 additions & 25 deletions src/linux_android.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@
//! Implementation for Linux / Android
extern crate std;

use crate::Error;
use crate::utils::use_init;
use std::{thread_local, io::{self, Read}, fs::File};
use crate::Error;
use core::cell::RefCell;
use core::num::NonZeroU32;
use core::sync::atomic::{AtomicBool, Ordering};
use std::{
fs::File,
io::{self, Read},
thread_local,
};

static RNG_INIT: AtomicBool = AtomicBool::new(false);

Expand All @@ -28,9 +32,7 @@ thread_local!(
);

fn syscall_getrandom(dest: &mut [u8]) -> Result<(), io::Error> {
let ret = unsafe {
libc::syscall(libc::SYS_getrandom, dest.as_mut_ptr(), dest.len(), 0)
};
let ret = unsafe { libc::syscall(libc::SYS_getrandom, dest.as_mut_ptr(), dest.len(), 0) };
if ret < 0 || (ret as usize) != dest.len() {
error!("Linux getrandom syscall failed with return value {}", ret);
return Err(io::Error::last_os_error());
Expand All @@ -40,26 +42,30 @@ fn syscall_getrandom(dest: &mut [u8]) -> Result<(), io::Error> {

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
RNG_SOURCE.with(|f| {
use_init(f,
|| {
let s = if is_getrandom_available() {
RngSource::GetRandom
} else {
// read one byte from "/dev/random" to ensure that
// OS RNG has initialized
if !RNG_INIT.load(Ordering::Relaxed) {
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
RNG_INIT.store(true, Ordering::Relaxed)
use_init(
f,
|| {
let s = if is_getrandom_available() {
RngSource::GetRandom
} else {
// read one byte from "/dev/random" to ensure that
// OS RNG has initialized
if !RNG_INIT.load(Ordering::Relaxed) {
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
RNG_INIT.store(true, Ordering::Relaxed)
}
RngSource::Device(File::open("/dev/urandom")?)
};
Ok(s)
},
|f| {
match f {
RngSource::GetRandom => syscall_getrandom(dest),
RngSource::Device(f) => f.read_exact(dest),
}
RngSource::Device(File::open("/dev/urandom")?)
};
Ok(s)
}, |f| {
match f {
RngSource::GetRandom => syscall_getrandom(dest),
RngSource::Device(f) => f.read_exact(dest),
}.map_err(From::from)
})
.map_err(From::from)
},
)
})
}

Expand All @@ -82,4 +88,6 @@ fn is_getrandom_available() -> bool {
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
12 changes: 8 additions & 4 deletions src/macos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
extern crate std;

use crate::Error;
use std::io;
use core::num::NonZeroU32;
use std::io;

enum SecRandom {}

Expand All @@ -20,9 +20,11 @@ enum SecRandom {}
const kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;

#[link(name = "Security", kind = "framework")]
extern {
extern "C" {
fn SecRandomCopyBytes(
rnd: *const SecRandom, count: libc::size_t, bytes: *mut u8,
rnd: *const SecRandom,
count: libc::size_t,
bytes: *mut u8,
) -> libc::c_int;
}

Expand All @@ -43,4 +45,6 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
Loading

0 comments on commit 26af4ae

Please sign in to comment.