rand: bubble up IO errors when creating an OSRng.

This commit is contained in:
Huon Wilson 2014-03-25 00:41:43 +11:00
parent 119289b0f2
commit 0e8c949786
3 changed files with 23 additions and 13 deletions

View file

@ -46,12 +46,15 @@ impl IsaacRng {
/// Create an ISAAC random number generator with a random seed.
pub fn new() -> IsaacRng {
let mut rng = EMPTY;
let mut os_rng = match OSRng::new() {
Ok(r) => r,
Err(e) => fail!("IsaacRng::new: creating OSRng failed: {}", e)
};
unsafe {
let ptr = rng.rsl.as_mut_ptr();
raw::mut_buf_as_slice(ptr as *mut u8, mem::size_of_val(&rng.rsl), |slice| {
OSRng::new().fill_bytes(slice);
os_rng.fill_bytes(slice);
})
}
@ -251,12 +254,15 @@ impl Isaac64Rng {
/// seed.
pub fn new() -> Isaac64Rng {
let mut rng = EMPTY_64;
let mut os_rng = match OSRng::new() {
Ok(r) => r,
Err(e) => fail!("Isaac64Rng::new: creating OSRng failed: {}", e)
};
unsafe {
let ptr = rng.rsl.as_mut_ptr();
raw::mut_buf_as_slice(ptr as *mut u8, mem::size_of_val(&rng.rsl), |slice| {
OSRng::new().fill_bytes(slice);
os_rng.fill_bytes(slice);
})
}

View file

@ -540,7 +540,10 @@ impl XorShiftRng {
pub fn new() -> XorShiftRng {
let mut s = [0u8, ..16];
loop {
let mut r = OSRng::new();
let mut r = match OSRng::new() {
Ok(r) => r,
Err(e) => fail!("XorShiftRng::new: creating OSRng failed: {}", e)
};
r.fill_bytes(s);
if !s.iter().all(|x| *x == 0) {

View file

@ -17,7 +17,7 @@ pub use self::imp::OSRng;
mod imp {
use Rng;
use reader::ReaderRng;
use std::io::File;
use std::io::{IoResult, File};
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
@ -35,12 +35,11 @@ mod imp {
impl OSRng {
/// Create a new `OSRng`.
pub fn new() -> OSRng {
let reader = File::open(&Path::new("/dev/urandom"));
let reader = reader.ok().expect("Error opening /dev/urandom");
pub fn new() -> IoResult<OSRng> {
let reader = try!(File::open(&Path::new("/dev/urandom")));
let reader_rng = ReaderRng::new(reader);
OSRng { inner: reader_rng }
Ok(OSRng { inner: reader_rng })
}
}
@ -61,6 +60,7 @@ mod imp {
mod imp {
use Rng;
use std::cast;
use std::io::{IoResult, IoError};
use std::libc::{c_ulong, DWORD, BYTE, LPCSTR, BOOL};
use std::os;
use std::rt::stack;
@ -99,7 +99,7 @@ mod imp {
impl OSRng {
/// Create a new `OSRng`.
pub fn new() -> OSRng {
pub fn new() -> IoResult<OSRng> {
let mut hcp = 0;
let mut ret = unsafe {
CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
@ -143,9 +143,10 @@ mod imp {
}
if ret == 0 {
fail!("couldn't create context: {}", os::last_os_error());
Err(IoError::last_error())
} else {
Ok(OSRng { hcryptprov: hcp })
}
OSRng { hcryptprov: hcp }
}
}