use core::convert::Infallible;
use rand_core::{Rng, SeedableRng, TryRng, utils};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Xoshiro128Plus {
s: [u32; 4],
}
impl Xoshiro128Plus {
pub fn jump(&mut self) {
impl_jump!(u32, self, [0x8764000b, 0xf542d2d3, 0x6fa035c3, 0x77f2db5b]);
}
pub fn long_jump(&mut self) {
impl_jump!(u32, self, [0xb523952e, 0x0b6f099f, 0xccf5a0ef, 0x1c580662]);
}
}
impl SeedableRng for Xoshiro128Plus {
type Seed = [u8; 16];
#[inline]
fn from_seed(seed: [u8; 16]) -> Xoshiro128Plus {
deal_with_zero_seed!(seed, Self, 16);
Xoshiro128Plus {
s: utils::read_words(&seed),
}
}
fn seed_from_u64(seed: u64) -> Xoshiro128Plus {
from_splitmix!(seed)
}
}
impl TryRng for Xoshiro128Plus {
type Error = Infallible;
#[inline]
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
let result_plus = self.s[0].wrapping_add(self.s[3]);
impl_xoshiro_u32!(self);
Ok(result_plus)
}
#[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())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reference() {
let mut rng = Xoshiro128Plus::from_seed([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]);
let expected = [
5, 12295, 25178119, 27286542, 39879690, 1140358681, 3276312097, 4110231701, 399823256,
2144435200,
];
for &e in &expected {
assert_eq!(rng.next_u32(), e);
}
}
#[test]
fn test_jump() {
let mut rng = Xoshiro128Plus::from_seed([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]);
rng.jump();
assert_eq!(rng.s[0], 2843103750);
assert_eq!(rng.s[1], 2038079848);
assert_eq!(rng.s[2], 1533207345);
assert_eq!(rng.s[3], 44816753);
}
#[test]
fn test_long_jump() {
let mut rng = Xoshiro128Plus::from_seed([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]);
rng.long_jump();
assert_eq!(rng.s[0], 1611968294);
assert_eq!(rng.s[1], 2125834322);
assert_eq!(rng.s[2], 966769569);
assert_eq!(rng.s[3], 3193880526);
}
}