#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Xabc {
a: u8,
b: u8,
c: u8,
x: u8,
}
impl Default for Xabc {
fn default() -> Self {
Self::new(Self::DEFAULT_SEED)
}
}
impl Xabc {
const DEFAULT_SEED: [u8; 3] = [0xDE, 0xFA, 0x17];
}
impl Xabc {
#[inline]
#[must_use]
pub const fn new(seeds: [u8; 3]) -> Self {
let a = seeds[0];
let b = seeds[1];
let c = seeds[2];
let x = 1;
let a = a ^ c ^ x;
let b = b.wrapping_add(a);
let c = c.wrapping_add(b >> 1) ^ a;
Self { a, b, c, x }
}
#[inline]
pub fn reseed(&mut self, seeds: [u8; 3]) {
self.a ^= seeds[0];
self.b ^= seeds[1];
self.c ^= seeds[2];
self.x += 1;
self.a = self.a ^ self.c ^ self.x;
self.b = self.b.wrapping_add(self.a);
self.c = self.c.wrapping_add(self.b >> 1) ^ self.a;
}
#[inline(always)]
#[must_use]
pub const fn current_u8(&self) -> u8 {
self.c
}
#[inline]
#[must_use]
pub fn next_u8(&mut self) -> u8 {
self.x = self.x.wrapping_add(1);
self.a = self.a ^ self.c ^ self.x;
self.b = self.b.wrapping_add(self.a);
self.c = self.c.wrapping_add(self.b >> 1) ^ self.a;
self.c
}
#[inline]
#[must_use]
pub const fn next_new(&self) -> Self {
let [mut a, mut b, mut c, mut x] = [self.a, self.b, self.c, self.x];
x += 1;
a = a ^ c ^ x;
b = b.wrapping_add(a);
c = c.wrapping_add(b >> 1) ^ a;
Self { a, b, c, x }
}
}
impl Xabc {
#[inline]
pub const fn new3_u8(seeds: [u8; 3]) -> Self {
Self::new(seeds)
}
}
#[cfg(feature = "rand_core")]
#[cfg_attr(feature = "nightly", doc(cfg(feature = "rand_core")))]
mod impl_rand {
use super::Xabc;
use rand_core::{Error, RngCore, SeedableRng};
impl RngCore for Xabc {
fn next_u32(&mut self) -> u32 {
u32::from_le_bytes([
self.next_u8(),
self.next_u8(),
self.next_u8(),
self.next_u8(),
])
}
fn next_u64(&mut self) -> u64 {
u64::from_le_bytes([
self.next_u8(),
self.next_u8(),
self.next_u8(),
self.next_u8(),
self.next_u8(),
self.next_u8(),
self.next_u8(),
self.next_u8(),
])
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
for byte in dest {
*byte = self.next_u8();
}
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
self.fill_bytes(dest);
Ok(())
}
}
impl SeedableRng for Xabc {
type Seed = [u8; 3];
fn from_seed(seed: Self::Seed) -> Self {
Self::new(seed)
}
}
}