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