Skip to content

Commit 1fa16bf

Browse files
committed
revise safety of internal get_rng method for ThreadLocalEntropy
1 parent db659bc commit 1fa16bf

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

crates/bevy_entropy/src/thread_local_entropy.rs

+20-8
Original file line numberDiff line numberDiff line change
@@ -16,36 +16,48 @@ impl ThreadLocalEntropy {
1616
/// allow mutable access without a cell, so using `UnsafeCell` to bypass overheads associated with
1717
/// `RefCell`. There's no direct access to the pointer or mutable reference, so we control how long it
1818
/// lives and can ensure no multiple mutable references exist.
19+
///
20+
/// # Safety
21+
///
22+
/// Caller must ensure only one `mut` reference exists at a time.
1923
#[inline]
20-
fn get_rng(&'_ mut self) -> &'_ mut ChaCha12Rng {
24+
unsafe fn get_rng(&'_ mut self) -> &'_ mut ChaCha12Rng {
2125
// Obtain pointer to thread local instance of PRNG which with Rc, should be !Send & !Sync as well
2226
// as 'static.
2327
let rng = SOURCE.with(|source| source.get());
2428

25-
// SAFETY: We must make sure to stop using `rng` before anyone else creates another
26-
// mutable reference
27-
unsafe { &mut *rng }
29+
&mut *rng
2830
}
2931
}
3032

3133
impl RngCore for ThreadLocalEntropy {
3234
#[inline]
3335
fn next_u32(&mut self) -> u32 {
34-
self.get_rng().next_u32()
36+
// SAFETY: We must ensure to drop the `&mut rng` ref before creating another
37+
// mutable reference
38+
unsafe { self.get_rng().next_u32() }
3539
}
3640

3741
#[inline]
3842
fn next_u64(&mut self) -> u64 {
39-
self.get_rng().next_u64()
43+
// SAFETY: We must ensure to drop the `&mut rng` ref before creating another
44+
// mutable reference
45+
unsafe { self.get_rng().next_u64() }
4046
}
4147

4248
#[inline]
4349
fn fill_bytes(&mut self, dest: &mut [u8]) {
44-
self.get_rng().fill_bytes(dest);
50+
// SAFETY: We must ensure to drop the `&mut rng` ref before creating another
51+
// mutable reference
52+
unsafe {
53+
self.get_rng().fill_bytes(dest);
54+
}
4555
}
4656

4757
#[inline]
4858
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
49-
self.get_rng().try_fill_bytes(dest)
59+
// SAFETY: We must ensure to drop the `&mut rng` ref before creating another
60+
// mutable reference
61+
unsafe { self.get_rng().try_fill_bytes(dest) }
5062
}
5163
}

0 commit comments

Comments
 (0)