Skip to main content

rand_xoshiro/
xoroshiro128plusplus.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 `xoroshiro128plusplus.c`
20/// reference source code](http://xoshiro.di.unimi.it/xoroshiro128plusplus.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 Xoroshiro128PlusPlus {
26    s0: u64,
27    s1: u64,
28}
29
30impl Xoroshiro128PlusPlus {
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::Xoroshiro128PlusPlus;
39    ///
40    /// let rng1 = Xoroshiro128PlusPlus::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, [0x2bd7a6a6e99c2ddc, 0x0992ccaf6a6fca05]);
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, [0x360fd5f2cf8d5d99, 0x9c6e6877736c46e3]);
57    }
58}
59
60impl TryRng for Xoroshiro128PlusPlus {
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 = plusplus_u64!(self.s0, self.s1, 17);
71        impl_xoroshiro_u64_plusplus!(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!(Xoroshiro128PlusPlus, u64);
82
83impl SeedableRng for Xoroshiro128PlusPlus {
84    type Seed = [u8; 16];
85
86    /// Create a new `Xoroshiro128PlusPlus`.  If `seed` is entirely 0, it will be
87    /// mapped to a different seed.
88    fn from_seed(seed: [u8; 16]) -> Xoroshiro128PlusPlus {
89        let s: [_; 2] = utils::read_words(crate::common::zero_seed_fallback(&seed));
90
91        Xoroshiro128PlusPlus { s0: s[0], s1: s[1] }
92    }
93
94    /// Seed a `Xoroshiro128PlusPlus` from a `u64` using `SplitMix64`.
95    fn seed_from_u64(seed: u64) -> Xoroshiro128PlusPlus {
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            Xoroshiro128PlusPlus::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/xoshiro128plusplus.c
110        let expected = [
111            393217,
112            669327710093319,
113            1732421326133921491,
114            11394790081659126983,
115            9555452776773192676,
116            3586421180005889563,
117            1691397964866707553,
118            10735626796753111697,
119            15216282715349408991,
120            14247243556711267923,
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 = Xoroshiro128PlusPlus::from_seed([0u8; 16]);
130        let from_sm0 = Xoroshiro128PlusPlus::seed_from_u64(0);
131        assert_eq!(from_zero, from_sm0);
132    }
133
134    #[test]
135    fn state_roundtrip() {
136        let rng = Xoroshiro128PlusPlus::seed_from_u64(42);
137        let clone = Xoroshiro128PlusPlus::from_seed(rng.state());
138        assert_eq!(clone, rng);
139    }
140}