1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use crate::rand::{Rng, SeedableRng};
use core::fmt::{self, Debug, Display, Formatter};
#[cfg(feature = "zeroize")]
use zeroize::Zeroize;
#[cfg_attr(feature = "zeroize", derive(Zeroize))]
#[cfg_attr(feature = "zeroize", zeroize(drop))]
pub struct WyRand {
seed: u64,
}
impl WyRand {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub const fn new_seed(seed: u64) -> Self {
Self { seed }
}
}
impl Default for WyRand {
fn default() -> Self {
let mut entropy: [u8; core::mem::size_of::<u64>()] = Default::default();
crate::entropy::system(&mut entropy);
Self {
seed: u64::from_ne_bytes(entropy),
}
}
}
impl Rng<8> for WyRand {
fn rand(&mut self) -> [u8; 8] {
self.seed = self.seed.wrapping_add(0xa0761d6478bd642f);
let t: u128 = (self.seed as u128).wrapping_mul((self.seed ^ 0xe7037ed1a0b428db) as u128);
let ret = (t.wrapping_shr(64) ^ t) as u64;
ret.to_ne_bytes()
}
}
impl Clone for WyRand {
fn clone(&self) -> Self {
Self { seed: self.seed }
}
}
impl Display for WyRand {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "WyRand ({:p})", self)
}
}
impl Debug for WyRand {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("WyRand")
.field("seed", &format_args!("0x{:x}", self.seed))
.finish()
}
}
impl SeedableRng<8, 8> for WyRand {
fn reseed(&mut self, seed: [u8; 8]) {
self.seed = u64::from_ne_bytes(seed);
}
}