1use core::convert::Infallible;
10use rand_core::{Rng, SeedableRng, TryRng, utils};
11#[cfg(feature = "serde")]
12use serde::{Deserialize, Serialize};
13
14#[derive(Debug, Clone, PartialEq, Eq)]
24#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
25pub struct Xoshiro128Plus {
26 s: [u32; 4],
27}
28
29impl Xoshiro128Plus {
30 pub fn jump(&mut self) {
46 impl_jump!(u32, self, [0x8764000b, 0xf542d2d3, 0x6fa035c3, 0x77f2db5b]);
47 }
48
49 pub fn long_jump(&mut self) {
55 impl_jump!(u32, self, [0xb523952e, 0x0b6f099f, 0xccf5a0ef, 0x1c580662]);
56 }
57}
58
59impl_state_array_of_four!(Xoshiro128Plus, u32);
60
61impl SeedableRng for Xoshiro128Plus {
62 type Seed = [u8; 16];
63
64 #[inline]
67 fn from_seed(seed: [u8; 16]) -> Xoshiro128Plus {
68 Xoshiro128Plus {
69 s: utils::read_words(crate::common::zero_seed_fallback(&seed)),
70 }
71 }
72
73 fn seed_from_u64(seed: u64) -> Xoshiro128Plus {
75 from_splitmix!(seed)
76 }
77}
78
79impl TryRng for Xoshiro128Plus {
80 type Error = Infallible;
81
82 #[inline]
83 fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
84 let result_plus = self.s[0].wrapping_add(self.s[3]);
85 impl_xoshiro_u32!(self);
86 Ok(result_plus)
87 }
88
89 #[inline]
90 fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
91 utils::next_u64_via_u32(self)
92 }
93
94 #[inline]
95 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
96 utils::fill_bytes_via_next_word(dest, || self.try_next_u32())
97 }
98}
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103
104 #[test]
105 fn reference() {
106 let mut rng = Xoshiro128Plus::from_seed([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]);
107 let expected = [
110 5, 12295, 25178119, 27286542, 39879690, 1140358681, 3276312097, 4110231701, 399823256,
111 2144435200,
112 ];
113 for &e in &expected {
114 assert_eq!(rng.next_u32(), e);
115 }
116 }
117
118 #[test]
119 fn test_jump() {
120 let mut rng = Xoshiro128Plus::from_seed([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]);
121 rng.jump();
122 assert_eq!(rng.s[0], 2843103750);
125 assert_eq!(rng.s[1], 2038079848);
126 assert_eq!(rng.s[2], 1533207345);
127 assert_eq!(rng.s[3], 44816753);
128 }
129
130 #[test]
131 fn test_long_jump() {
132 let mut rng = Xoshiro128Plus::from_seed([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]);
133 rng.long_jump();
134 assert_eq!(rng.s[0], 1611968294);
137 assert_eq!(rng.s[1], 2125834322);
138 assert_eq!(rng.s[2], 966769569);
139 assert_eq!(rng.s[3], 3193880526);
140 }
141
142 #[test]
143 fn zero_seed_maps_to_seed_from_u64_zero() {
144 let from_zero = Xoshiro128Plus::from_seed([0u8; 16]);
145 let from_sm0 = Xoshiro128Plus::seed_from_u64(0);
146 assert_eq!(from_zero, from_sm0);
147 }
148
149 #[test]
150 fn state_roundtrip() {
151 let rng = Xoshiro128Plus::seed_from_u64(42);
152 let clone = Xoshiro128Plus::from_seed(rng.state());
153 assert_eq!(clone, rng);
154 }
155}