rand_xoshiro/
xoroshiro128plus.rs1use core::convert::Infallible;
10use rand_core::{Rng, SeedableRng, TryRng, utils};
11#[cfg(feature = "serde")]
12use serde::{Deserialize, Serialize};
13
14#[allow(missing_copy_implementations)]
24#[derive(Debug, Clone, PartialEq, Eq)]
25#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
26pub struct Xoroshiro128Plus {
27 s0: u64,
28 s1: u64,
29}
30
31impl Xoroshiro128Plus {
32 pub fn jump(&mut self) {
48 impl_jump!(u64, self, [0xdf900294d8f554a5, 0x170865df4b3201fc]);
49 }
50
51 pub fn long_jump(&mut self) {
57 impl_jump!(u64, self, [0xd2a98b26625eee7b, 0xdddf9b1090aa7ac1]);
58 }
59}
60
61impl TryRng for Xoroshiro128Plus {
62 type Error = Infallible;
63
64 #[inline]
65 fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
66 Ok((self.next_u64() >> 32) as u32)
69 }
70
71 #[inline]
72 fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
73 let r = self.s0.wrapping_add(self.s1);
74 impl_xoroshiro_u64!(self);
75 Ok(r)
76 }
77
78 #[inline]
79 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
80 utils::fill_bytes_via_next_word(dest, || self.try_next_u64())
81 }
82}
83impl_state_pair!(Xoroshiro128Plus, u64);
84
85impl SeedableRng for Xoroshiro128Plus {
86 type Seed = [u8; 16];
87
88 fn from_seed(seed: [u8; 16]) -> Xoroshiro128Plus {
91 let s: [_; 2] = utils::read_words(crate::common::zero_seed_fallback(&seed));
92
93 Xoroshiro128Plus { s0: s[0], s1: s[1] }
94 }
95
96 fn seed_from_u64(seed: u64) -> Xoroshiro128Plus {
98 from_splitmix!(seed)
99 }
100}
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105
106 #[test]
107 fn reference() {
108 let mut rng = Xoroshiro128Plus::from_seed([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]);
109 let expected = [
112 3,
113 412333834243,
114 2360170716294286339,
115 9295852285959843169,
116 2797080929874688578,
117 6019711933173041966,
118 3076529664176959358,
119 3521761819100106140,
120 7493067640054542992,
121 920801338098114767,
122 ];
123 for &e in &expected {
124 assert_eq!(rng.next_u64(), e);
125 }
126 }
127
128 #[test]
129 fn zero_seed_maps_to_seed_from_u64_zero() {
130 let from_zero = Xoroshiro128Plus::from_seed([0u8; 16]);
131 let from_sm0 = Xoroshiro128Plus::seed_from_u64(0);
132 assert_eq!(from_zero, from_sm0);
133 }
134
135 #[test]
136 fn state_roundtrip() {
137 let rng = Xoroshiro128Plus::seed_from_u64(42);
138 let clone = Xoroshiro128Plus::from_seed(rng.state());
139 assert_eq!(clone, rng);
140 }
141}