Coverage Report

Created: 2026-12-01 07:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/rand_pcg-0.10.3/src/pcg128.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
// This is the default multiplier used by PCG for 128-bit state.
14
const MULTIPLIER: u128 = 0x2360_ED05_1FC6_5DA4_4385_DF64_9FCC_F645;
15
16
use core::fmt;
17
use rand_core::{Infallible, SeedableRng, TryRng, utils};
18
#[cfg(feature = "serde")]
19
use serde::{Deserialize, Serialize};
20
21
/// A PCG random number generator (XSL RR 128/64 (LCG) variant).
22
///
23
/// Permuted Congruential Generator with 128-bit state, internal Linear
24
/// Congruential Generator, and 64-bit output via "xorshift low (bits),
25
/// random rotation" output function.
26
///
27
/// This is a 128-bit LCG with explicitly chosen stream with the PCG-XSL-RR
28
/// output function. This combination is the standard `pcg64`.
29
///
30
/// Despite the name, this implementation uses 32 bytes (256 bit) space
31
/// comprising 128 bits of state and 128 bits stream selector. These are both
32
/// set by `SeedableRng`, using a 256-bit seed.
33
///
34
/// Note that two generators with different stream parameters may be closely
35
/// correlated.
36
#[derive(Clone, PartialEq, Eq)]
37
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
38
pub struct Lcg128Xsl64 {
39
    state: u128,
40
    increment: u128,
41
}
42
43
/// [`Lcg128Xsl64`] is also officially known as `pcg64`.
44
pub type Pcg64 = Lcg128Xsl64;
45
46
impl Lcg128Xsl64 {
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_64()` `delta`
58
    /// number of times.
59
    ///
60
    /// # Warning
61
    ///
62
    /// Do not advance by a large power of two, such as `1 << 127` (half of the
63
    /// period), to split a single stream into several. The state is an LCG
64
    /// modulo `2^128`, whose lowest `e` bits repeat every `2^e` steps, so
65
    /// advancing by `2^e` leaves them unchanged. After `advance(1 << 127)`, the
66
    /// two states differ only in their top bit at every step, and each output
67
    /// is the other with its 32-bit halves swapped and one bit flipped.
68
    #[inline]
69
0
    pub fn advance(&mut self, delta: u128) {
70
0
        let mut acc_mult: u128 = 1;
71
0
        let mut acc_plus: u128 = 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 = 0xa02bdbf7bb3c0a7ac28fa16a64abf96`
100
0
    pub fn new(state: u128, stream: u128) -> Self {
101
        // The increment must be odd, hence we discard one bit:
102
0
        let increment = (stream << 1) | 1;
103
0
        Lcg128Xsl64::from_state_incr(state, increment)
104
0
    }
105
106
    #[inline]
107
0
    fn from_state_incr(state: u128, increment: u128) -> Self {
108
0
        let mut pcg = Lcg128Xsl64 { state, increment };
109
        // Move away from initial value:
110
0
        pcg.state = pcg.state.wrapping_add(pcg.increment);
111
0
        pcg.step();
112
0
        pcg
113
0
    }
114
115
    #[inline]
116
0
    fn step(&mut self) {
117
        // prepare the LCG for the next round
118
0
        self.state = self
119
0
            .state
120
0
            .wrapping_mul(MULTIPLIER)
121
0
            .wrapping_add(self.increment);
122
0
    }
123
}
124
125
crate::macros::impl_state_stream!(Lcg128Xsl64, u128);
126
127
// Custom Debug implementation that does not expose the internal state
128
impl fmt::Debug for Lcg128Xsl64 {
129
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
130
0
        write!(f, "Lcg128Xsl64 {{}}")
131
0
    }
