Skip to content
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

ThreadRng::rng is unsafe #1037

Merged
merged 1 commit into from Sep 3, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 16 additions & 11 deletions src/rngs/thread.rs
Expand Up @@ -95,30 +95,35 @@ impl Default for ThreadRng {
}
}

impl ThreadRng {
#[inline(always)]
fn rng(&mut self) -> &mut ReseedingRng<Core, OsRng> {
unsafe { &mut *self.rng.get() }
}
}

impl RngCore for ThreadRng {
#[inline(always)]
fn next_u32(&mut self) -> u32 {
self.rng().next_u32()
// SAFETY: We must make sure to stop using `rng` before anyone else
// creates another mutable reference
let rng = unsafe { &mut *self.rng.get() };
rng.next_u32()
}

#[inline(always)]
fn next_u64(&mut self) -> u64 {
self.rng().next_u64()
// SAFETY: We must make sure to stop using `rng` before anyone else
// creates another mutable reference
let rng = unsafe { &mut *self.rng.get() };
rng.next_u64()
}

fn fill_bytes(&mut self, dest: &mut [u8]) {
self.rng().fill_bytes(dest)
// SAFETY: We must make sure to stop using `rng` before anyone else
// creates another mutable reference
let rng = unsafe { &mut *self.rng.get() };
rng.fill_bytes(dest)
}

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
self.rng().try_fill_bytes(dest)
// SAFETY: We must make sure to stop using `rng` before anyone else
// creates another mutable reference
let rng = unsafe { &mut *self.rng.get() };
rng.try_fill_bytes(dest)
}
}

Expand Down