Skip to content

Commit 1d76be5

Browse files
committed
Let RngReader take R by value
1 parent 234c0ec commit 1d76be5

File tree

1 file changed

+38
-4
lines changed

1 file changed

+38
-4
lines changed

rand_core/src/lib.rs

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -543,13 +543,16 @@ pub trait SeedableRng: Sized {
543543
/// use std::fs::File;
544544
/// use rand_core::{OsRng, RngReader};
545545
///
546-
/// io::copy(&mut RngReader(&mut OsRng).take(100), &mut File::create("/tmp/random.bytes").unwrap()).unwrap();
546+
/// io::copy(
547+
/// &mut RngReader(OsRng).take(100),
548+
/// &mut File::create("/tmp/random.bytes").unwrap()
549+
/// ).unwrap();
547550
/// ```
548551
#[cfg(feature = "std")]
549-
pub struct RngReader<'a, R: TryRngCore + ?Sized>(pub &'a mut R);
552+
pub struct RngReader<R: TryRngCore>(pub R);
550553

551554
#[cfg(feature = "std")]
552-
impl<R: TryRngCore + ?Sized> std::io::Read for RngReader<'_, R> {
555+
impl<R: TryRngCore> std::io::Read for RngReader<R> {
553556
#[inline]
554557
fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
555558
self.0
@@ -560,7 +563,7 @@ impl<R: TryRngCore + ?Sized> std::io::Read for RngReader<'_, R> {
560563
}
561564

562565
#[cfg(feature = "std")]
563-
impl<R: TryRngCore + ?Sized> std::fmt::Debug for RngReader<'_, R> {
566+
impl<R: TryRngCore> std::fmt::Debug for RngReader<R> {
564567
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
565568
f.debug_tuple("RngReader").finish()
566569
}
@@ -726,4 +729,35 @@ mod test {
726729
}
727730
assert_eq!(rng.next_u32(), 4);
728731
}
732+
733+
struct StepRng(u32, u32);
734+
impl RngCore for StepRng {
735+
fn next_u32(&mut self) -> u32 {
736+
let x = self.0;
737+
self.0 += self.1;
738+
x
739+
}
740+
fn next_u64(&mut self) -> u64 {
741+
le::next_u64_via_u32(self)
742+
}
743+
fn fill_bytes(&mut self, dest: &mut [u8]) {
744+
le::fill_bytes_via_next(self, dest);
745+
}
746+
}
747+
748+
#[cfg(feature = "std")]
749+
#[test]
750+
fn rng_reader() {
751+
use std::io::Read;
752+
753+
let mut rng = StepRng(255, 1);
754+
let mut buf = [0u8; 16];
755+
let expected = [255, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 2, 1, 0, 0];
756+
757+
RngReader(&mut rng).read_exact(&mut buf).unwrap();
758+
assert_eq!(&buf, &expected);
759+
760+
RngReader(StepRng(255, 1)).read_exact(&mut buf).unwrap();
761+
assert_eq!(&buf, &expected);
762+
}
729763
}

0 commit comments

Comments
 (0)