| 1 |
//! Tests for the `block` module items |
| 2 |
use rand_core::{ |
| 3 |
SeedableRng, |
| 4 |
block::{BlockRng, Generator}, |
| 5 |
}; |
| 6 |
|
| 7 |
const RESULTS_LEN: usize = 16; |
| 8 |
|
| 9 |
#[derive(Debug, Clone)] |
| 10 |
struct DummyRng { |
| 11 |
counter: u32, |
| 12 |
} |
| 13 |
|
| 14 |
impl Generator for DummyRng { |
| 15 |
type Output = [u32; RESULTS_LEN]; |
| 16 |
|
| 17 |
fn generate(&mut self, output: &mut Self::Output) { |
| 18 |
for item in output { |
| 19 |
*item = self.counter; |
| 20 |
self.counter = self.counter.wrapping_add(3511615421); |
| 21 |
} |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
impl SeedableRng for DummyRng { |
| 26 |
type Seed = [u8; 4]; |
| 27 |
|
| 28 |
fn from_seed(seed: Self::Seed) -> Self { |
| 29 |
DummyRng { |
| 30 |
counter: u32::from_le_bytes(seed), |
| 31 |
} |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
#[test] |
| 36 |
fn blockrng_next_u32_vs_next_u64() { |
| 37 |
let mut rng1 = BlockRng::new(DummyRng::from_seed([1, 2, 3, 4])); |
| 38 |
let mut rng2 = rng1.clone(); |
| 39 |
let mut rng3 = rng1.clone(); |
| 40 |
|
| 41 |
let mut a = [0; 16]; |
| 42 |
a[..4].copy_from_slice(&rng1.next_word().to_le_bytes()); |
| 43 |
a[4..12].copy_from_slice(&rng1.next_u64_from_u32().to_le_bytes()); |
| 44 |
a[12..].copy_from_slice(&rng1.next_word().to_le_bytes()); |
| 45 |
|
| 46 |
let mut b = [0; 16]; |
| 47 |
b[..4].copy_from_slice(&rng2.next_word().to_le_bytes()); |
| 48 |
b[4..8].copy_from_slice(&rng2.next_word().to_le_bytes()); |
| 49 |
b[8..].copy_from_slice(&rng2.next_u64_from_u32().to_le_bytes()); |
| 50 |
assert_eq!(a, b); |
| 51 |
|
| 52 |
let mut c = [0; 16]; |
| 53 |
c[..8].copy_from_slice(&rng3.next_u64_from_u32().to_le_bytes()); |
| 54 |
c[8..12].copy_from_slice(&rng3.next_word().to_le_bytes()); |
| 55 |
c[12..].copy_from_slice(&rng3.next_word().to_le_bytes()); |
| 56 |
assert_eq!(a, c); |
| 57 |
} |
| 58 |
|
| 59 |
#[test] |
| 60 |
fn blockrng_next_u64() { |
| 61 |
let mut rng = BlockRng::new(DummyRng::from_seed([1, 2, 3, 4])); |
| 62 |
let result_size = RESULTS_LEN; |
| 63 |
for _i in 0..result_size / 2 - 1 { |
| 64 |
rng.next_u64_from_u32(); |
| 65 |
} |
| 66 |
rng.next_word(); |
| 67 |
|
| 68 |
let _ = rng.next_u64_from_u32(); |
| 69 |
assert_eq!(rng.word_offset(), 1); |
| 70 |
} |