Coverage Report

Created: 2024-12-17 06:15

/rust/registry/src/index.crates.io-6f17d22bba15001f/rand-0.8.5/src/rngs/thread.rs
Line
Count
Source (jump to first uncovered line)
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 core::cell::UnsafeCell;
12
use std::rc::Rc;
13
use std::thread_local;
14
15
use super::std::Core;
16
use crate::rngs::adapter::ReseedingRng;
17
use crate::rngs::OsRng;
18
use 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 noticeable impact with thresholds
37
// of 32 kB and less. We choose 64 kB to avoid significant overhead.
38
const 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
/// though it is recommended not to use inside a fork handler.
45
/// The handle cannot be passed between threads (is not `Send` or `Sync`).
46
///
47
/// `ThreadRng` uses the same PRNG as [`StdRng`] for security and performance
48
/// and is automatically seeded from [`OsRng`].
49
///
50
/// Unlike `StdRng`, `ThreadRng` uses the  [`ReseedingRng`] wrapper to reseed
51
/// the PRNG from fresh entropy every 64 kiB of random data as well as after a
52
/// fork on Unix (though not quite immediately; see documentation of
53
/// [`ReseedingRng`]).
54
/// Note that the reseeding is done as an extra precaution against side-channel
55
/// attacks and mis-use (e.g. if somehow weak entropy were supplied initially).
56
/// The PRNG algorithms used are assumed to be secure.
57
///
58
/// [`ReseedingRng`]: crate::rngs::adapter::ReseedingRng
59
/// [`StdRng`]: crate::rngs::StdRng
60
#[cfg_attr(doc_cfg, doc(cfg(all(feature = "std", feature = "std_rng"))))]
61
#[derive(Clone, Debug)]
62
pub struct ThreadRng {
63
    // Rc is explicitly !Send and !Sync
64
    rng: Rc<UnsafeCell<ReseedingRng<Core, OsRng>>>,
65
}
66
67
thread_local!(
68
    // We require Rc<..> to avoid premature freeing when thread_rng is used
69
    // within thread-local destructors. See #968.
70
    static THREAD_RNG_KEY: Rc<UnsafeCell<ReseedingRng<Core, OsRng>>> = {
71
        let r = Core::from_rng(OsRng).unwrap_or_else(|err|
72
0
                panic!("could not initialize thread_rng: {}", err));
Unexecuted instantiation: rand::rngs::thread::THREAD_RNG_KEY::__init::{closure#0}
Unexecuted instantiation: rand::rngs::thread::THREAD_RNG_KEY::__init::{closure#0}
73
        let rng = ReseedingRng::new(r,
74
                                    THREAD_RNG_RESEED_THRESHOLD,
75
                                    OsRng);
76
        Rc::new(UnsafeCell::new(rng))
77
    }
78
);
79
80
/// Retrieve the lazily-initialized thread-local random number generator,
81
/// seeded by the system. Intended to be used in method chaining style,
82
/// e.g. `thread_rng().gen::<i32>()`, or cached locally, e.g.
83
/// `let mut rng = thread_rng();`.  Invoked by the `Default` trait, making
84
/// `ThreadRng::default()` equivalent.
85
///
86
/// For more information see [`ThreadRng`].
87
#[cfg_attr(doc_cfg, doc(cfg(all(feature = "std", feature = "std_rng"))))]
88
54.6k
pub fn thread_rng() -> ThreadRng {
89
54.6k
    let rng = THREAD_RNG_KEY.with(|t| t.clone());
rand::rngs::thread::thread_rng::{closure#0}
Line
Count
Source
89
54.6k
    let rng = THREAD_RNG_KEY.with(|t| t.clone());
Unexecuted instantiation: rand::rngs::thread::thread_rng::{closure#0}
90
54.6k
    ThreadRng { rng }
91
54.6k
}
rand::rngs::thread::thread_rng
Line
Count
Source
88
54.6k
pub fn thread_rng() -> ThreadRng {
89
54.6k
    let rng = THREAD_RNG_KEY.with(|t| t.clone());
90
54.6k
    ThreadRng { rng }
91
54.6k
}
Unexecuted instantiation: rand::rngs::thread::thread_rng
92
93
impl Default for ThreadRng {
94
0
    fn default() -> ThreadRng {
95
0
        crate::prelude::thread_rng()
96
0
    }
Unexecuted instantiation: <rand::rngs::thread::ThreadRng as core::default::Default>::default
Unexecuted instantiation: <rand::rngs::thread::ThreadRng as core::default::Default>::default
97
}
98
99
impl RngCore for ThreadRng {
100
    #[inline(always)]
101
47.2k
    fn next_u32(&mut self) -> u32 {
102
47.2k
        // SAFETY: We must make sure to stop using `rng` before anyone else
103
47.2k
        // creates another mutable reference
104
47.2k
        let rng = unsafe { &mut *self.rng.get() };
105
47.2k
        rng.next_u32()
106
47.2k
    }
<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32
Line
Count
Source
101
47.2k
    fn next_u32(&mut self) -> u32 {
102
47.2k
        // SAFETY: We must make sure to stop using `rng` before anyone else
103
47.2k
        // creates another mutable reference
104
47.2k
        let rng = unsafe { &mut *self.rng.get() };
105
47.2k
        rng.next_u32()
106
47.2k
    }
Unexecuted instantiation: <rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32
107
108
    #[inline(always)]
109
7.59k
    fn next_u64(&mut self) -> u64 {
110
7.59k
        // SAFETY: We must make sure to stop using `rng` before anyone else
111
7.59k
        // creates another mutable reference
112
7.59k
        let rng = unsafe { &mut *self.rng.get() };
113
7.59k
        rng.next_u64()
114
7.59k
    }
<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u64
Line
Count
Source
109
7.59k
    fn next_u64(&mut self) -> u64 {
110
7.59k
        // SAFETY: We must make sure to stop using `rng` before anyone else
111
7.59k
        // creates another mutable reference
112
7.59k
        let rng = unsafe { &mut *self.rng.get() };
113
7.59k
        rng.next_u64()
114
7.59k
    }
Unexecuted instantiation: <rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u64
115
116
0
    fn fill_bytes(&mut self, dest: &mut [u8]) {
117
0
        // SAFETY: We must make sure to stop using `rng` before anyone else
118
0
        // creates another mutable reference
119
0
        let rng = unsafe { &mut *self.rng.get() };
120
0
        rng.fill_bytes(dest)
121
0
    }
Unexecuted instantiation: <rand::rngs::thread::ThreadRng as rand_core::RngCore>::fill_bytes
Unexecuted instantiation: <rand::rngs::thread::ThreadRng as rand_core::RngCore>::fill_bytes
122
123
0
    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
124
0
        // SAFETY: We must make sure to stop using `rng` before anyone else
125
0
        // creates another mutable reference
126
0
        let rng = unsafe { &mut *self.rng.get() };
127
0
        rng.try_fill_bytes(dest)
128
0
    }
Unexecuted instantiation: <rand::rngs::thread::ThreadRng as rand_core::RngCore>::try_fill_bytes
Unexecuted instantiation: <rand::rngs::thread::ThreadRng as rand_core::RngCore>::try_fill_bytes
129
}
130
131
impl CryptoRng for ThreadRng {}
132
133
134
#[cfg(test)]
135
mod test {
136
    #[test]
137
    fn test_thread_rng() {
138
        use crate::Rng;
139
        let mut r = crate::thread_rng();
140
        r.gen::<i32>();
141
        assert_eq!(r.gen_range(0..1), 0);
142
    }
143
}