Skip to main content

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