Run Rustfmt on entire repo

This commit is contained in:
Joe Richey 2019-06-26 01:22:35 -07:00
parent af4ea8dc47
commit 3d8373b89d
21 changed files with 119 additions and 90 deletions

View File

@ -28,7 +28,7 @@ matrix:
install:
- rustup component add rustfmt
script:
- cargo fmt --all -- src/*.rs --check
- cargo fmt --all -- */*.rs --check
- rust: nightly
os: linux

View File

@ -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;
}
@ -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;
}

View File

@ -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) };
@ -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
}

View File

@ -8,8 +8,8 @@
//! 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");
@ -17,4 +17,6 @@ pub fn getrandom_inner(_: &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
}

View File

@ -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;
@ -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.
///
@ -48,7 +44,7 @@ impl Error {
match *self {
Error::UNKNOWN => Some("getrandom: unknown error"),
Error::UNAVAILABLE => Some("getrandom: unavailable"),
_ => None
_ => None,
}
}
}
@ -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() {

View File

@ -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 {
@ -31,4 +31,4 @@ impl From<Error> for io::Error {
}
}
impl error::Error for Error { }
impl error::Error for Error {}

View File

@ -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;
fn kern_arnd(buf: &mut [u8]) -> Result<usize, Error> {
static MIB: [libc::c_int; 2] = [libc::CTL_KERN, libc::KERN_ARND];
@ -43,4 +43,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
}

View File

@ -7,8 +7,8 @@
// 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);
@ -16,4 +16,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
}

View File

@ -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
//!
@ -115,18 +115,22 @@
//! [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")]
@ -144,13 +148,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",
@ -238,7 +243,6 @@ mod_use!(
dummy
);
/// Fill `dest` with random bytes from the system's preferred random number
/// source.
///

View File

@ -16,9 +16,7 @@ use std::io;
fn syscall_getrandom(dest: &mut [u8], block: bool) -> Result<usize, io::Error> {
let flags = if block { 0 } else { libc::GRND_NONBLOCK };
let ret = unsafe {
libc::syscall(libc::SYS_getrandom, dest.as_mut_ptr(), dest.len(), flags)
};
let ret = unsafe { libc::syscall(libc::SYS_getrandom, dest.as_mut_ptr(), dest.len(), flags) };
if ret < 0 {
let err = io::Error::last_os_error();
if err.raw_os_error() == Some(libc::EINTR) {
@ -31,7 +29,9 @@ fn syscall_getrandom(dest: &mut [u8], block: bool) -> Result<usize, io::Error> {
}
pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
lazy_static! { static ref HAS_GETRANDOM: bool = is_getrandom_available(); }
lazy_static! {
static ref HAS_GETRANDOM: bool = is_getrandom_available();
}
match *HAS_GETRANDOM {
true => {
let mut start = 0;
@ -39,7 +39,7 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
start += syscall_getrandom(&mut dest[start..], true)?;
}
Ok(())
},
}
false => use_file::getrandom_inner(dest),
}
}
@ -48,12 +48,14 @@ fn is_getrandom_available() -> bool {
match syscall_getrandom(&mut [], false) {
Err(err) => match err.raw_os_error() {
Some(libc::ENOSYS) => false, // No kernel support
Some(libc::EPERM) => false, // Blocked by seccomp
Some(libc::EPERM) => false, // Blocked by seccomp
_ => true,
}
},
Ok(_) => true,
}
}
#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}

View File

