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
9#[cfg(feature="serde1")] use serde::{Serialize, Deserialize};
10use rand_core::le::read_u32_into;
11use rand_core::impls::{fill_bytes_via_next, next_u64_via_u32};
12use rand_core::{RngCore, SeedableRng};
13
14/// A xoroshiro64** random number generator.
15///
16/// The xoshiro64** 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 `xoroshiro64starstar.c`
20/// reference source code](http://xoshiro.di.unimi.it/xoroshiro64starstar.c) by
21/// David Blackman and Sebastiano Vigna.
22#[allow(missing_copy_implementations)]
23#[derive(Debug, Clone, PartialEq, Eq)]
24#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))]
25pub struct Xoroshiro64StarStar {
26 s0: u32,
27 s1: u32,
28}
29
30impl RngCore for Xoroshiro64StarStar {
31 #[inline]
32 fn next_u32(&mut self) -> u32 {
33 let r: u32 = starstar_u32!(self.s0);
34 impl_xoroshiro_u32!(self);
35 r
36 }
37
38 #[inline]
39 fn next_u64(&mut self) -> u64 {
40 next_u64_via_u32(self)
41 }
42
43 #[inline]
44 fn fill_bytes(&mut self, dest: &mut [u8]) {
45 fill_bytes_via_next(self, dest);
46 }
47
48 #[inline]
49 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
50 self.fill_bytes(dest);
51 Ok(())
52 }
53}
54
55impl SeedableRng for Xoroshiro64StarStar {
56 type Seed = [u8; 8];
57
58 /// Create a new `Xoroshiro64StarStar`. If `seed` is entirely 0, it will be
59 /// mapped to a different seed.
60 fn from_seed(seed: [u8; 8]) -> Xoroshiro64StarStar {
61 deal_with_zero_seed!(seed, Self);
62 let mut s: [u32; 2] = [0; 2];
63 read_u32_into(&seed, &mut s);
64
65 Xoroshiro64StarStar {
66 s0: s[0],
67 s1: s[1],
68 }
69 }
70
71 /// Seed a `Xoroshiro64StarStar` from a `u64` using `SplitMix64`.
72 fn seed_from_u64(seed: u64) -> Xoroshiro64StarStar {
73 from_splitmix!(seed)
74 }
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 #[test]
82 fn reference() {
83 let mut rng = Xoroshiro64StarStar::from_seed([1, 0, 0, 0, 2, 0, 0, 0]);
84 // These values were produced with the reference implementation:
85 // http://xoshiro.di.unimi.it/xoshiro64starstar.c
86 let expected = [
87 3802928447, 813792938, 1618621494, 2955957307, 3252880261,
88 1129983909, 2539651700, 1327610908, 1757650787, 2763843748,
89 ];
90 for &e in &expected {
91 assert_eq!(rng.next_u32(), e);
92 }
93 }
94
95 #[test]
96 fn zero_seed() {
97 let mut rng = Xoroshiro64StarStar::seed_from_u64(0);
98 assert_ne!(rng.next_u64(), 0);
99 }
100}
101