rand_pcg/
pcg128.rs

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.
10
11//! PCG random number generators
12
13// This is the default multiplier used by PCG for 64-bit state.
14const MULTIPLIER: u128 = 2549297995355413924u128 << 64 | 4865540595714422341;
15
16use core::fmt;
17use core::mem::transmute;
18use rand_core::{RngCore, SeedableRng, Error, le};
19
20/// 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}
37
38/// A friendly name for `Mcg128Xsl64`.
39pub type Pcg64Mcg = Mcg128Xsl64;
40
41impl 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`
47    pub fn new(state: u128) -> Self {
48        // Force low bit to 1, as in C version (C++ uses `state | 3` instead).
49        Mcg128Xsl64 { state: state | 1 }
50    }
51}
52
53// Custom Debug implementation that does not expose the internal state
54impl fmt::Debug for Mcg128Xsl64 {
55    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56        write!(f, "Mcg128Xsl64 {{}}")
57    }
58}
59
60/// 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 {
63    type Seed = [u8; 16];
64
65    fn from_seed(seed: Self::Seed) -> Self {
66        // Read as if a little-endian u128 value:
67        let mut seed_u64 = [0u64; 2];
68        le::read_u64_into(&seed, &mut seed_u64);
69        let state = (seed_u64[0] as u128) |
70                    (seed_u64[1] as u128) << 64;
71        Mcg128Xsl64::new(state)
72    }
73}
74
75impl RngCore for Mcg128Xsl64 {
76    #[inline]
77    fn next_u32(&mut self) -> u32 {
78        self.next_u64() as u32
79    }
80
81    #[inline]
82    fn next_u64(&mut self) -> u64 {
83        // prepare the LCG for the next round
84        let state = self.state.wrapping_mul(MULTIPLIER);
85        self.state = state;
86
87        // Output function XSL RR ("xorshift low (bits), random rotation")
88        // Constants are for 128-bit state, 64-bit output
89        const XSHIFT: u32 = 64;     // (128 - 64 + 64) / 2
90        const ROTATE: u32 = 122;    // 128 - 6
91
92        let rot = (state >> ROTATE) as u32;
93        let xsl = ((state >> XSHIFT) as u64) ^ (state as u64);
94        xsl.rotate_right(rot)
95    }
96
97    #[inline]
98    fn fill_bytes(&mut self, dest: &mut [u8]) {
99        // specialisation of impls::fill_bytes_via_next; approx 3x faster
100        let mut left = dest;
101        while left.len() >= 8 {
102            let (l, r) = {left}.split_at_mut(8);
103            left = r;
104            let chunk: [u8; 8] = unsafe {
105                transmute(self.next_u64().to_le())
106            };
107            l.copy_from_slice(&chunk);
108        }
109        let n = left.len();
110        if n > 0 {
111            let chunk: [u8; 8] = unsafe {
112                transmute(self.next_u64().to_le())
113            };
114            left.copy_from_slice(&chunk[..n]);
115        }
116    }
117
118    #[inline]
119    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
120        Ok(self.fill_bytes(dest))
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use ::rand_core::{RngCore, SeedableRng};
127    use super::*;
128
129    #[test]
130    fn test_mcg128xsl64_construction() {
131        // Test that various construction techniques produce a working RNG.
132        let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16];
133        let mut rng1 = Mcg128Xsl64::from_seed(seed);
134        assert_eq!(rng1.next_u64(), 7071994460355047496);
135
136        let mut rng2 = Mcg128Xsl64::from_rng(&mut rng1).unwrap();
137        assert_eq!(rng2.next_u64(), 12300796107712034932);
138
139        let mut rng3 = Mcg128Xsl64::seed_from_u64(0);
140        assert_eq!(rng3.next_u64(), 6198063878555692194);
141
142        // This is the same as Mcg128Xsl64, so we only have a single test:
143        let mut rng4 = Pcg64Mcg::seed_from_u64(0);
144        assert_eq!(rng4.next_u64(), 6198063878555692194);
145    }
146
147    #[test]
148    fn test_mcg128xsl64_true_values() {
149        // Numbers copied from official test suite (C version).
150        let mut rng = Mcg128Xsl64::new(42);
151
152        let mut results = [0u64; 6];
153        for i in results.iter_mut() { *i = rng.next_u64(); }
154        let expected: [u64; 6] = [0x63b4a3a813ce700a, 0x382954200617ab24,
155            0xa7fd85ae3fe950ce, 0xd715286aa2887737, 0x60c92fee2e59f32c, 0x84c4e96beff30017];
156        assert_eq!(results, expected);
157    }
158
159    #[cfg(feature="serde1")]
160    #[test]
161    fn test_mcg128xsl64_serde() {
162        use bincode;
163        use std::io::{BufWriter, BufReader};
164
165        let mut rng = Mcg128Xsl64::seed_from_u64(0);
166
167        let buf: Vec<u8> = Vec::new();
168        let mut buf = BufWriter::new(buf);
169        bincode::serialize_into(&mut buf, &rng).expect("Could not serialize");
170
171        let buf = buf.into_inner().unwrap();
172        let mut read = BufReader::new(&buf[..]);
173        let mut deserialized: Mcg128Xsl64 = bincode::deserialize_from(&mut read).expect("Could not deserialize");
174
175        assert_eq!(rng.state, deserialized.state);
176
177        for _ in 0..16 {
178            assert_eq!(rng.next_u64(), deserialized.next_u64());
179        }
180    }
181}