/rust/registry/src/index.crates.io-1949cf8c6b5b557f/rand_pcg-0.10.3/src/pcg64.rs
Line | Count | Source |
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 | | use core::{convert::Infallible, fmt}; |
14 | | use rand_core::{SeedableRng, TryRng, utils}; |
15 | | #[cfg(feature = "serde")] |
16 | | use serde::{Deserialize, Serialize}; |
17 | | |
18 | | // This is the default multiplier used by PCG for 64-bit state. |
19 | | const MULTIPLIER: u64 = 6364136223846793005; |
20 | | |
21 | | /// A PCG random number generator (XSH RR 64/32 (LCG) variant). |
22 | | /// |
23 | | /// Permuted Congruential Generator with 64-bit state, internal Linear |
24 | | /// Congruential Generator, and 32-bit output via "xorshift high (bits), |
25 | | /// random rotation" output function. |
26 | | /// |
27 | | /// This is a 64-bit LCG with explicitly chosen stream with the PCG-XSH-RR |
28 | | /// output function. This combination is the standard `pcg32`. |
29 | | /// |
30 | | /// Despite the name, this implementation uses 16 bytes (128 bit) space |
31 | | /// comprising 64 bits of state and 64 bits stream selector. These are both set |
32 | | /// by `SeedableRng`, using a 128-bit seed. |
33 | | /// |
34 | | /// Note that two generators with different stream parameter may be closely |
35 | | /// correlated. |
36 | | #[derive(Clone, PartialEq, Eq)] |
37 | | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] |
38 | | pub struct Lcg64Xsh32 { |
39 | | state: u64, |
40 | | increment: u64, |
41 | | } |
42 | | |
43 | | /// [`Lcg64Xsh32`] is also officially known as `pcg32`. |
44 | | pub type Pcg32 = Lcg64Xsh32; |
45 | | |
46 | | impl Lcg64Xsh32 { |
47 | | /// Multi-step advance functions (jump-ahead, jump-back) |
48 | | /// |
49 | | /// The method used here is based on Brown, "Random Number Generation |
50 | | /// with Arbitrary Stride,", Transactions of the American Nuclear |
51 | | /// Society (Nov. 1994). The algorithm is very similar to fast |
52 | | /// exponentiation. |
53 | | /// |
54 | | /// Even though delta is an unsigned integer, we can pass a |
55 | | /// signed integer to go backwards, it just goes "the long way round". |
56 | | /// |
57 | | /// Using this function is equivalent to calling `next_32()` `delta` |
58 | | /// number of times. |
59 | | /// |
60 | | /// # Warning |
61 | | /// |
62 | | /// Do not advance by a large power of two, such as `1 << 63` (half of the |
63 | | /// period), to split a single stream into several. The state is an LCG |
64 | | /// modulo `2^64`, whose lowest `e` bits repeat every `2^e` steps, so |
65 | | /// advancing by `2^e` leaves them unchanged. After `advance(1 << 63)`, the |
66 | | /// two states differ only in their top bit at every step, and each output |
67 | | /// is the other with its 16-bit halves swapped and one bit flipped. |
68 | | #[inline] |
69 | 0 | pub fn advance(&mut self, delta: u64) { |
70 | 0 | let mut acc_mult: u64 = 1; |
71 | 0 | let mut acc_plus: u64 = 0; |
72 | 0 | let mut cur_mult = MULTIPLIER; |
73 | 0 | let mut cur_plus = self.increment; |
74 | 0 | let mut mdelta = delta; |
75 | | |
76 | 0 | while mdelta > 0 { |
77 | 0 | if (mdelta & 1) != 0 { |
78 | 0 | acc_mult = acc_mult.wrapping_mul(cur_mult); |
79 | 0 | acc_plus = acc_plus.wrapping_mul(cur_mult).wrapping_add(cur_plus); |
80 | 0 | } |
81 | 0 | cur_plus = cur_mult.wrapping_add(1).wrapping_mul(cur_plus); |
82 | 0 | cur_mult = cur_mult.wrapping_mul(cur_mult); |
83 | 0 | mdelta /= 2; |
84 | | } |
85 | 0 | self.state = acc_mult.wrapping_mul(self.state).wrapping_add(acc_plus); |
86 | 0 | } |
87 | | |
88 | | /// Construct an instance compatible with PCG seed and stream. |
89 | | /// |
90 | | /// Note that the highest bit of the `stream` parameter is discarded |
91 | | /// to simplify upholding internal invariants. |
92 | | /// |
93 | | /// Note that two generators with different stream parameters may be closely |
94 | | /// correlated. |
95 | | /// |
96 | | /// PCG specifies the following default values for both parameters: |
97 | | /// |
98 | | /// - `state = 0xcafef00dd15ea5e5` |
99 | | /// - `stream = 0xa02bdbf7bb3c0a7` |
100 | | // Note: stream is 1442695040888963407u64 >> 1 |
101 | 0 | pub fn new(state: u64, stream: u64) -> Self { |
102 | | // The increment must be odd, hence we discard one bit: |
103 | 0 | let increment = (stream << 1) | 1; |
104 | 0 | Lcg64Xsh32::from_state_incr(state, increment) |
105 | 0 | } |
106 | | |
107 | | #[inline] |
108 | 0 | fn from_state_incr(state: u64, increment: u64) -> Self { |
109 | 0 | let mut pcg = Lcg64Xsh32 { state, increment }; |
110 | | // Move away from initial value: |
111 | 0 | pcg.state = pcg.state.wrapping_add(pcg.increment); |
112 | 0 | pcg.step(); |
113 | 0 | pcg |
114 | 0 | } |
115 | | |
116 | | #[inline] |
117 | 0 | fn step(&mut self) { |
118 | | // prepare the LCG for the next round |
119 | 0 | self.state = self |
120 | 0 | .state |
121 | 0 | .wrapping_mul(MULTIPLIER) |
122 | 0 | .wrapping_add(self.increment); |
123 | 0 | } Unexecuted instantiation: <rand_pcg::pcg64::Lcg64Xsh32>::step Unexecuted instantiation: <rand_pcg::pcg64::Lcg64Xsh32>::step |
124 | | } |
125 | | |
126 | | crate::macros::impl_state_stream!(Lcg64Xsh32, u64); |
127 | | |
128 | | // Custom Debug implementation that does not expose the internal state |
129 | | impl fmt::Debug for Lcg64Xsh32 { |
130 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
131 | 0 | write!(f, "Lcg64Xsh32 {{}}") |
132 | 0 | } |
133 | | } |
134 | | |
135 | | impl SeedableRng for Lcg64Xsh32 { |
136 | | type Seed = [u8; 16]; |
137 | | |
138 | | /// We use a single 127-bit seed to initialise the state and select a stream. |
139 | | /// One `seed` bit (lowest bit of `seed[8]`) is ignored. |
140 | 0 | fn from_seed(seed: Self::Seed) -> Self { |
141 | 0 | let seed_u64: [u64; 2] = utils::read_words(&seed); |
142 | | |
143 | | // The increment must be odd, hence we discard one bit: |
144 | 0 | Lcg64Xsh32::from_state_incr(seed_u64[0], seed_u64[1] | 1) |
145 | 0 | } |
146 | | } |
147 | | |
148 | | impl TryRng for Lcg64Xsh32 { |
149 | | type Error = Infallible; |
150 | | |
151 | | #[inline] |
152 | 0 | fn try_next_u32(&mut self) -> Result<u32, Infallible> { |
153 | 0 | let state = self.state; |
154 | 0 | self.step(); |
155 | | |
156 | | // Output function XSH RR: xorshift high (bits), followed by a random rotate |
157 | | // Constants are for 64-bit state, 32-bit output |
158 | | const ROTATE: u32 = 59; // 64 - 5 |
159 | | const XSHIFT: u32 = 18; // (5 + 32) / 2 |
160 | | const SPARE: u32 = 27; // 64 - 32 - 5 |
161 | | |
162 | 0 | let rot = (state >> ROTATE) as u32; |
163 | 0 | let xsh = (((state >> XSHIFT) ^ state) >> SPARE) as u32; |
164 | 0 | Ok(xsh.rotate_right(rot)) |
165 | 0 | } Unexecuted instantiation: <rand_pcg::pcg64::Lcg64Xsh32 as rand_core::TryRng>::try_next_u32 Unexecuted instantiation: <rand_pcg::pcg64::Lcg64Xsh32 as rand_core::TryRng>::try_next_u32 |
166 | | |
167 | | #[inline] |
168 | 0 | fn try_next_u64(&mut self) -> Result<u64, Infallible> { |
169 | 0 | utils::next_u64_via_u32(self) |
170 | 0 | } |
171 | | |
172 | | #[inline] |
173 | 0 | fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Infallible> { |
174 | 0 | utils::fill_bytes_via_next_word(dest, || self.try_next_u32()); |
175 | 0 | Ok(()) |
176 | 0 | } |
177 | | } |