1const MAX_BITS: u32 = i64::BITS - 1;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub struct Modulus {
30 bits: u32,
31}
32
33impl Modulus {
34 #[must_use]
36 pub const fn new<const BITS: u32>() -> Self {
37 const {
38 assert!(
39 BITS >= 1 && BITS <= MAX_BITS,
40 "a modulus is 1..=63 bits wide"
41 );
42 }
43 Self { bits: BITS }
44 }
45
46 #[must_use]
48 pub const fn try_new(bits: u32) -> Option<Self> {
49 if bits >= 1 && bits <= MAX_BITS {
50 Some(Self { bits })
51 } else {
52 None
53 }
54 }
55
56 #[must_use]
58 pub const fn bits(self) -> u32 {
59 self.bits
60 }
61
62 #[must_use]
64 pub const fn modulus(self) -> u64 {
65 1u64 << self.bits
66 }
67
68 #[must_use]
70 pub const fn mask(self) -> u64 {
71 self.modulus() - 1
72 }
73
74 #[must_use]
77 pub const fn half(self) -> u64 {
78 self.modulus() >> 1
79 }
80
81 #[must_use]
83 pub const fn reduce(self, value: u64) -> u64 {
84 value & self.mask()
85 }
86
87 #[must_use]
89 pub const fn add(self, a: u64, n: u64) -> u64 {
90 self.reduce(a.wrapping_add(n))
91 }
92
93 #[must_use]
95 pub const fn add_signed(self, a: u64, delta: i64) -> u64 {
96 self.reduce(a.wrapping_add_signed(delta))
97 }
98
99 #[must_use]
101 pub const fn forward(self, from: u64, to: u64) -> u64 {
102 self.reduce(to.wrapping_sub(from))
103 }
104
105 #[must_use]
110 pub const fn signed(self, from: u64, to: u64) -> i64 {
111 let forward = self.forward(from, to);
112 if forward <= self.half() {
113 forward.cast_signed()
114 } else {
115 (forward.wrapping_sub(self.modulus())).cast_signed()
116 }
117 }
118
119 #[must_use]
122 pub const fn is_tie(self, a: u64, b: u64) -> bool {
123 self.forward(b, a) == self.half()
124 }
125
126 #[must_use]
128 pub const fn lt(self, a: u64, b: u64) -> bool {
129 self.signed(b, a) < 0
130 }
131
132 #[must_use]
134 pub const fn leq(self, a: u64, b: u64) -> bool {
135 self.signed(b, a) <= 0
136 }
137
138 #[must_use]
140 pub const fn gt(self, a: u64, b: u64) -> bool {
141 self.signed(b, a) > 0 && !self.is_tie(a, b)
142 }
143
144 #[must_use]
146 pub const fn geq(self, a: u64, b: u64) -> bool {
147 self.signed(b, a) >= 0 && !self.is_tie(a, b)
148 }
149
150 #[must_use]
153 pub const fn in_closed_range(self, value: u64, first: u64, last: u64) -> bool {
154 let span = self.signed(first, last);
155 if span < 0 {
156 return false;
157 }
158 let offset = self.signed(first, value);
159 offset >= 0 && offset <= span
160 }
161
162 #[must_use]
166 pub const fn extend_near(self, reference: i64, raw: u64) -> Option<i64> {
167 reference.checked_add(self.signed(reference.cast_unsigned(), raw))
168 }
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub struct Unwrapper {
175 modulus: Modulus,
176 last: Option<(u64, i128)>,
177}
178
179impl Unwrapper {
180 #[must_use]
183 pub const fn new(modulus: Modulus) -> Self {
184 Self {
185 modulus,
186 last: None,
187 }
188 }
189
190 #[must_use]
193 pub const fn seeded(modulus: Modulus, origin: i128) -> Self {
194 Self {
195 modulus,
196 last: Some((origin.cast_unsigned() as u64, origin)),
197 }
198 }
199
200 #[must_use]
202 pub const fn modulus(&self) -> Modulus {
203 self.modulus
204 }
205
206 #[must_use]
209 pub const fn position(&self) -> Option<i128> {
210 match self.last {
211 Some((_, position)) => Some(position),
212 None => None,
213 }
214 }
215
216 pub fn unwrap(&mut self, raw: u64) -> i128 {
220 let position = match self.last {
221 Some((previous_raw, previous)) => {
222 previous + i128::from(self.modulus.signed(previous_raw, raw))
223 }
224 None => i128::from(raw),
225 };
226 self.last = Some((raw, position));
227 position
228 }
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 const S16: Modulus = Modulus::new::<16>();
236 const S32: Modulus = Modulus::new::<32>();
237 const S33: Modulus = Modulus::new::<33>();
238
239 #[test]
240 fn widths_outside_the_range_are_refused_at_runtime() {
241 assert_eq!(Modulus::try_new(0), None);
242 assert_eq!(Modulus::try_new(64), None);
243 assert_eq!(Modulus::try_new(1), Some(Modulus::new::<1>()));
244 assert_eq!(Modulus::try_new(63), Some(Modulus::new::<63>()));
245 assert_eq!(Modulus::new::<63>().modulus(), 1 << 63);
246 assert_eq!(S16.mask(), 0xFFFF);
247 assert_eq!(S16.half(), 0x8000);
248 }
249
250 #[test]
251 fn forward_and_signed_cross_the_wrap() {
252 assert_eq!(S16.forward(0xFFFF, 0), 1);
253 assert_eq!(S16.forward(0, 0xFFFF), 0xFFFF);
254 assert_eq!(S16.signed(0xFFFF, 0), 1);
255 assert_eq!(S16.signed(0, 0xFFFF), -1);
256 assert_eq!(S16.signed(5, 5), 0);
257 assert_eq!(S32.signed(u64::from(u32::MAX) - 9, 5), 15);
258 assert_eq!(S33.signed(5, (1 << 33) - 10), -15);
259 }
260
261 #[test]
262 fn the_half_space_tie_resolves_forward_and_orders_nothing() {
263 assert_eq!(S16.signed(0, 0x8000), 0x8000);
264 assert_eq!(S16.signed(0x8000, 0), 0x8000);
265 assert!(S16.is_tie(0, 0x8000));
266 for (a, b) in [(0, 0x8000), (0x8000, 0)] {
267 assert!(!S16.lt(a, b));
268 assert!(!S16.gt(a, b));
269 assert!(!S16.leq(a, b));
270 assert!(!S16.geq(a, b));
271 }
272 assert_eq!(S16.signed(0, 0x8001), -0x7FFF);
273 assert_eq!(S16.signed(0, 0x7FFF), 0x7FFF);
274 }
275
276 #[test]
277 fn ordering_predicates_follow_the_shorter_direction() {
278 assert!(S16.lt(0xFFFF, 0));
279 assert!(S16.gt(0, 0xFFFF));
280 assert!(S16.leq(3, 3));
281 assert!(S16.geq(3, 3));
282 assert!(S16.in_closed_range(0, 0xFFFE, 2));
283 assert!(!S16.in_closed_range(3, 0xFFFE, 2));
284 assert!(!S16.in_closed_range(0, 2, 0xFFFE));
285 }
286
287 #[test]
288 fn inputs_are_reduced_and_addition_wraps() {
289 assert_eq!(S16.reduce(0x1_0005), 5);
290 assert_eq!(S16.add(0xFFFF, 1), 0);
291 assert_eq!(S16.add(u64::MAX, 1), 0);
292 assert_eq!(S16.add_signed(5, -10), 0xFFFB);
293 assert_eq!(S16.add_signed(0, i64::MIN), 0);
294 assert_eq!(S33.add_signed(5, -10), (1 << 33) - 5);
295 assert_eq!(S16.forward(0x1_0000, 0x2_0001), 1);
296 }
297
298 #[test]
299 fn extend_near_picks_the_closest_congruent_value() {
300 assert_eq!(S32.extend_near(0x1_0000_0005, 3), Some(0x1_0000_0003));
301 assert_eq!(S32.extend_near(0x1_FFFF_FFFE, 2), Some(0x2_0000_0002));
302 assert_eq!(S32.extend_near(2, u64::from(u32::MAX)), Some(-1));
303 assert_eq!(
304 S32.extend_near(i64::MAX, u64::from(u32::MAX)),
305 Some(i64::MAX)
306 );
307 assert_eq!(S32.extend_near(i64::MAX, 0), None);
308 assert_eq!(S32.extend_near(i64::MIN, u64::from(u32::MAX)), None);
309 }
310
311 #[test]
312 fn the_unwrapper_carries_a_counter_across_its_wraps_in_both_directions() {
313 let mut u = Unwrapper::new(S16);
314 assert_eq!(u.unwrap(0xFFFE), 0xFFFE);
315 assert_eq!(u.unwrap(1), 0x1_0001);
316 assert_eq!(u.unwrap(0xFFFF), 0xFFFF);
317 assert_eq!(u.unwrap(0x7FFF), 0x1_7FFF);
318 assert_eq!(Unwrapper::new(S16).position(), None);
319 assert_eq!(u.position(), Some(0x1_7FFF));
320 let mut seeded = Unwrapper::seeded(S33, (1 << 33) + 10);
321 assert_eq!(seeded.position(), Some((1 << 33) + 10));
322 assert_eq!(seeded.unwrap(5), (1 << 33) + 5);
323 assert_eq!(seeded.modulus(), S33);
324 let mut back = Unwrapper::new(S33);
325 assert_eq!(back.unwrap(2), 2);
326 assert_eq!(back.unwrap((1 << 33) - 3), -3);
327 }
328
329 #[test]
330 fn the_32_bit_unwrap_table_holds_for_every_edge() {
331 const CASES: [(&[u32], &[i128]); 6] = [
332 (
333 &[0xFFFF_F000, 0xFFFF_FBB8, 0x0000_0770],
334 &[0xFFFF_F000, 0xFFFF_FBB8, 0x1_0000_0770],
335 ),
336 (&[0x9000_0000], &[0x9000_0000]),
337 (&[0x0001_0000, 0x0000_F448], &[0x1_0000, 0xF448]),
338 (&[0, 0x8000_0000], &[0, 0x8000_0000]),
339 (&[1000, 0xFFFF_F000], &[1000, -4096]),
340 (&[0xFFFF_F000, 1000], &[0xFFFF_F000, 0x1_0000_03E8]),
341 ];
342 for (raws, expected) in CASES {
343 let mut unwrapper = Unwrapper::new(S32);
344 let got: alloc::vec::Vec<i128> = raws
345 .iter()
346 .map(|&raw| unwrapper.unwrap(u64::from(raw)))
347 .collect();
348 assert_eq!(got, expected, "{raws:x?}");
349 }
350 }
351}