Skip to content

Commit 9728648

Browse files
authored
Merge pull request #434 from pitdicker/std_io_read
Implement std::io::Read for RngCore
2 parents 9bdd3df + 7959fbf commit 9728648

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

rand_core/src/error.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ use core::fmt;
1414

1515
#[cfg(feature="std")]
1616
use std::error::Error as stdError;
17+
#[cfg(feature="std")]
18+
use std::io;
1719

1820
/// Error kind which can be matched over.
1921
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
@@ -161,3 +163,17 @@ impl stdError for Error {
161163
self.cause.as_ref().map(|e| e.as_ref() as &stdError)
162164
}
163165
}
166+
167+
#[cfg(feature="std")]
168+
impl From<Error> for io::Error {
169+
fn from(error: Error) -> Self {
170+
use std::io::ErrorKind::*;
171+
match error.kind {
172+
ErrorKind::Unavailable => io::Error::new(NotFound, error),
173+
ErrorKind::Unexpected |
174+
ErrorKind::Transient => io::Error::new(Other, error),
175+
ErrorKind::NotReady => io::Error::new(WouldBlock, error),
176+
ErrorKind::__Nonexhaustive => unreachable!(),
177+
}
178+
}
179+
}

rand_core/src/lib.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,3 +439,11 @@ impl<R: RngCore + ?Sized> RngCore for Box<R> {
439439
(**self).try_fill_bytes(dest)
440440
}
441441
}
442+
443+
#[cfg(feature="std")]
444+
impl std::io::Read for RngCore {
445+
fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
446+
self.try_fill_bytes(buf)?;
447+
Ok(buf.len())
448+
}
449+
}

0 commit comments

Comments
 (0)