1#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
5pub struct SmVersion(pub u32);
6
7impl SmVersion {
8 pub const SM_75: Self = Self(75);
9 pub const SM_80: Self = Self(80);
10 pub const SM_86: Self = Self(86);
11 pub const SM_89: Self = Self(89);
12 pub const SM_90: Self = Self(90);
13 pub const SM_100: Self = Self(100);
14
15 pub fn value(self) -> u32 {
17 self.0
18 }
19}
20
21#[derive(Debug, Clone)]
26pub struct LcgRng {
27 state: u64,
28}
29
30impl LcgRng {
31 const MUL: u64 = 6_364_136_223_846_793_005;
32 const ADD: u64 = 1_442_695_040_888_963_407;
33
34 pub fn new(seed: u64) -> Self {
36 Self {
37 state: seed.wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(1),
38 }
39 }
40
41 pub fn next_u64(&mut self) -> u64 {
43 self.state = self.state.wrapping_mul(Self::MUL).wrapping_add(Self::ADD);
44 self.state
45 }
46
47 pub fn next_f64(&mut self) -> f64 {
49 (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
50 }
51
52 pub fn next_bool(&mut self) -> bool {
54 (self.next_u64() >> 32) & 1 == 1
55 }
56
57 pub fn next_normal(&mut self) -> f64 {
59 let u1 = self.next_f64().max(1e-300);
60 let u2 = self.next_f64();
61 (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()
62 }
63
64 pub fn next_range(&mut self, lo: f64, hi: f64) -> f64 {
66 lo + (hi - lo) * self.next_f64()
67 }
68
69 pub fn sample_categorical(&mut self, probs: &[f64]) -> usize {
73 let u = self.next_f64();
74 let mut acc = 0.0;
75 for (i, &p) in probs.iter().enumerate() {
76 acc += p;
77 if u <= acc {
78 return i;
79 }
80 }
81 if probs.is_empty() { 0 } else { probs.len() - 1 }
82 }
83
84 pub fn next_usize(&mut self, n: usize) -> usize {
86 if n == 0 {
87 0
88 } else {
89 (self.next_u64() as usize) % n
90 }
91 }
92}
93
94#[derive(Debug, Clone)]
96pub struct SeqHandle {
97 pub sm: SmVersion,
98 pub rng: LcgRng,
99}
100
101impl SeqHandle {
102 pub fn new(sm: SmVersion, seed: u64) -> Self {
104 Self {
105 sm,
106 rng: LcgRng::new(seed),
107 }
108 }
109
110 pub fn from_sm_code(sm_code: u32, seed: u64) -> Self {
112 Self::new(SmVersion(sm_code), seed)
113 }
114}