1cfg_rt! {
2 mod rt;
3 pub(crate) use rt::RngSeedGenerator;
4
5 cfg_unstable! {
6 mod rt_unstable;
7 }
8}
9
10#[allow(unreachable_pub)]
15#[derive(Clone, Debug)]
16pub struct RngSeed {
17 s: u32,
18 r: u32,
19}
20
21#[derive(Clone, Copy, Debug)]
29pub(crate) struct FastRand {
30 one: u32,
31 two: u32,
32}
33
34impl RngSeed {
35 pub(crate) fn new() -> Self {
37 Self::from_u64(crate::loom::rand::seed())
38 }
39
40 fn from_u64(seed: u64) -> Self {
41 let one = (seed >> 32) as u32;
42 let two = seed as u32;
43
44 Self::from_pair(one, two)
45 }
46
47 fn from_pair(s: u32, r: u32) -> Self {
48 if s == 0 && r == 0 {
49 Self { s: 0, r: 1 }
50 } else {
51 Self { s, r }
52 }
53 }
54}
55
56impl FastRand {
57 pub(crate) fn new() -> FastRand {
59 FastRand::from_seed(RngSeed::new())
60 }
61
62 pub(crate) fn from_seed(seed: RngSeed) -> FastRand {
64 FastRand {
65 one: seed.s,
66 two: seed.r,
67 }
68 }
69
70 #[cfg(any(feature = "macros", feature = "sync", feature = "rt"))]
71 pub(crate) fn fastrand_n(&mut self, n: u32) -> u32 {
72 let mul = (self.fastrand() as u64).wrapping_mul(n as u64);
75 (mul >> 32) as u32
76 }
77
78 fn fastrand(&mut self) -> u32 {
79 let mut s1 = self.one;
80 let s0 = self.two;
81
82 s1 ^= s1 << 17;
83 s1 = s1 ^ s0 ^ s1 >> 7 ^ s0 >> 16;
84
85 self.one = s0;
86 self.two = s1;
87
88 s0.wrapping_add(s1)
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 #[test]
97 fn non_zero_seed_from_u64() {
98 let seed = RngSeed::from_u64(0);
99 assert_eq!(seed.s, 0);
100 assert_eq!(seed.r, 1);
101 }
102
103 #[test]
104 fn non_zero_seed_from_pair() {
105 let seed = RngSeed::from_pair(0, 0);
106 assert_eq!(seed.s, 0);
107 assert_eq!(seed.r, 1);
108 }
109}