Skip to main content

rand_xoshiro/
xoshiro128starstar.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 excellent statistical properties.
18///
19/// The algorithm used here is translated from [the `xoshiro128starstar.c`
20/// reference source code](http://xoshiro.di.unimi.it/xoshiro128starstar.c) by
21/// David Blackman and Sebastiano Vigna.
22#[derive(Debug, Clone, PartialEq, Eq)]
23#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
24pub struct Xoshiro128StarStar {
25    s: [u32; 4],
26}
27
28impl Xoshiro128StarStar {
29    /// Jump forward, equivalently to 2^64 calls to `next_u32()`.
30    ///
31    /// This can be used to generate 2^64 non-overlapping subsequences for
32    /// parallel computations.
33    ///
34    /// ```
35    /// use rand_xoshiro::rand_core::SeedableRng;
36    /// use rand_xoshiro::Xoroshiro128StarStar;
37    ///
38    /// let rng1 = Xoroshiro128StarStar::seed_from_u64(0);
39    /// let mut rng2 = rng1.clone();
40    /// rng2.jump();
41    /// let mut rng3 = rng2.clone();
42    /// rng3.jump();
43    /// ```
44    pub fn jump(&mut self) {
45        impl_jump!(u32, self, [0x8764000b, 0xf542d2d3, 0x6fa035c3, 0x77f2db5b]);
46    }
47
48    /// Jump forward, equivalently to 2^96 calls to `next_u32()`.
49    ///
50    /// This can be used to generate 2^32 starting points, from each of which
51    /// `jump()` will generate 2^32 non-overlapping subsequences for parallel
52    /// distributed computations.
53    pub fn long_jump(&mut self) {
54        impl_jump!(u32, self, [0xb523952e, 0x0b6f099f, 0xccf5a0ef, 0x1c580662]);
55    }
56}
57
58impl_state_array_of_four!(Xoshiro128StarStar, u32);
59
60impl SeedableRng for Xoshiro128StarStar {
61    type Seed = [u8; 16];
62
63    /// Create a new `Xoshiro128StarStar`.  If `seed` is entirely 0, it will be
64    /// mapped to a different seed.
65    #[inline]
66    fn from_seed(seed: [u8; 16]) -> Xoshiro128StarStar {
67        Xoshiro128StarStar {
68            s: utils::read_words(crate::common::zero_seed_fallback(&seed)),
69        }
70    }
71
72    /// Seed a `Xoshiro128StarStar` from a `u64` using `SplitMix64`.
73    fn seed_from_u64(seed: u64) -> Xoshiro128StarStar {
74        from_splitmix!(seed)
75    }
76}
77
78impl TryRng for Xoshiro128StarStar {
79    type Error = Infallible;
80
81    #[inline]
82    fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
83        let result_starstar = starstar_u64!(self.s[1]);
84        impl_xoshiro_u32!(self);
85        Ok(result_starstar)
86    }
87
88    #[inline]
89    fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
90        utils::next_u64_via_u32(self)
91    }
92
93    #[inline]
94    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
95        utils::fill_bytes_via_next_word(dest, || self.try_next_u32())
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn reference() {
105        let mut rng =
106            Xoshiro128StarStar::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 (v1.1):
108        // http://xoshiro.di.unimi.it/xoshiro128starstar.c
109        let expected = [
110            11520, 0, 5927040, 70819200, 2031721883, 1637235492, 1287239034, 3734860849,
111            3729100597, 4258142804,
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 =
121            Xoshiro128StarStar::from_seed([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]);
122        rng.jump();
123        // These values were produced by instrumenting the reference implementation:
124        // http://xoshiro.di.unimi.it/xoshiro128plus.c
125        assert_eq!(rng.s[0], 2843103750);
126        assert_eq!(rng.s[1], 2038079848);
127        assert_eq!(rng.s[2], 1533207345);
128        assert_eq!(rng.s[3], 44816753);
129    }
130
131    #[test]
132    fn test_long_jump() {
133        let mut rng =
134            Xoshiro128StarStar::from_seed([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]);
135        rng.long_jump();
136        // These values were produced by instrumenting the reference implementation:
137        // http://xoshiro.di.unimi.it/xoshiro128plus.c
138        assert_eq!(rng.s[0], 1611968294);
139        assert_eq!(rng.s[1], 2125834322);
140        assert_eq!(rng.s[2], 966769569);
141        assert_eq!(rng.s[3], 3193880526);
142    }
143
144    #[test]
145    fn zero_seed_maps_to_seed_from_u64_zero() {
146        let from_zero = Xoshiro128StarStar::from_seed([0u8; 16]);
147        let from_sm0 = Xoshiro128StarStar::seed_from_u64(0);
148        assert_eq!(from_zero, from_sm0);
149    }
150
151    #[test]
152    fn state_roundtrip() {
153        let rng = Xoshiro128StarStar::seed_from_u64(42);
154        let clone = Xoshiro128StarStar::from_seed(rng.state());
155        assert_eq!(clone, rng);
156    }
157}