1// Copyright 2018 Developers of the Rand project.
2// Copyright 2017 Paul Dicker.
3// Copyright 2014-2017 Melissa O'Neill and PCG Project contributors
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
1011//! PCG random number generators
1213// This is the default multiplier used by PCG for 64-bit state.
14const MULTIPLIER: u128 = 2549297995355413924u128 << 64 | 4865540595714422341;
1516use core::fmt;
17use core::mem::transmute;
18use rand_core::{RngCore, SeedableRng, Error, le};
1920/// A PCG random number generator (XSL 128/64 (MCG) variant).
21///
22/// Permuted Congruential Generator with 128-bit state, internal Multiplicative
23/// Congruential Generator, and 64-bit output via "xorshift low (bits),
24/// random rotation" output function.
25///
26/// This is a 128-bit MCG with the PCG-XSL-RR output function.
27/// Note that compared to the standard `pcg64` (128-bit LCG with PCG-XSL-RR
28/// output function), this RNG is faster, also has a long cycle, and still has
29/// good performance on statistical tests.
30///
31/// Note: this RNG is only available using Rust 1.26 or later.
32#[derive(Clone)]
33#[cfg_attr(feature="serde1", derive(Serialize,Deserialize))]
34pub struct Mcg128Xsl64 {
35 state: u128,
36}
3738/// A friendly name for `Mcg128Xsl64`.
39pub type Pcg64Mcg = Mcg128Xsl64;
4041impl Mcg128Xsl64 {
42/// Construct an instance compatible with PCG seed.
43 ///
44 /// Note that PCG specifies a default value for the parameter:
45 ///
46 /// - `state = 0xcafef00dd15ea5e5`
47pub fn new(state: u128) -> Self {
48// Force low bit to 1, as in C version (C++ uses `state | 3` instead).
49Mcg128Xsl64 { state: state | 1 }
50 }
51}
5253// Custom Debug implementation that does not expose the internal state
54impl fmt::Debug for Mcg128Xsl64 {
55fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56write!(f, "Mcg128Xsl64 {{}}")
57 }
58}
5960/// We use a single 126-bit seed to initialise the state and select a stream.
61/// Two `seed` bits (lowest order of last byte) are ignored.
62impl SeedableRng for Mcg128Xsl64 {
63type Seed = [u8; 16];
6465fn from_seed(seed: Self::Seed) -> Self {
66// Read as if a little-endian u128 value:
67let mut seed_u64 = [0u64; 2];
68 le::read_u64_into(&seed, &mut seed_u64);
69let state = (seed_u64[0] as u128) |
70 (seed_u64[1] as u128) << 64;
71 Mcg128Xsl64::new(state)
72 }
73}
7475impl RngCore for Mcg128Xsl64 {
76#[inline]
77fn next_u32(&mut self) -> u32 {
78self.next_u64() as u32
79 }
8081#[inline]
82fn next_u64(&mut self) -> u64 {
83// prepare the LCG for the next round
84let state = self.state.wrapping_mul(MULTIPLIER);
85self.state = state;
8687// Output function XSL RR ("xorshift low (bits), random rotation")
88 // Constants are for 128-bit state, 64-bit output
89const XSHIFT: u32 = 64; // (128 - 64 + 64) / 2
90const ROTATE: u32 = 122; // 128 - 6
9192let rot = (state >> ROTATE) as u32;
93let xsl = ((state >> XSHIFT) as u64) ^ (state as u64);
94 xsl.rotate_right(rot)
95 }
9697#[inline]
98fn fill_bytes(&mut self, dest: &mut [u8]) {
99// specialisation of impls::fill_bytes_via_next; approx 3x faster
100let mut left = dest;
101while left.len() >= 8 {
102let (l, r) = {left}.split_at_mut(8);
103 left = r;
104let chunk: [u8; 8] = unsafe {
105 transmute(self.next_u64().to_le())
106 };
107 l.copy_from_slice(&chunk);
108 }
109let n = left.len();
110if n > 0 {
111let chunk: [u8; 8] = unsafe {
112 transmute(self.next_u64().to_le())
113 };
114 left.copy_from_slice(&chunk[..n]);
115 }
116 }
117118#[inline]
119fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
120Ok(self.fill_bytes(dest))
121 }
122}
123124#[cfg(test)]
125mod tests {
126use ::rand_core::{RngCore, SeedableRng};
127use super::*;
128129#[test]
130fn test_mcg128xsl64_construction() {
131// Test that various construction techniques produce a working RNG.
132let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16];
133let mut rng1 = Mcg128Xsl64::from_seed(seed);
134assert_eq!(rng1.next_u64(), 7071994460355047496);
135136let mut rng2 = Mcg128Xsl64::from_rng(&mut rng1).unwrap();
137assert_eq!(rng2.next_u64(), 12300796107712034932);
138139let mut rng3 = Mcg128Xsl64::seed_from_u64(0);
140assert_eq!(rng3.next_u64(), 6198063878555692194);
141142// This is the same as Mcg128Xsl64, so we only have a single test:
143let mut rng4 = Pcg64Mcg::seed_from_u64(0);
144assert_eq!(rng4.next_u64(), 6198063878555692194);
145 }
146147#[test]
148fn test_mcg128xsl64_true_values() {
149// Numbers copied from official test suite (C version).
150let mut rng = Mcg128Xsl64::new(42);
151152let mut results = [0u64; 6];
153for i in results.iter_mut() { *i = rng.next_u64(); }
154let expected: [u64; 6] = [0x63b4a3a813ce700a, 0x382954200617ab24,
1550xa7fd85ae3fe950ce, 0xd715286aa2887737, 0x60c92fee2e59f32c, 0x84c4e96beff30017];
156assert_eq!(results, expected);
157 }
158159#[cfg(feature="serde1")]
160 #[test]
161fn test_mcg128xsl64_serde() {
162use bincode;
163use std::io::{BufWriter, BufReader};
164165let mut rng = Mcg128Xsl64::seed_from_u64(0);
166167let buf: Vec<u8> = Vec::new();
168let mut buf = BufWriter::new(buf);
169 bincode::serialize_into(&mut buf, &rng).expect("Could not serialize");
170171let buf = buf.into_inner().unwrap();
172let mut read = BufReader::new(&buf[..]);
173let mut deserialized: Mcg128Xsl64 = bincode::deserialize_from(&mut read).expect("Could not deserialize");
174175assert_eq!(rng.state, deserialized.state);
176177for _ in 0..16 {
178assert_eq!(rng.next_u64(), deserialized.next_u64());
179 }
180 }
181}