Debian Codegraph @

.cargo/vendor/rand/src/rngs/mock.rs

raw
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
11 #![allow(deprecated)]
12
13 use rand_core::{impls, RngCore};
14
15 #[cfg(feature = "serde")]
16 use serde::{Deserialize, Serialize};
17
18 /// A mock generator yielding very predictable output
19 ///
20 /// This generates an arithmetic sequence (i.e. adds a constant each step)
21 /// over a `u64` number, using wrapping arithmetic. If the increment is 0
22 /// the generator yields a constant.
23 ///
24 /// Other integer types (64-bit and smaller) are produced via cast from `u64`.
25 ///
26 /// Other types are produced via their implementation of [`Rng`](crate::Rng) or
27 /// [`Distribution`](crate::distr::Distribution).
28 /// Output values may not be intuitive and may change in future releases but
29 /// are considered
30 /// [portable](https://rust-random.github.io/book/portability.html).
31 /// (`bool` output is true when bit `1u64 << 31` is set.)
32 ///
33 /// # Example
34 ///
35 /// ```
36 /// # #![allow(deprecated)]
37 /// use rand::Rng;
38 /// use rand::rngs::mock::StepRng;
39 ///
40 /// let mut my_rng = StepRng::new(2, 1);
41 /// let sample: [u64; 3] = my_rng.random();
42 /// assert_eq!(sample, [2, 3, 4]);
43 /// ```
44 #[derive(Debug, Clone, PartialEq, Eq)]
45 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
46 #[deprecated(since = "0.9.2", note = "Deprecated without replacement")]
47 pub struct StepRng {
48 v: u64,
49 a: u64,
50 }
51
52 impl StepRng {
53 /// Create a `StepRng`, yielding an arithmetic sequence starting with
54 /// `initial` and incremented by `increment` each time.
55 pub fn new(initial: u64, increment: u64) -> Self {
56 StepRng {
57 v: initial,
58 a: increment,
59 }
60 }
61 }
62
63 impl RngCore for StepRng {
64 #[inline]
65 fn next_u32(&mut self) -> u32 {
66 self.next_u64() as u32
67 }
68
69 #[inline]
70 fn next_u64(&mut self) -> u64 {
71 let res = self.v;
72 self.v = self.v.wrapping_add(self.a);
73 res
74 }
75
76 #[inline]
77 fn fill_bytes(&mut self, dst: &mut [u8]) {
78 impls::fill_bytes_via_next(self, dst)
79 }
80 }