Skip to content

Commit

Permalink
OsRng: merge in changes from dhardy/master: better error handling, -nacl
Browse files Browse the repository at this point in the history
This removes support for the NaCl target, which appears to be dead.
  • Loading branch information
dhardy committed Jan 9, 2018
1 parent 230b225 commit fed7943
Show file tree
Hide file tree
Showing 3 changed files with 170 additions and 234 deletions.
36 changes: 36 additions & 0 deletions src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,40 @@ pub fn next_u64_via_fill<R: Rng+?Sized>(rng: &mut R) -> u64 {
impl_uint_from_fill!(rng, u64, 8)
}

/// Implement `fill_bytes` via `try_fill` with implicit error handling.
pub fn fill_via_try_fill<R: Rng+?Sized>(rng: &mut R, dest: &mut [u8]) {
const WAIT_DUR_MS: u32 = 100;
const MAX_WAIT: u32 = (1 * 60 * 1000) / WAIT_DUR_MS;
const TRANSIENT_STEP: u32 = MAX_WAIT / 8;
let mut err_count = 0;

loop {
if let Err(e) = rng.try_fill_bytes(dest) {
if e.kind().should_retry() {
if err_count > MAX_WAIT {
// TODO: log details & cause?
panic!("Too many RNG errors or timeout; last error: {}", e.msg());
}

if e.kind().should_wait() {
#[cfg(feature="std")]{
let dur = ::std::time::Duration::from_millis(WAIT_DUR_MS as u64);
::std::thread::sleep(dur);
}
err_count += 1;
} else {
err_count += TRANSIENT_STEP;
}

continue;
}

// TODO: log details & cause?
panic!("Fatal RNG error: {}", e.msg());
}

break;
}
}

// TODO: implement tests for the above
3 changes: 1 addition & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,6 @@
use core::marker;
use core::mem;
#[cfg(feature="std")] use std::cell::RefCell;
#[cfg(feature="std")] use std::io;
#[cfg(feature="std")] use std::rc::Rc;

// external rngs
Expand Down Expand Up @@ -817,7 +816,7 @@ impl StdRng {
/// Reading the randomness from the OS may fail, and any error is
/// propagated via the `io::Result` return value.
#[cfg(feature="std")]
pub fn new() -> io::Result<StdRng> {
pub fn new() -> Result<StdRng, Error> {
match OsRng::new() {
Ok(mut r) => Ok(StdRng { rng: r.gen() }),
Err(e1) => {
Expand Down
Loading

0 comments on commit fed7943

Please sign in to comment.