#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico"
)]
#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![no_std]
use core::num::Wrapping as w;
use core::{convert::Infallible, fmt};
use rand_core::{Rng, SeedableRng, TryRng, utils};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct XorShiftRng {
x: w<u32>,
y: w<u32>,
z: w<u32>,
w: w<u32>,
}
impl fmt::Debug for XorShiftRng {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "XorShiftRng {{}}")
}
}
impl TryRng for XorShiftRng {
type Error = Infallible;
#[inline]
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
let x = self.x;
let t = x ^ (x << 11);
self.x = self.y;
self.y = self.z;
self.z = self.w;
let w_ = self.w;
self.w = w_ ^ (w_ >> 19) ^ (t ^ (t >> 8));
Ok(self.w.0)
}
#[inline]
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
utils::next_u64_via_u32(self)
}
#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
utils::fill_bytes_via_next_word(dest, || self.try_next_u32())
}
}
impl SeedableRng for XorShiftRng {
type Seed = [u8; 16];
fn from_seed(seed: Self::Seed) -> Self {
let mut seed_u32: [u32; 4] = utils::read_words(&seed);
if seed_u32 == [0; 4] {
seed_u32 = [0xBAD_5EED, 0xBAD_5EED, 0xBAD_5EED, 0xBAD_5EED];
}
XorShiftRng {
x: w(seed_u32[0]),
y: w(seed_u32[1]),
z: w(seed_u32[2]),
w: w(seed_u32[3]),
}
}
fn from_rng<R>(rng: &mut R) -> Self
where
R: Rng + ?Sized,
{
let mut b = [0u8; 16];
loop {
rng.fill_bytes(b.as_mut());
if b != [0; 16] {
break;
}
}
XorShiftRng {
x: w(u32::from_le_bytes([b[0], b[1], b[2], b[3]])),
y: w(u32::from_le_bytes([b[4], b[5], b[6], b[7]])),
z: w(u32::from_le_bytes([b[8], b[9], b[10], b[11]])),
w: w(u32::from_le_bytes([b[12], b[13], b[14], b[15]])),
}
}
fn try_from_rng<R>(rng: &mut R) -> Result<Self, R::Error>
where
R: TryRng + ?Sized,
{
let mut b = [0u8; 16];
loop {
rng.try_fill_bytes(b.as_mut())?;
if b != [0; 16] {
break;
}
}
Ok(XorShiftRng {
x: w(u32::from_le_bytes([b[0], b[1], b[2], b[3]])),
y: w(u32::from_le_bytes([b[4], b[5], b[6], b[7]])),
z: w(u32::from_le_bytes([b[8], b[9], b[10], b[11]])),
w: w(u32::from_le_bytes([b[12], b[13], b[14], b[15]])),
})
}
}