]> git.proxmox.com Git - rustc.git/blob - vendor/rand-0.7.3/src/rngs/mock.rs
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / vendor / rand-0.7.3 / src / 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
11 use rand_core::{impls, Error, RngCore};
12
13 /// A simple implementation of `RngCore` for testing purposes.
14 ///
15 /// This generates an arithmetic sequence (i.e. adds a constant each step)
16 /// over a `u64` number, using wrapping arithmetic. If the increment is 0
17 /// the generator yields a constant.
18 ///
19 /// ```
20 /// use rand::Rng;
21 /// use rand::rngs::mock::StepRng;
22 ///
23 /// let mut my_rng = StepRng::new(2, 1);
24 /// let sample: [u64; 3] = my_rng.gen();
25 /// assert_eq!(sample, [2, 3, 4]);
26 /// ```
27 #[derive(Debug, Clone)]
28 pub struct StepRng {
29 v: u64,
30 a: u64,
31 }
32
33 impl StepRng {
34 /// Create a `StepRng`, yielding an arithmetic sequence starting with
35 /// `initial` and incremented by `increment` each time.
36 pub fn new(initial: u64, increment: u64) -> Self {
37 StepRng {
38 v: initial,
39 a: increment,
40 }
41 }
42 }
43
44 impl RngCore for StepRng {
45 #[inline]
46 fn next_u32(&mut self) -> u32 {
47 self.next_u64() as u32
48 }
49
50 #[inline]
51 fn next_u64(&mut self) -> u64 {
52 let result = self.v;
53 self.v = self.v.wrapping_add(self.a);
54 result
55 }
56
57 #[inline]
58 fn fill_bytes(&mut self, dest: &mut [u8]) {
59 impls::fill_bytes_via_next(self, dest);
60 }
61
62 #[inline]
63 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
64 self.fill_bytes(dest);
65 Ok(())
66 }
67 }