132
}
133
134
impl SeedableRng for Lcg128Xsl64 {
135
    type Seed = [u8; 32];
136
137
    /// We use a single 255-bit seed to initialise the state and select a stream.
138
    /// One `seed` bit (lowest bit of `seed[8]`) is ignored.
139
0
    fn from_seed(seed: Self::Seed) -> Self {
140
0
        let seed_u64: [u64; 4] = utils::read_words(&seed);
141
0
        let state = u128::from(seed_u64[0]) | (u128::from(seed_u64[1]) << 64);
142
0
        let incr = u128::from(seed_u64[2]) | (u128::from(seed_u64[3]) << 64);
143
144
        // The increment must be odd, hence we discard one bit:
145
0
        Lcg128Xsl64::from_state_incr(state, incr | 1)
146
0
    }
147
}
148
149
impl TryRng for Lcg128Xsl64 {
150
    type Error = Infallible;
151
152
    #[inline]
153
0
    fn try_next_u32(&mut self) -> Result<u32, Infallible> {
154
0
        self.try_next_u64().map(|result| result as u32)
155
0
    }
156
157
    #[inline]
158
0
    fn try_next_u64(&mut self) -> Result<u64, Infallible> {
159
0
        self.step();
160
0
        Ok(output_xsl_rr(self.state))
161
0
    }
162
163
    #[inline]
164
0
    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Infallible> {
165
0
        utils::fill_bytes_via_next_word(dest, || self.try_next_u64())
166
0
    }
167
}
168
169
/// A PCG random number generator (XSL 128/64 (MCG) variant).
170
///
171
/// Permuted Congruential Generator with 128-bit state, internal Multiplicative
172
/// Congruential Generator, and 64-bit output via "xorshift low (bits),
173
/// random rotation" output function.
174
///
175
/// This is a 128-bit MCG with the PCG-XSL-RR output function, also known as
176
/// `pcg64_fast`.
177
/// Note that compared to the standard `pcg64` (128-bit LCG with PCG-XSL-RR
178
/// output function), this RNG is faster, also has a long cycle, and still has
179
/// good performance on statistical tests.
180
#[derive(Clone, PartialEq, Eq)]
181
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
182
pub struct Mcg128Xsl64 {
183
    state: u128,
184
}
185
186
/// A friendly name for [`Mcg128Xsl64`] (also known as `pcg64_fast`).
187
pub type Pcg64Mcg = Mcg128Xsl64;
188
189
impl Mcg128Xsl64 {
190
    /// Multi-step advance functions (jump-ahead, jump-back)
191
    ///
192
    /// The method used here is based on Brown, "Random Number Generation
193
    /// with Arbitrary Stride,", Transactions of the American Nuclear
194
    /// Society (Nov. 1994).  The algorithm is very similar to fast
195
    /// exponentiation.
196
    ///
197
    /// Even though delta is an unsigned integer, we can pass a
198
    /// signed integer to go backwards, it just goes "the long way round".
199
    ///
200
    /// Using this function is equivalent to calling `next_64()` `delta`
201
    /// number of times.
202
    ///
203
    /// # Warning
204
    ///
205
    /// Do not advance by a large power of two, such as `1 << 125` (half of the
206
    /// period), to split a single stream into several. The state is an MCG
207
    /// modulo `2^128`, whose lowest `e` bits repeat every `2^e` steps, so
208
    /// advancing by `2^e` leaves them unchanged. After `advance(1 << 125)`, the
209
    /// two states differ only in their top bit at every step, and each output
210
    /// is the other with its 32-bit halves swapped and one bit flipped.
211
    #[inline]
212
0
    pub fn advance(&mut self, delta: u128) {
213
0
        let mut acc_mult: u128 = 1;
214
0
        let mut acc_plus: u128 = 0;
215
0
        let mut cur_mult = MULTIPLIER;
216
0
        let mut cur_plus: u128 = 0;
217
0
        let mut mdelta = delta;
218
219
0
        while mdelta > 0 {
220
0
            if (mdelta & 1) != 0 {
221
0
                acc_mult = acc_mult.wrapping_mul(cur_mult);
222
0
                acc_plus = acc_plus.wrapping_mul(cur_mult).wrapping_add(cur_plus);
223
0
            }
224
0
            cur_plus = cur_mult.wrapping_add(1).wrapping_mul(cur_plus);
225
0
            cur_mult = cur_mult.wrapping_mul(cur_mult);
226
0
            mdelta /= 2;
227
        }
228
0
        self.state = acc_mult.wrapping_mul(self.state).wrapping_add(acc_plus);
229
0
    }
230
231
    /// Construct an instance compatible with PCG seed.
232
    ///
233
    /// Note that PCG specifies a default value for the parameter:
234
    ///
235
    /// - `state = 0xcafef00dd15ea5e5`
236
0
    pub fn new(state: u128) -> Self {
237
        // Force low bit to 1, as in C version (C++ uses `state | 3` instead).
238
0
        Mcg128Xsl64 { state: state | 1 }
239
0
    }
240
241
    /// Current state of the generator
242
    ///
243
    /// Will always be odd.
244
0
    pub fn state(&self) -> u128 {
245
0
        self.state
246
0
    }
247
}
248
249
// Custom Debug implementation that does not expose the internal state
250
impl fmt::Debug for Mcg128Xsl64 {
251
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
252
0
        write!(f, "Mcg128Xsl64 {{}}")
253
0
    }
254
}
255
256
/// We use a single 126-bit seed to initialise the state and select a stream.
257
/// Two `seed` bits (lowest order of last byte) are ignored.
258
impl SeedableRng for Mcg128Xsl64 {
259
    type Seed = [u8; 16];
260
261
0
    fn from_seed(seed: Self::Seed) -> Self {
262
        // Read as if a little-endian u128 value:
263
0
        let seed_u64: [u64; 2] = utils::read_words(&seed);
264
0
        let state = u128::from(seed_u64[0]) | (u128::from(seed_u64[1]) << 64);
265
0
        Mcg128Xsl64::new(state)
266
0
    }
267
}
268
269
impl TryRng for Mcg128Xsl64 {
270
    type Error = Infallible;
271
272
    #[inline]
273
0
    fn try_next_u32(&mut self) -> Result<u32, Infallible> {
274
0
        self.try_next_u64().map(|result| result as u32)
275
0
    }
276
277
    #[inline]
278
0
    fn try_next_u64(&mut self) -> Result<u64, Infallible> {
279
0
        self.state = self.state.wrapping_mul(MULTIPLIER);
280
0
        Ok(output_xsl_rr(self.state))
281
0
    }
282
283
    #[inline]
284
0
    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Infallible> {
285
0
        utils::fill_bytes_via_next_word(dest, || self.try_next_u64())
286
0
    }
287
}
288
289
#[inline(always)]
290
0
fn output_xsl_rr(state: u128) -> u64 {
291
    // Output function XSL RR ("xorshift low (bits), random rotation")
292
    // Constants are for 128-bit state, 64-bit output
293
    const XSHIFT: u32 = 64; // (128 - 64 + 64) / 2
294
    const ROTATE: u32 = 122; // 128 - 6
295
296
0
    let rot = (state >> ROTATE) as u32;
297
0
    let xsl = ((state >> XSHIFT) as u64) ^ (state as u64);
298
0
    xsl.rotate_right(rot)
299
0
}