rand/rngs/mock.rs
1// Copyright 2018 Developers of the Rand project.
2//
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.
8
9//! Mock random number generator
10
11use rand_core::{impls, RngCore};
12
13#[cfg(feature = "serde")]
14use serde::{Deserialize, Serialize};
15
16/// A mock generator yielding very predictable output
17///
18/// This generates an arithmetic sequence (i.e. adds a constant each step)
19/// over a `u64` number, using wrapping arithmetic. If the increment is 0
20/// the generator yields a constant.
21///
22/// Other integer types (64-bit and smaller) are produced via cast from `u64`.
23///
24/// Other types are produced via their implementation of [`Rng`](crate::Rng) or
25/// [`Distribution`](crate::distr::Distribution).
26/// Output values may not be intuitive and may change in future releases but
27/// are considered
28/// [portable](https://rust-random.github.io/book/portability.html).
29/// (`bool` output is true when bit `1u64 << 31` is set.)
30///
31/// # Example
32///
33/// ```
34/// use rand::Rng;
35/// use rand::rngs::mock::StepRng;
36///
37/// let mut my_rng = StepRng::new(2, 1);
38/// let sample: [u64; 3] = my_rng.random();
39/// assert_eq!(sample, [2, 3, 4]);
40/// ```
41#[derive(Debug, Clone, PartialEq, Eq)]
42#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
43pub struct StepRng {
44 v: u64,
45 a: u64,
46}
47
48impl StepRng {
49 /// Create a `StepRng`, yielding an arithmetic sequence starting with
50 /// `initial` and incremented by `increment` each time.
51 pub fn new(initial: u64, increment: u64) -> Self {
52 StepRng {
53 v: initial,
54 a: increment,
55 }
56 }
57}
58
59impl RngCore for StepRng {
60 #[inline]
61 fn next_u32(&mut self) -> u32 {
62 self.next_u64() as u32
63 }
64
65 #[inline]
66 fn next_u64(&mut self) -> u64 {
67 let res = self.v;
68 self.v = self.v.wrapping_add(self.a);
69 res
70 }
71
72 #[inline]
73 fn fill_bytes(&mut self, dst: &mut [u8]) {
74 impls::fill_bytes_via_next(self, dst)
75 }
76}
77
78#[cfg(test)]
79mod tests {
80 #[cfg(any(feature = "alloc", feature = "serde"))]
81 use super::StepRng;
82
83 #[test]
84 #[cfg(feature = "serde")]
85 fn test_serialization_step_rng() {
86 let some_rng = StepRng::new(42, 7);
87 let de_some_rng: StepRng =
88 bincode::deserialize(&bincode::serialize(&some_rng).unwrap()).unwrap();
89 assert_eq!(some_rng.v, de_some_rng.v);
90 assert_eq!(some_rng.a, de_some_rng.a);
91 }
92
93 #[test]
94 #[cfg(feature = "alloc")]
95 fn test_bool() {
96 use crate::{distr::StandardUniform, Rng};
97
98 // If this result ever changes, update doc on StepRng!
99 let rng = StepRng::new(0, 1 << 31);
100 let result: alloc::vec::Vec<bool> = rng.sample_iter(StandardUniform).take(6).collect();
101 assert_eq!(&result, &[false, true, false, true, false, true]);
102 }
103}