1 // Copyright 2018 Developers of the Rand project.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8 
9 //! Thread-local random number generator
10 
11 use std::cell::UnsafeCell;
12 
13 use {RngCore, CryptoRng, SeedableRng, Error};
14 use rngs::adapter::ReseedingRng;
15 use rngs::EntropyRng;
16 use rand_hc::Hc128Core;
17 
18 // Rationale for using `UnsafeCell` in `ThreadRng`:
19 //
20 // Previously we used a `RefCell`, with an overhead of ~15%. There will only
21 // ever be one mutable reference to the interior of the `UnsafeCell`, because
22 // we only have such a reference inside `next_u32`, `next_u64`, etc. Within a
23 // single thread (which is the definition of `ThreadRng`), there will only ever
24 // be one of these methods active at a time.
25 //
26 // A possible scenario where there could be multiple mutable references is if
27 // `ThreadRng` is used inside `next_u32` and co. But the implementation is
28 // completely under our control. We just have to ensure none of them use
29 // `ThreadRng` internally, which is nonsensical anyway. We should also never run
30 // `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`.
34 
35 
36 // Number of generated bytes after which to reseed `TreadRng`.
37 //
38 // The time it takes to reseed HC-128 is roughly equivalent to generating 7 KiB.
39 // We pick a treshold here that is large enough to not reduce the average
40 // performance too much, but also small enough to not make reseeding something
41 // that basically never happens.
42 const THREAD_RNG_RESEED_THRESHOLD: u64 = 32*1024*1024; // 32 MiB
43 
44 /// The type returned by [`thread_rng`], essentially just a reference to the
45 /// PRNG in thread-local memory.
46 ///
47 /// `ThreadRng` uses [`ReseedingRng`] wrapping the same PRNG as [`StdRng`],
48 /// which is reseeded after generating 32 MiB of random data. A single instance
49 /// is cached per thread and the returned `ThreadRng` is a reference to this
50 /// instance — hence `ThreadRng` is neither `Send` nor `Sync` but is safe to use
51 /// within a single thread. This RNG is seeded and reseeded via [`EntropyRng`]
52 /// as required.
53 ///
54 /// Note that the reseeding is done as an extra precaution against entropy
55 /// leaks and is in theory unnecessary — to predict `ThreadRng`'s output, an
56 /// attacker would have to either determine most of the RNG's seed or internal
57 /// state, or crack the algorithm used.
58 ///
59 /// Like [`StdRng`], `ThreadRng` is a cryptographically secure PRNG. The current
60 /// algorithm used is [HC-128], which is an array-based PRNG that trades memory
61 /// usage for better performance. This makes it similar to ISAAC, the algorithm
62 /// used in `ThreadRng` before rand 0.5.
63 ///
64 /// Cloning this handle just produces a new reference to the same thread-local
65 /// generator.
66 ///
67 /// [`ReseedingRng`]: crate::rngs::adapter::ReseedingRng
68 /// [`StdRng`]: crate::rngs::StdRng
69 /// [HC-128]: rand_hc::Hc128Rng
70 #[derive(Clone, Debug)]
71 pub struct ThreadRng {
72     // use of raw pointer implies type is neither Send nor Sync
73     rng: *mut ReseedingRng<Hc128Core, EntropyRng>,
74 }
75 
76 thread_local!(
77     static THREAD_RNG_KEY: UnsafeCell<ReseedingRng<Hc128Core, EntropyRng>> = {
78         let mut entropy_source = EntropyRng::new();
79         let r = Hc128Core::from_rng(&mut entropy_source).unwrap_or_else(|err|
80                 panic!("could not initialize thread_rng: {}", err));
81         let rng = ReseedingRng::new(r,
82                                     THREAD_RNG_RESEED_THRESHOLD,
83                                     entropy_source);
84         UnsafeCell::new(rng)
85     }
86 );
87 
88 /// Retrieve the lazily-initialized thread-local random number generator,
89 /// seeded by the system. Intended to be used in method chaining style,
90 /// e.g. `thread_rng().gen::<i32>()`, or cached locally, e.g.
91 /// `let mut rng = thread_rng();`.  Invoked by the `Default` trait, making
92 /// `ThreadRng::default()` equivelent.
93 ///
94 /// For more information see [`ThreadRng`].
thread_rng() -> ThreadRng95 pub fn thread_rng() -> ThreadRng {
96     ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.get()) }
97 }
98 
99 impl Default for ThreadRng {
default() -> ThreadRng100     fn default() -> ThreadRng {
101         ::prelude::thread_rng()
102     }
103 }
104 
105 impl RngCore for ThreadRng {
106     #[inline(always)]
next_u32(&mut self) -> u32107     fn next_u32(&mut self) -> u32 {
108         unsafe { (*self.rng).next_u32() }
109     }
110 
111     #[inline(always)]
next_u64(&mut self) -> u64112     fn next_u64(&mut self) -> u64 {
113         unsafe { (*self.rng).next_u64() }
114     }
115 
fill_bytes(&mut self, dest: &mut [u8])116     fn fill_bytes(&mut self, dest: &mut [u8]) {
117         unsafe { (*self.rng).fill_bytes(dest) }
118     }
119 
try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>120     fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
121         unsafe { (*self.rng).try_fill_bytes(dest) }
122     }
123 }
124 
125 impl CryptoRng for ThreadRng {}
126 
127 
128 #[cfg(test)]
129 mod test {
130     #[test]
test_thread_rng()131     fn test_thread_rng() {
132         use Rng;
133         let mut r = ::thread_rng();
134         r.gen::<i32>();
135         assert_eq!(r.gen_range(0, 1), 0);
136     }
137 }
138