1#![doc(
24 html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
25 html_favicon_url = "https://www.rust-lang.org/favicon.ico"
26)]
27#![forbid(unsafe_code)]
28#![deny(missing_docs)]
29#![deny(missing_debug_implementations)]
30#![no_std]
31
32use core::num::Wrapping as w;
33use core::{convert::Infallible, fmt};
34use rand_core::{Rng, SeedableRng, TryRng, utils};
35#[cfg(feature = "serde")]
36use serde::{Deserialize, Serialize};
37
38#[derive(Clone, PartialEq, Eq)]
53#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
54pub struct XorShiftRng {
55 x: w<u32>,
56 y: w<u32>,
57 z: w<u32>,
58 w: w<u32>,
59}
60
61impl fmt::Debug for XorShiftRng {
63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64 write!(f, "XorShiftRng {{}}")
65 }
66}
67
68impl TryRng for XorShiftRng {
69 type Error = Infallible;
70 #[inline]
71 fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
72 let x = self.x;
75 let t = x ^ (x << 11);
76 self.x = self.y;
77 self.y = self.z;
78 self.z = self.w;
79 let w_ = self.w;
80 self.w = w_ ^ (w_ >> 19) ^ (t ^ (t >> 8));
81 Ok(self.w.0)
82 }
83
84 #[inline]
85 fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
86 utils::next_u64_via_u32(self)
87 }
88
89 #[inline]
90 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
91 utils::fill_bytes_via_next_word(dest, || self.try_next_u32())
92 }
93}
94
95impl SeedableRng for XorShiftRng {
96 type Seed = [u8; 16];
97
98 fn from_seed(seed: Self::Seed) -> Self {
99 let mut seed_u32: [u32; 4] = utils::read_words(&seed);
100
101 if seed_u32 == [0; 4] {
105 seed_u32 = [0xBAD_5EED, 0xBAD_5EED, 0xBAD_5EED, 0xBAD_5EED];
106 }
107
108 XorShiftRng {
109 x: w(seed_u32[0]),
110 y: w(seed_u32[1]),
111 z: w(seed_u32[2]),
112 w: w(seed_u32[3]),
113 }
114 }
115
116 fn from_rng<R>(rng: &mut R) -> Self
117 where
118 R: Rng + ?Sized,
119 {
120 let mut b = [0u8; 16];
121 loop {
122 rng.fill_bytes(b.as_mut());
123 if b != [0; 16] {
124 break;
125 }
126 }
127
128 XorShiftRng {
129 x: w(u32::from_le_bytes([b[0], b[1], b[2], b[3]])),
130 y: w(u32::from_le_bytes([b[4], b[5], b[6], b[7]])),
131 z: w(u32::from_le_bytes([b[8], b[9], b[10], b[11]])),
132 w: w(u32::from_le_bytes([b[12], b[13], b[14], b[15]])),
133 }
134 }
135
136 fn try_from_rng<R>(rng: &mut R) -> Result<Self, R::Error>
137 where
138 R: TryRng + ?Sized,
139 {
140 let mut b = [0u8; 16];
141 loop {
142 rng.try_fill_bytes(b.as_mut())?;
143 if b != [0; 16] {
144 break;
145 }
146 }
147
148 Ok(XorShiftRng {
149 x: w(u32::from_le_bytes([b[0], b[1], b[2], b[3]])),
150 y: w(u32::from_le_bytes([b[4], b[5], b[6], b[7]])),
151 z: w(u32::from_le_bytes([b[8], b[9], b[10], b[11]])),
152 w: w(u32::from_le_bytes([b[12], b[13], b[14], b[15]])),
153 })
154 }
155}