1 // Copyright 2018 Developers of the Rand project.
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.
9 #[cfg(feature="serde1")] use serde::{Serialize, Deserialize};
10 use rand_core
::impls
::{next_u64_via_u32, fill_bytes_via_next}
;
11 use rand_core
::le
::read_u32_into
;
12 use rand_core
::{SeedableRng, RngCore, Error}
;
14 /// A xoshiro128+ random number generator.
16 /// The xoshiro128+ 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.
20 /// The algorithm used here is translated from [the `xoshiro128starstar.c`
21 /// reference source code](http://xoshiro.di.unimi.it/xoshiro128starstar.c) by
22 /// David Blackman and Sebastiano Vigna.
23 #[derive(Debug, Clone, PartialEq, Eq)]
24 #[cfg_attr(feature="serde1", derive(Serialize, Deserialize))]
25 pub struct Xoshiro128Plus
{
30 /// Jump forward, equivalently to 2^64 calls to `next_u32()`.
32 /// This can be used to generate 2^64 non-overlapping subsequences for
33 /// parallel computations.
36 /// use rand_xoshiro::rand_core::SeedableRng;
37 /// use rand_xoshiro::Xoroshiro128StarStar;
39 /// let rng1 = Xoroshiro128StarStar::seed_from_u64(0);
40 /// let mut rng2 = rng1.clone();
42 /// let mut rng3 = rng2.clone();
45 pub fn jump(&mut self) {
46 impl_jump
!(u32, self, [0x8764000b, 0xf542d2d3, 0x6fa035c3, 0x77f2db5b]);
50 impl SeedableRng
for Xoshiro128Plus
{
53 /// Create a new `Xoshiro128Plus`. If `seed` is entirely 0, it will be
54 /// mapped to a different seed.
56 fn from_seed(seed
: [u8; 16]) -> Xoshiro128Plus
{
57 deal_with_zero_seed
!(seed
, Self);
58 let mut state
= [0; 4];
59 read_u32_into(&seed
, &mut state
);
60 Xoshiro128Plus { s: state }
63 /// Seed a `Xoshiro128Plus` from a `u64` using `SplitMix64`.
64 fn seed_from_u64(seed
: u64) -> Xoshiro128Plus
{
69 impl RngCore
for Xoshiro128Plus
{
71 fn next_u32(&mut self) -> u32 {
72 let result_plus
= self.s
[0].wrapping_add(self.s
[3]);
73 impl_xoshiro_u32
!(self);
78 fn next_u64(&mut self) -> u64 {
79 next_u64_via_u32(self)
83 fn fill_bytes(&mut self, dest
: &mut [u8]) {
84 fill_bytes_via_next(self, dest
);
88 fn try_fill_bytes(&mut self, dest
: &mut [u8]) -> Result
<(), Error
> {
89 self.fill_bytes(dest
);
100 let mut rng
= Xoshiro128Plus
::from_seed(
101 [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]);
102 // These values were produced with the reference implementation:
103 // http://xoshiro.di.unimi.it/xoshiro128plus.c
105 5, 12295, 25178119, 27286542, 39879690, 1140358681, 3276312097,
106 4110231701, 399823256, 2144435200,
108 for &e
in &expected
{
109 assert_eq
!(rng
.next_u32(), e
);