@ -10,8 +10,8 @@
extern crate std;
use crate::Error;
use std::io;
use core::num::NonZeroU32;
use std::io;
// TODO: Make extern once extern_types feature is stabilized. See:
// https://github.com/rust-lang/rust/issues/43467
@ -19,7 +19,7 @@ use core::num::NonZeroU32;
struct SecRandom([u8; 0]);
#[link(name = "Security", kind = "framework")]
extern {
extern "C" {
static kSecRandomDefault: *const SecRandom;
fn SecRandomCopyBytes(rnd: *const SecRandom, count: usize, bytes: *mut u8) -> libc::c_int;
@ -36,4 +36,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
}

View File

@ -15,12 +15,7 @@ use std::num::NonZeroU32;
pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
for chunk in dest.chunks_mut(256) {
let ret = unsafe {
libc::getentropy(
chunk.as_mut_ptr() as *mut libc::c_void,
chunk.len()
)
};
let ret = unsafe { libc::getentropy(chunk.as_mut_ptr() as *mut libc::c_void, chunk.len()) };
if ret == -1 {
error!("libc::getentropy call failed");
return Err(io::Error::last_os_error().into());
@ -30,4 +25,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
}

View File

@ -8,8 +8,8 @@
//! Implementation for SGX using RDRAND instruction
use crate::Error;
use core::mem;
use core::arch::x86_64::{__cpuid, _rdrand64_step};
use core::mem;
use core::num::NonZeroU32;
use lazy_static::lazy_static;
@ -80,4 +80,6 @@ unsafe fn rdrand_exact(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
}

View File

@ -42,7 +42,9 @@ fn libc_getrandom(rand: GetRandomFn, dest: &mut [u8]) -> Result<(), Error> {
}
pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
lazy_static! { static ref GETRANDOM_FUNC: Option<GetRandomFn> = fetch_getrandom(); }
lazy_static! {
static ref GETRANDOM_FUNC: Option<GetRandomFn> = fetch_getrandom();
}
// 256 bytes is the lowest common denominator across all the Solaris
// derived platforms for atomically obtaining random data.
@ -62,4 +64,6 @@ fn fetch_getrandom() -> Option<GetRandomFn> {
}
#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}

View File

@ -32,7 +32,9 @@ 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 RNG_FD: Result<RawFd, Error> = init_file(); }
lazy_static! {
static ref RNG_FD: Result<RawFd, Error> = init_file();
}
let mut f = unsafe { File::from_raw_fd((*RNG_FD)?) };
if cfg!(target_os = "emscripten") {
@ -56,4 +58,6 @@ fn init_file() -> Result<RawFd, Error> {
#[inline(always)]
#[allow(dead_code)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}

View File

@ -12,9 +12,8 @@ use core::num::NonZeroU32;
use std::io;
pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
let ret = unsafe {
libc::__wasi_random_get(dest.as_mut_ptr() as *mut libc::c_void, dest.len())
};
let ret =
unsafe { libc::__wasi_random_get(dest.as_mut_ptr() as *mut libc::c_void, dest.len()) };
if ret == libc::__WASI_ESUCCESS {
Ok(())
} else {
@ -24,4 +23,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
}

View File

@ -14,8 +14,8 @@ use std::thread_local;
use wasm_bindgen::prelude::*;
use crate::Error;
use crate::error::CODE_PREFIX;
use crate::Error;
const CODE_CRYPTO_UNDEF: u32 = CODE_PREFIX | 0x80;
const CODE_GRV_UNDEF: u32 = CODE_PREFIX | 0x81;
@ -72,7 +72,7 @@ fn getrandom_init() -> Result<RngSource, Error> {
let is_browser = this.self_() != JsValue::undefined();
if !is_browser {
return Ok(RngSource::Node(node_require("crypto")))
return Ok(RngSource::Node(node_require("crypto")));
}
// If `self` is defined then we're in a browser somehow (main window
@ -104,7 +104,7 @@ pub fn error_msg_inner(n: NonZeroU32) -> Option<&'static str> {
match n.get() {
CODE_CRYPTO_UNDEF => Some("getrandom: self.crypto is undefined"),
CODE_GRV_UNDEF => Some("crypto.getRandomValues is undefined"),
_ => None
_ => None,
}
}

View File

@ -10,9 +10,9 @@
use core::mem;
use core::num::NonZeroU32;
use stdweb::{js, _js_impl};
use stdweb::unstable::TryInto;
use stdweb::web::error::Error as WebError;
use stdweb::{_js_impl, js};
use crate::Error;
use lazy_static::lazy_static;
@ -20,13 +20,15 @@ use lazy_static::lazy_static;
#[derive(Clone, Copy, Debug)]
enum RngSource {
Browser,
Node
Node,
}
pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
assert_eq!(mem::size_of::<usize>(), 4);
lazy_static! { static ref RNG_SOURCE: Result<RngSource, Error> = getrandom_init(); }
lazy_static! {
static ref RNG_SOURCE: Result<RngSource, Error> = getrandom_init();
}
getrandom_fill((*RNG_SOURCE)?, dest)
}
@ -51,14 +53,18 @@ fn getrandom_init() -> Result<RngSource, Error> {
}
};
if js!{ return @{ result.as_ref() }.success } == true {
let ty = js!{ return @{ result }.ty };
if js! { return @{ result.as_ref() }.success } == true {
let ty = js! { return @{ result }.ty };
if ty == 1 { Ok(RngSource::Browser) }
else if ty == 2 { Ok(RngSource::Node) }
else { unreachable!() }
if ty == 1 {
Ok(RngSource::Browser)
} else if ty == 2 {
Ok(RngSource::Node)
} else {
unreachable!()
}
} else {
let err: WebError = js!{ return @{ result }.error }.try_into().unwrap();
let err: WebError = js! { return @{ result }.error }.try_into().unwrap();
error!("getrandom unavailable: {}", err);
Err(Error::UNAVAILABLE)
}
@ -90,17 +96,19 @@ fn getrandom_fill(source: RngSource, dest: &mut [u8]) -> Result<(), Error> {
} catch(err) {
return { success: false, error: err };
}
}
},
};
if js!{ return @{ result.as_ref() }.success } != true {
let err: WebError = js!{ return @{ result }.error }.try_into().unwrap();
if js! { return @{ result.as_ref() }.success } != true {
let err: WebError = js! { return @{ result }.error }.try_into().unwrap();
error!("getrandom failed: {}", err);
return Err(Error::UNKNOWN)
return Err(Error::UNKNOWN);
}
}
Ok(())
}
#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}

View File

@ -9,12 +9,12 @@
//! Implementation for Windows
extern crate std;
use crate::Error;
use core::num::NonZeroU32;
use std::io;
use winapi::shared::minwindef::ULONG;
use winapi::um::ntsecapi::RtlGenRandom;
use winapi::um::winnt::PVOID;
use std::io;
use core::num::NonZeroU32;
use crate::Error;
pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
// Prevent overflow of ULONG
@ -29,4 +29,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
}

View File

@ -31,18 +31,18 @@ fn test_huge() {
getrandom(&mut huge).unwrap();
}
#[cfg(any(unix, windows, target_os="redox", target_os = "fuchsia"))]
#[cfg(any(unix, windows, target_os = "redox", target_os = "fuchsia"))]
#[test]
fn test_multithreading() {
use std::sync::mpsc::channel;
use std::thread;
let mut txs = vec!();
let mut txs = vec![];
for _ in 0..20 {
let (tx, rx) = channel();
txs.push(tx);
thread::spawn(move|| {
thread::spawn(move || {
// wait until all the tasks are ready to go.
rx.recv().unwrap();
let mut v = [0u8; 1000];

View File

@ -15,8 +15,8 @@ extern crate wasm_bindgen;
extern crate wasm_bindgen_test;
use std::slice;
use wasm_bindgen_test::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
use getrandom::getrandom;