Skip to main content

rand_xoshiro/
xoroshiro128starstar.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 xoroshiro128** random number generator.
15///
16/// The xoroshiro128** 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 `xoroshiro128starstar.c`
20/// reference source code](http://xoshiro.di.unimi.it/xoroshiro128starstar.c) by
21/// David Blackman and Sebastiano Vigna.
22#[allow(missing_copy_implementations)]
23#[derive(Debug, Clone, PartialEq, Eq)]
24#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
25pub struct Xoroshiro128StarStar {
26    s0: u64,
27    s1: u64,
28}
29
30impl Xoroshiro128StarStar {
31    /// Jump forward, equivalently to 2^64 calls to `next_u64()`.
32    ///
33    /// This can be used to generate 2^64 non-overlapping subsequences for
34    /// parallel computations.
35    ///
36    /// ```
37    /// use rand_xoshiro::rand_core::SeedableRng;
38    /// use rand_xoshiro::Xoroshiro128StarStar;
39    ///
40    /// let rng1 = Xoroshiro128StarStar::seed_from_u64(0);
41    /// let mut rng2 = rng1.clone();
42    /// rng2.jump();
43    /// let mut rng3 = rng2.clone();
44    /// rng3.jump();
45    /// ```
46    pub fn jump(&mut self) {
47        impl_jump!(u64, self, [0xdf900294d8f554a5, 0x170865df4b3201fc]);
48    }
49
50    /// Jump forward, equivalently to 2^96 calls to `next_u64()`.
51    ///
52    /// This can be used to generate 2^32 starting points, from each of which
53    /// `jump()` will generate 2^32 non-overlapping subsequences for parallel
54    /// distributed computations.
55    pub fn long_jump(&mut self) {
56        impl_jump!(u64, self, [0xd2a98b26625eee7b, 0xdddf9b1090aa7ac1]);
57    }
58}
59
60impl TryRng for Xoroshiro128StarStar {
61    type Error = Infallible;
62
63    #[inline]
64    fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
65        Ok(self.next_u64() as u32)
66    }
67
68    #[inline]
69    fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
70        let r = starstar_u64!(self.s0);
71        impl_xoroshiro_u64!(self);
72        Ok(r)
73    }
74
75    #[inline]
76    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
77        utils::fill_bytes_via_next_word(dest, || self.try_next_u64())
78    }
79}
80
81impl_state_pair!(Xoroshiro128StarStar, u64);
82
83impl SeedableRng for Xoroshiro128StarStar {
84    type Seed = [u8; 16];
85
86    /// Create a new `Xoroshiro128StarStar`.  If `seed` is entirely 0, it will be
87    /// mapped to a different seed.
88    fn from_seed(seed: [u8; 16]) -> Xoroshiro128StarStar {
89        let s: [_; 2] = utils::read_words(crate::common::zero_seed_fallback(&seed));
90
91        Xoroshiro128StarStar { s0: s[0], s1: s[1] }
92    }
93
94    /// Seed a `Xoroshiro128StarStar` from a `u64` using `SplitMix64`.
95    fn seed_from_u64(seed: u64) -> Xoroshiro128StarStar {
96        from_splitmix!(seed)
97    }
98}
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103
104    #[test]
105    fn reference() {
106        let mut rng =
107            Xoroshiro128StarStar::from_seed([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]);
108        // These values were produced with the reference implementation:
109        // http://xoshiro.di.unimi.it/xoshiro128starstar.c
110        let expected = [
111            5760,
112            97769243520,
113            9706862127477703552,
114            9223447511460779954,
115            8358291023205304566,
116            15695619998649302768,
117            8517900938696309774,
118            16586480348202605369,
119            6959129367028440372,
120            16822147227405758281,
121        ];
122        for &e in &expected {
123            assert_eq!(rng.next_u64(), e);
124        }
125    }
126
127    #[test]
128    fn zero_seed_maps_to_seed_from_u64_zero() {
129        let from_zero = Xoroshiro128StarStar::from_seed([0u8; 16]);
130        let from_sm0 = Xoroshiro128StarStar::seed_from_u64(0);
131        assert_eq!(from_zero, from_sm0);
132    }
133
134    #[test]
135    fn state_roundtrip() {
136        let rng = Xoroshiro128StarStar::seed_from_u64(42);
137        let clone = Xoroshiro128StarStar::from_seed(rng.state());
138        assert_eq!(clone, rng);
139    }
140}