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

ThreadRng::rng is unsafe #1037

merged 1 commit into from
Sep 3, 2020

Conversation

vks
Copy link
Collaborator

@vks vks commented Sep 2, 2020

This method must be used correctly to avoid undefined behavior. Making
it unsafe communicates this more clearly. Note that this is a private,
internal method that was and is being used soundly.

This is a followup to @RalfJung's comment in #1035.

src/rngs/thread.rs Outdated Show resolved Hide resolved
@vks vks changed the title ThreadRng::rng should be unsafe ThreadRng::rng document why it is safe Sep 2, 2020
@dhardy
Copy link
Member

dhardy commented Sep 2, 2020

The issue is this:

let mut a = thread_rng();
let mut b = a.clone();
let ra = a.rng();
let rb = b.rng();
// both ra and rb are `&mut` to the same thing!

But at this point we might as well just take the simplest solution and inline it:

let rng = unsafe { &mut *self.rng.get() };
rng.next_u32()

@vks vks changed the title ThreadRng::rng document why it is safe ThreadRng::rng is unsafe Sep 2, 2020
This method must be used correctly to avoid undefined behavior.
Therefore, it should be `unsafe`. Instead, we just inline it and add a
comment why the code is safe.
@vks vks force-pushed the should-be-unsafe branch from e1c43ca to d45672b Compare September 2, 2020 18:35
@vks
Copy link
Collaborator Author

vks commented Sep 2, 2020

@dhardy Thanks! I pushed a commit that gets rid of ThreadRng::rng and inlines the corresponding code.

@RalfJung
Copy link
Contributor

RalfJung commented Sep 3, 2020

The issue is this:

Indeed, that's why the old rng should have been unsafe. Inlining also works of course. Bonus points for the safety comments. :)

@vks vks merged commit 54b77d8 into rust-random:master Sep 3, 2020
@vks vks deleted the should-be-unsafe branch September 3, 2020 15:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants