Skip to content

Commit 59f70db

Browse files
authored
Merge pull request #326 from pitdicker/doc_fixes
Update documentation for ReadRng error handling
2 parents 56fbee5 + 0495a6c commit 59f70db

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

src/read.rs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,14 @@ use rand_core::{RngCore, Error, ErrorKind, impls};
1616

1717

1818
/// An RNG that reads random bytes straight from a `Read`. This will
19-
/// work best with an infinite reader, but this is not required.
19+
/// work best with an infinite reader, but that is not required.
2020
///
2121
/// # Panics
2222
///
23-
/// It will panic if it there is insufficient data to fulfill a request.
23+
/// `ReadRng` uses `std::io::read_exact`, which retries on interrupts. All other
24+
/// errors from the underlying reader, including when it does not have enough
25+
/// data, will only be reported through `try_fill_bytes`. The other `RngCore`
26+
/// methods will panic in case of an error error.
2427
///
2528
/// # Example
2629
///
@@ -53,21 +56,22 @@ impl<R: Read> RngCore for ReadRng<R> {
5356
fn next_u64(&mut self) -> u64 {
5457
impls::next_u64_via_fill(self)
5558
}
56-
59+
5760
fn fill_bytes(&mut self, dest: &mut [u8]) {
58-
self.try_fill_bytes(dest).unwrap();
61+
self.try_fill_bytes(dest).unwrap_or_else(|err|
62+
panic!("reading random bytes from Read implementation failed; error: {}", err));
5963
}
6064

6165
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
6266
if dest.len() == 0 { return Ok(()); }
6367
// Use `std::io::read_exact`, which retries on `ErrorKind::Interrupted`.
6468
self.reader.read_exact(dest).map_err(|err| {
6569
match err.kind() {
66-
::std::io::ErrorKind::WouldBlock => Error::with_cause(
67-
ErrorKind::NotReady,
68-
"reading from random device would block", err),
70+
::std::io::ErrorKind::UnexpectedEof => Error::with_cause(
71+
ErrorKind::Unavailable,
72+
"not enough bytes available, reached end of source", err),
6973
_ => Error::with_cause(ErrorKind::Unavailable,
70-
"error reading random device", err)
74+
"error reading from Read source", err)
7175
}
7276
})
7377
}
@@ -90,6 +94,7 @@ mod test {
9094
assert_eq!(rng.next_u64(), 2_u64.to_be());
9195
assert_eq!(rng.next_u64(), 3_u64.to_be());
9296
}
97+
9398
#[test]
9499
fn test_reader_rng_u32() {
95100
let v = vec![0u8, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3];
@@ -99,6 +104,7 @@ mod test {
99104
assert_eq!(rng.next_u32(), 2_u32.to_be());
100105
assert_eq!(rng.next_u32(), 3_u32.to_be());
101106
}
107+
102108
#[test]
103109
fn test_reader_rng_fill_bytes() {
104110
let v = [1u8, 2, 3, 4, 5, 6, 7, 8];

0 commit comments

Comments
 (0)