]> git.proxmox.com Git - rustc.git/blame - vendor/rand-0.7.3/src/rngs/mock.rs
Merge tag 'debian/1.52.1+dfsg1-1_exp2' into proxmox/buster
[rustc.git] / vendor / rand-0.7.3 / src / rngs / mock.rs
CommitLineData
0731742a 1// Copyright 2018 Developers of the Rand project.
b7449926
XL
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
dfeec247 11use rand_core::{impls, Error, RngCore};
b7449926
XL
12
13/// A simple implementation of `RngCore` for testing purposes.
dfeec247 14///
b7449926
XL
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.
dfeec247 18///
b7449926
XL
19/// ```
20/// use rand::Rng;
21/// use rand::rngs::mock::StepRng;
dfeec247 22///
b7449926
XL
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)]
28pub struct StepRng {
29 v: u64,
30 a: u64,
31}
32
33impl 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 {
dfeec247
XL
37 StepRng {
38 v: initial,
39 a: increment,
40 }
b7449926
XL
41 }
42}
43
44impl RngCore for StepRng {
416331ca 45 #[inline]
b7449926
XL
46 fn next_u32(&mut self) -> u32 {
47 self.next_u64() as u32
48 }
49
416331ca 50 #[inline]
b7449926
XL
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
416331ca 57 #[inline]
b7449926
XL
58 fn fill_bytes(&mut self, dest: &mut [u8]) {
59 impls::fill_bytes_via_next(self, dest);
60 }
61
416331ca 62 #[inline]
b7449926 63 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
dfeec247
XL
64 self.fill_bytes(dest);
65 Ok(())
b7449926
XL
66 }
67}