Skip to content

impl<R: RngCore> RngCore for Rc<RefCell<R>> #604

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions rand_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,36 @@ impl<R: RngCore + ?Sized> RngCore for Box<R> {
}
}

// Implement `RngCore` for Rc<RefCell<..>> references to a `RngCore`.
// Force inlining all functions, so that it is up to the `RngCore`
// implementation and the optimizer to decide on inlining.
//
// We do not actually use `Rc` here because it requires `std` but its
// `Deref` should make this suffice, and this can be used on the stack.
// #[cfg(feature="std")]
// impl<R: RngCore> RngCore for ::std::rc::Rc<::std::cell::RefCell<R>> {
impl<'a,R: RngCore> RngCore for &'a ::core::cell::RefCell<R> {
#[inline(always)]
fn next_u32(&mut self) -> u32 {
self.borrow_mut().next_u32()
}

#[inline(always)]
fn next_u64(&mut self) -> u64 {
self.borrow_mut().next_u64()
}

#[inline(always)]
fn fill_bytes(&mut self, dest: &mut [u8]) {
self.borrow_mut().fill_bytes(dest)
}

#[inline(always)]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
self.borrow_mut().try_fill_bytes(dest)
}
}

#[cfg(feature="std")]
impl std::io::Read for RngCore {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
Expand Down
13 changes: 13 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1089,6 +1089,19 @@ mod test {
let _c: u8 = Standard.sample(&mut r);
}

#[test]
// #[cfg(feature="stc")]
fn test_rng_rc_refcell_trait() {
use std::ops::Deref;
use distributions::{Distribution, Standard};
// let rng = rng(110);
let mut r = & *::std::rc::Rc::new(::std::cell::RefCell::new(rng(110)));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We would not require the & * here if we had an actual impl for Rc<RefCell<R>> but navigating rustc to a &mut &RefCel<R> is tricky.

r.next_u32();
r.gen::<i32>();
assert_eq!(r.gen_range(0, 1), 0);
let _c: u8 = Standard.sample(&mut r);
}

#[test]
#[cfg(feature="std")]
fn test_random() {
Expand Down