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.
89use byteorder::{ByteOrder, LittleEndian};
10use rand_core;
11use rand_core::le::read_u32_into;
12use rand_core::impls::{fill_bytes_via_next, next_u64_via_u32};
13use rand_core::{RngCore, SeedableRng};
1415/// A xoroshiro64* random number generator.
16///
17/// The xoroshiro64* algorithm is not suitable for cryptographic purposes, but
18/// is very fast and has good statistical properties, besides a low linear
19/// complexity in the lowest bits.
20///
21/// The algorithm used here is translated from [the `xoroshiro64star.c`
22/// reference source code](http://xoshiro.di.unimi.it/xoroshiro64star.c) by
23/// David Blackman and Sebastiano Vigna.
24#[allow(missing_copy_implementations)]
25#[derive(Debug, Clone)]
26pub struct Xoroshiro64Star {
27 s0: u32,
28 s1: u32,
29}
3031impl RngCore for Xoroshiro64Star {
32#[inline]
33fn next_u32(&mut self) -> u32 {
34let r = self.s0.wrapping_mul(0x9E3779BB);
35impl_xoroshiro_u32!(self);
36 r
37 }
3839#[inline]
40fn next_u64(&mut self) -> u64 {
41 next_u64_via_u32(self)
42 }
4344#[inline]
45fn fill_bytes(&mut self, dest: &mut [u8]) {
46 fill_bytes_via_next(self, dest);
47 }
4849#[inline]
50fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
51self.fill_bytes(dest);
52Ok(())
53 }
54}
5556impl SeedableRng for Xoroshiro64Star {
57type Seed = [u8; 8];
5859/// Create a new `Xoroshiro64Star`. If `seed` is entirely 0, it will be
60 /// mapped to a different seed.
61fn from_seed(seed: [u8; 8]) -> Xoroshiro64Star {
62deal_with_zero_seed!(seed, Self);
63let mut s = [0; 2];
64 read_u32_into(&seed, &mut s);
6566 Xoroshiro64Star {
67 s0: s[0],
68 s1: s[1],
69 }
70 }
7172/// Seed a `Xoroshiro64Star` from a `u64` using `SplitMix64`.
73fn seed_from_u64(seed: u64) -> Xoroshiro64Star {
74let mut s = [0; 8];
75 LittleEndian::write_u64(&mut s, seed);
76 Xoroshiro64Star::from_seed(s)
77 }
78}
7980#[cfg(test)]
81mod tests {
82use super::*;
8384#[test]
85fn reference() {
86let mut rng = Xoroshiro64Star::from_seed([1, 0, 0, 0, 2, 0, 0, 0]);
87// These values were produced with the reference implementation:
88 // http://xoshiro.di.unimi.it/xoshiro64star.c
89let expected = [
902654435771, 327208753, 4063491769, 4259754937, 261922412, 168123673,
91552743735, 1672597395, 1031040050, 2755315674,
92 ];
93for &e in &expected {
94assert_eq!(rng.next_u32(), e);
95 }
96 }
97}