99//! Thread-local random number generator
1010
1111use std:: cell:: UnsafeCell ;
12+ use std:: ptr:: NonNull ;
1213
1314use { RngCore , CryptoRng , SeedableRng , Error } ;
1415use rngs:: adapter:: ReseedingRng ;
@@ -28,9 +29,6 @@ use super::std::Core;
2829// completely under our control. We just have to ensure none of them use
2930// `ThreadRng` internally, which is nonsensical anyway. We should also never run
3031// `ThreadRng` in destructors of its implementation, which is also nonsensical.
31- //
32- // The additional `Rc` is not strictly neccesary, and could be removed. For now
33- // it ensures `ThreadRng` stays `!Send` and `!Sync`, and implements `Clone`.
3432
3533
3634// Number of generated bytes after which to reseed `ThreadRng`.
@@ -52,13 +50,13 @@ const THREAD_RNG_RESEED_THRESHOLD: u64 = 1024 * 64;
5250/// Note that the reseeding is done as an extra precaution against side-channel
5351/// attacks and mis-use (e.g. if somehow weak entropy were supplied initially).
5452/// The PRNG algorithms used are assumed to be secure.
55- ///
53+ ///
5654/// [`ReseedingRng`]: crate::rngs::adapter::ReseedingRng
5755/// [`StdRng`]: crate::rngs::StdRng
5856#[ derive( Copy , Clone , Debug ) ]
5957pub struct ThreadRng {
60- // use of raw pointer implies type is neither Send nor Sync
61- rng : * mut ReseedingRng < Core , OsRng > ,
58+ // inner raw pointer implies type is neither Send nor Sync
59+ rng : NonNull < ReseedingRng < Core , OsRng > > ,
6260}
6361
6462thread_local ! (
@@ -80,7 +78,9 @@ thread_local!(
8078///
8179/// For more information see [`ThreadRng`].
8280pub fn thread_rng ( ) -> ThreadRng {
83- ThreadRng { rng : THREAD_RNG_KEY . with ( |t| t. get ( ) ) }
81+ let raw = THREAD_RNG_KEY . with ( |t| t. get ( ) ) ;
82+ let nn = NonNull :: new ( raw) . unwrap ( ) ;
83+ ThreadRng { rng : nn }
8484}
8585
8686impl Default for ThreadRng {
@@ -92,20 +92,20 @@ impl Default for ThreadRng {
9292impl RngCore for ThreadRng {
9393 #[ inline( always) ]
9494 fn next_u32 ( & mut self ) -> u32 {
95- unsafe { ( * self . rng ) . next_u32 ( ) }
95+ unsafe { self . rng . as_mut ( ) . next_u32 ( ) }
9696 }
9797
9898 #[ inline( always) ]
9999 fn next_u64 ( & mut self ) -> u64 {
100- unsafe { ( * self . rng ) . next_u64 ( ) }
100+ unsafe { self . rng . as_mut ( ) . next_u64 ( ) }
101101 }
102102
103103 fn fill_bytes ( & mut self , dest : & mut [ u8 ] ) {
104- unsafe { ( * self . rng ) . fill_bytes ( dest) }
104+ unsafe { self . rng . as_mut ( ) . fill_bytes ( dest) }
105105 }
106106
107107 fn try_fill_bytes ( & mut self , dest : & mut [ u8 ] ) -> Result < ( ) , Error > {
108- unsafe { ( * self . rng ) . try_fill_bytes ( dest) }
108+ unsafe { self . rng . as_mut ( ) . try_fill_bytes ( dest) }
109109 }
110110}
111111
0 commit comments