rand/rngs/thread.rs
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
11use core::cell::UnsafeCell;
12use std::rc::Rc;
13use std::thread_local;
14
15use super::std::Core;
16use crate::rngs::adapter::ReseedingRng;
17use crate::rngs::OsRng;
18use crate::{CryptoRng, Error, RngCore, SeedableRng};
19
20// Rationale for using `UnsafeCell` in `ThreadRng`:
21//
22// Previously we used a `RefCell`, with an overhead of ~15%. There will only
23// ever be one mutable reference to the interior of the `UnsafeCell`, because
24// we only have such a reference inside `next_u32`, `next_u64`, etc. Within a
25// single thread (which is the definition of `ThreadRng`), there will only ever
26// be one of these methods active at a time.
27//
28// A possible scenario where there could be multiple mutable references is if
29// `ThreadRng` is used inside `next_u32` and co. But the implementation is
30// completely under our control. We just have to ensure none of them use
31// `ThreadRng` internally, which is nonsensical anyway. We should also never run
32// `ThreadRng` in destructors of its implementation, which is also nonsensical.
33
34
35// Number of generated bytes after which to reseed `ThreadRng`.
36// According to benchmarks, reseeding has a noticable impact with thresholds
37// of 32 kB and less. We choose 64 kB to avoid significant overhead.
38const THREAD_RNG_RESEED_THRESHOLD: u64 = 1024 * 64;
39
40/// A reference to the thread-local generator
41///
42/// An instance can be obtained via [`thread_rng`] or via `ThreadRng::default()`.
43/// This handle is safe to use everywhere (including thread-local destructors)
44/// but cannot be passed between threads (is not `Send` or `Sync`).
45///
46/// `ThreadRng` uses the same PRNG as [`StdRng`] for security and performance
47/// and is automatically seeded from [`OsRng`].
48///
49/// Unlike `StdRng`, `ThreadRng` uses the [`ReseedingRng`] wrapper to reseed
50/// the PRNG from fresh entropy every 64 kiB of random data as well as after a
51/// fork on Unix (though not quite immediately; see documentation of
52/// [`ReseedingRng`]).
53/// Note that the reseeding is done as an extra precaution against side-channel
54/// attacks and mis-use (e.g. if somehow weak entropy were supplied initially).
55/// The PRNG algorithms used are assumed to be secure.
56///
57/// [`ReseedingRng`]: crate::rngs::adapter::ReseedingRng
58/// [`StdRng`]: crate::rngs::StdRng
59#[cfg_attr(doc_cfg, doc(cfg(all(feature = "std", feature = "std_rng"))))]
60#[derive(Clone, Debug)]
61pub struct ThreadRng {
62 // Rc is explictly !Send and !Sync
63 rng: Rc<UnsafeCell<ReseedingRng<Core, OsRng>>>,
64}
65
66thread_local!(
67 // We require Rc<..> to avoid premature freeing when thread_rng is used
68 // within thread-local destructors. See #968.
69 static THREAD_RNG_KEY: Rc<UnsafeCell<ReseedingRng<Core, OsRng>>> = {
70 let r = Core::from_rng(OsRng).unwrap_or_else(|err|
71 panic!("could not initialize thread_rng: {}", err));
72 let rng = ReseedingRng::new(r,
73 THREAD_RNG_RESEED_THRESHOLD,
74 OsRng);
75 Rc::new(UnsafeCell::new(rng))
76 }
77);
78
79/// Retrieve the lazily-initialized thread-local random number generator,
80/// seeded by the system. Intended to be used in method chaining style,
81/// e.g. `thread_rng().gen::<i32>()`, or cached locally, e.g.
82/// `let mut rng = thread_rng();`. Invoked by the `Default` trait, making
83/// `ThreadRng::default()` equivalent.
84///
85/// For more information see [`ThreadRng`].
86#[cfg_attr(doc_cfg, doc(cfg(all(feature = "std", feature = "std_rng"))))]
87pub fn thread_rng() -> ThreadRng {
88 let rng = THREAD_RNG_KEY.with(|t| t.clone());
89 ThreadRng { rng }
90}
91
92impl Default for ThreadRng {
93 fn default() -> ThreadRng {
94 crate::prelude::thread_rng()
95 }
96}
97
98impl RngCore for ThreadRng {
99 #[inline(always)]
100 fn next_u32(&mut self) -> u32 {
101 // SAFETY: We must make sure to stop using `rng` before anyone else
102 // creates another mutable reference
103 let rng = unsafe { &mut *self.rng.get() };
104 rng.next_u32()
105 }
106
107 #[inline(always)]
108 fn next_u64(&mut self) -> u64 {
109 // SAFETY: We must make sure to stop using `rng` before anyone else
110 // creates another mutable reference
111 let rng = unsafe { &mut *self.rng.get() };
112 rng.next_u64()
113 }
114
115 fn fill_bytes(&mut self, dest: &mut [u8]) {
116 // SAFETY: We must make sure to stop using `rng` before anyone else
117 // creates another mutable reference
118 let rng = unsafe { &mut *self.rng.get() };
119 rng.fill_bytes(dest)
120 }
121
122 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
123 // SAFETY: We must make sure to stop using `rng` before anyone else
124 // creates another mutable reference
125 let rng = unsafe { &mut *self.rng.get() };
126 rng.try_fill_bytes(dest)
127 }
128}
129
130impl CryptoRng for ThreadRng {}
131
132
133#[cfg(test)]
134mod test {
135 #[test]
136 fn test_thread_rng() {
137 use crate::Rng;
138 let mut r = crate::thread_rng();
139 r.gen::<i32>();
140 assert_eq!(r.gen_range(0..1), 0);
141 }
142}