Skip to content

Commit

Permalink
Tweak retry counter
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Jan 22, 2018
1 parent 7f61e2f commit 41fc616
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -986,7 +986,9 @@ impl Rng for ThreadRng {
/// `EntropyRng` uses the interface for random numbers provided by the operating
/// system ([`OsRng`]). If that returns an error, it will fall back to the
/// [`JitterRng`] entropy collector. Occasionally it will then check if `OsRng`
/// is still not available, and switch back if possible.
/// is still not available, and switch back if possible. Once every 8 calls to
/// `try_fill_bytes` if `OsRng` failed with `ErrorKind:Unavailable`, otherwise
/// with every call.
///
/// [`OsRng`]: os/struct.OsRng.html
/// [`JitterRng`]: jitter/struct.JitterRng.html
Expand Down Expand Up @@ -1074,22 +1076,28 @@ impl Rng for EntropyRng {
}
}
EntropySource::Jitter(ref mut rng) => {
if self.counter >= 8 {
if let Ok(os_rng) = try_os_new(dest) {
switch_rng = Some(EntropySource::Os(os_rng));
} else {
self.counter = (self.counter + 1) % 8;
return rng.try_fill_bytes(dest); // use JitterRng
if self.counter == 0 {
match try_os_new(dest) {
Ok(os_rng) => {
switch_rng = Some(EntropySource::Os(os_rng));
}
Err(e) => {
if e.kind() == ErrorKind::Unavailable {
self.counter = 8; // Wait 8 calls before retry
} else {
self.counter = 0; // Retry on next call
}
return rng.try_fill_bytes(dest); // use JitterRng
}
}
} else {
self.counter = (self.counter + 1) % 8;
self.counter -= 1;
return rng.try_fill_bytes(dest); // use JitterRng
}
}
}
if let Some(rng) = switch_rng {
self.rng = rng;
self.counter = 0;
}
Ok(())
}
Expand Down

0 comments on commit 41fc616

Please sign in to comment.