Debian Codegraph @

debian/rust-vendor/rand_core/tests/utils.rs

raw
1 //! Tests for the `utils` module items
2 use rand_core::{Infallible, Rng, TryRng, utils};
3
4 struct DummyRng(u32);
5
6 impl TryRng for DummyRng {
7 type Error = Infallible;
8 fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
9 self.0 = self.0.wrapping_mul(3);
10 Ok(self.0)
11 }
12
13 fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
14 utils::next_u64_via_u32(self)
15 }
16
17 fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
18 utils::fill_bytes_via_next_word(dst, || self.try_next_u32())
19 }
20 }
21
22 #[test]
23 fn test_next_u64_via_u32() {
24 let mut rng = DummyRng(0xF973_F2EC);
25
26 assert_eq!(rng.next_u64(), 0xC513_8A4C_EC5B_D8C4);
27 assert_eq!(rng.next_u64(), 0xEDAF_DCAC_4F3A_9EE4);
28 assert_eq!(rng.next_u64(), 0x5B2E_C20C_C90F_9604);
29 }
30
31 #[test]
32 fn test_fill_bytes_via_next_word() {
33 let mut rng = DummyRng(0xF973_F2EC);
34
35 let mut buf = [0u8; 8];
36
37 let dst = &mut buf[..3];
38 rng.fill_bytes(dst);
39 assert_eq!(dst, &[196, 216, 91]);
40
41 let dst = &mut buf[..5];
42 rng.fill_bytes(dst);
43 assert_eq!(dst, &[76, 138, 19, 197, 228]);
44
45 let dst = &mut buf[..];
46 rng.fill_bytes(dst);
47 assert_eq!(dst, &[172, 220, 175, 237, 4, 150, 15, 201]);
48 }
49
50 #[test]
51 fn test_read_words() {
52 use utils::read_words;
53
54 let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
55
56 let buf: [u32; 4] = read_words(&bytes);
57 assert_eq!(buf[0], 0x0403_0201);
58 assert_eq!(buf[3], 0x100F_0E0D);
59
60 let buf: [u32; 3] = read_words(&bytes[1..13]); // unaligned
61 assert_eq!(buf[0], 0x0504_0302);
62 assert_eq!(buf[2], 0x0D0C_0B0A);
63
64 let buf: [u64; 2] = read_words(&bytes);
65 assert_eq!(buf[0], 0x0807_0605_0403_0201);
66 assert_eq!(buf[1], 0x100F_0E0D_0C0B_0A09);
67
68 let buf: [u64; 1] = read_words(&bytes[7..15]); // unaligned
69 assert_eq!(buf[0], 0x0F0E_0D0C_0B0A_0908);
70 }