Skip to main content

rand_xoshiro/
xoshiro128plus.rs

1// Copyright 2018 Developers of the Rand project.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use core::convert::Infallible;
10use rand_core::{Rng, SeedableRng, TryRng, utils};
11#[cfg(feature = "serde")]
12use serde::{Deserialize, Serialize};
13
14/// A xoshiro128+ random number generator.
15///
16/// The xoshiro128+ algorithm is not suitable for cryptographic purposes, but
17/// is very fast and has good statistical properties, besides a low linear
18/// complexity in the lowest bits.
19///
20/// The algorithm used here is translated from [the `xoshiro128starstar.c`
21/// reference source code](http://xoshiro.di.unimi.it/xoshiro128starstar.c) by
22/// David Blackman and Sebastiano Vigna.
23#[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    /// Jump forward, equivalently to 2^64 calls to `next_u32()`.
31    ///
32    /// This can be used to generate 2^64 non-overlapping subsequences for
33    /// parallel computations.
34    ///
35    /// ```
36    /// use rand_xoshiro::rand_core::SeedableRng;
37    /// use rand_xoshiro::Xoroshiro128StarStar;
38    ///
39    /// let rng1 = Xoroshiro128StarStar::seed_from_u64(0);
40    /// let mut rng2 = rng1.clone();
41    /// rng2.jump();
42    /// let mut rng3 = rng2.clone();
43    /// rng3.jump();
44    /// ```
45    pub fn jump(&mut self) {
46        impl_jump!(u32, self, [0x8764000b, 0xf542d2d3, 0x6fa035c3, 0x77f2db5b]);
47    }
48
49    /// Jump forward, equivalently to 2^96 calls to `next_u32()`.
50    ///
51    /// This can be used to generate 2^32 starting points, from each of which
52    /// `jump()` will generate 2^32 non-overlapping subsequences for parallel
53    /// distributed computations.
54    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    /// Create a new `Xoshiro128Plus`.  If `seed` is entirely 0, it will be
65    /// mapped to a different seed.
66    #[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    /// Seed a `Xoshiro128Plus` from a `u64` using `SplitMix64`.
74    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        // These values were produced with the reference implementation:
108        // http://xoshiro.di.unimi.it/xoshiro128plus.c
109        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        // These values were produced by instrumenting the reference implementation:
123        // http://xoshiro.di.unimi.it/xoshiro128plus.c
124        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        // These values were produced by instrumenting the reference implementation:
135        // http://xoshiro.di.unimi.it/xoshiro128plus.c
136        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}