Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_math/
wide.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! The one sanctioned wide-arithmetic type for guest code.
3//!
4//! The R3000 has `mult` and `multu`, which write a 64-bit product to the
5//! HI:LO pair in one instruction. A 64-bit add or subtract is a few 32-bit
6//! instructions with a carry, a compare is two word compares, and a shift is
7//! a few word shifts. None of that calls a compiler helper. The expensive
8//! half of 64-bit arithmetic is division and remainder (`__divdi3`,
9//! `__udivdi3`, `__moddi3`, `__umoddi3`, with `u64_div_rem` behind them),
10//! and the 128-bit and soft-float routines; the project's guest symbol gate
11//! (`tools/guest_symbol_gate.sh`) fails a link that contains any of them.
12//!
13//! Game and engine code that has a quantity this wide (a dot product of two
14//! world-sized vectors, a squared distance, the cross product of two screen
15//! edges, a CORDIC accumulator) holds a [`Wide`] or a [`WideU`] and never
16//! names `i64` or `u64`, so a per-project source guard can fail the build on
17//! every `i64`/`u64` token outside this file. This file is where the rule is
18//! enforced: its 64-bit tokens carry `psx-numeric-allow` markers.
19//!
20//! # What exists, and what deliberately does not
21//!
22//! Only operations that compile to native R3000 instructions exist:
23//!
24//! - full products of two 32-bit words ([`Wide::mul`], [`WideU::mul`]), and
25//!   multiply-accumulate forms of them;
26//! - 64-bit add, subtract, negate, absolute value, compare;
27//! - shifts, with the count taken modulo 64;
28//! - the low 64 bits of a 64-by-64 product ([`Wide::mul_w`]) and of a
29//!   64-by-32 product ([`Wide::times`]), which LLVM expands to a few
30//!   `multu`/`mul` and adds;
31//! - extraction to 32 bits in three explicit flavours: truncating
32//!   (`low`, `shr_i32`), checked (`to_i32`, `to_u32`) and saturating
33//!   (`saturate_i32`, `saturate_u32`);
34//! - a square root ([`Wide::isqrt`], [`WideU::isqrt`]), which is
35//!   [`crate::int32::isqrt_u64`] and uses `multu` only.
36//!
37//! This module has **no division and no remainder**, and no way to ask for
38//! one. Dividing a wide value is [`crate::wide_div`]: exact, in 32-bit
39//! instructions only, with explicit rounding and clamping. To divide a product
40//! of two words by a word use [`crate::int32::mul_div_i32`] /
41//! [`crate::int32::mul_div_u32`] (a native `multu` then `divu`), which is
42//! cheaper than building the `Wide` first.
43//!
44//! Arithmetic wraps like the release-mode `i64` / `u64` it stands in for.
45//! Every function is `#[inline(always)]` (or `const`), so a call site
46//! compiles to the same instructions as the bare 64-bit expression.
47//!
48//! The representation is private. Outside tests the only 64-bit tokens in
49//! this module are the handful in the private `widen*` / `raw` helpers, each
50//! with a marker.
51
52use core::cmp::Ordering;
53use core::fmt;
54use core::ops::{Add, Neg, Shl, Shr, Sub};
55
56/// Sign-extend a word: one `sra` for the high word.
57#[inline(always)]
58// psx-numeric-allow-next-line: the sanctioned wide word; sign extension is one sra, no helper
59const fn widen(a: i32) -> i64 {
60    // psx-numeric-allow-next-line: sign extension, no helper
61    a as i64
62}
63
64/// Zero-extend a word: free.
65#[inline(always)]
66// psx-numeric-allow-next-line: the sanctioned wide word; zero extension is free, no helper
67const fn widen_unsigned(a: u32) -> u64 {
68    // psx-numeric-allow-next-line: zero extension, no helper
69    a as u64
70}
71
72/// The same 64 bits read as signed: free.
73#[inline(always)]
74// psx-numeric-allow-next-line: the sanctioned wide word; a reinterpretation, no instructions
75const fn signed(a: u64) -> i64 {
76    // psx-numeric-allow-next-line: reinterpretation, no instructions
77    a as i64
78}
79
80/// The same 64 bits read as unsigned: free.
81#[inline(always)]
82// psx-numeric-allow-next-line: the sanctioned wide word; a reinterpretation, no instructions
83const fn unsigned(a: i64) -> u64 {
84    // psx-numeric-allow-next-line: reinterpretation, no instructions
85    a as u64
86}
87
88/// A signed 64-bit value, built from native 32-bit multiplies and adds.
89///
90/// See the [module documentation](self) for the operations it offers and the
91/// ones it leaves out on purpose.
92#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
93pub struct Wide(
94    // psx-numeric-allow-next-line: the one signed wide word; every method is a native HI:LO operation
95    i64,
96);
97
98impl Wide {
99    /// Zero.
100    pub const ZERO: Wide = Wide(0);
101    /// One.
102    pub const ONE: Wide = Wide(1);
103    /// The largest value, `2^63 - 1`.
104    // psx-numeric-allow-next-line: the largest wide value
105    pub const MAX: Wide = Wide(i64::MAX);
106    /// The smallest value, `-2^63`.
107    // psx-numeric-allow-next-line: the smallest wide value
108    pub const MIN: Wide = Wide(i64::MIN);
109
110    /// A 32-bit value widened (sign-extending).
111    #[inline(always)]
112    pub const fn of(a: i32) -> Wide {
113        Wide(widen(a))
114    }
115
116    /// A 32-bit unsigned value widened (zero-extending).
117    #[inline(always)]
118    pub const fn of_u(a: u32) -> Wide {
119        Wide(signed(widen_unsigned(a)))
120    }
121
122    /// The value with signed high word `hi` and low word `lo`, the pair a
123    /// `mult` leaves in HI:LO.
124    #[inline(always)]
125    pub const fn from_parts(hi: i32, lo: u32) -> Wide {
126        Wide(widen(hi).wrapping_shl(32) | signed(widen_unsigned(lo)))
127    }
128
129    /// The full signed product of two words: one `mult`.
130    #[inline(always)]
131    pub const fn mul(a: i32, b: i32) -> Wide {
132        Wide(widen(a).wrapping_mul(widen(b)))
133    }
134
135    /// `self + a * b`: one `mult` and a 64-bit add.
136    #[inline(always)]
137    pub const fn mul_add(self, a: i32, b: i32) -> Wide {
138        Wide(self.0.wrapping_add(widen(a).wrapping_mul(widen(b))))
139    }
140
141    /// `self - a * b`: one `mult` and a 64-bit subtract.
142    #[inline(always)]
143    pub const fn mul_sub(self, a: i32, b: i32) -> Wide {
144        Wide(self.0.wrapping_sub(widen(a).wrapping_mul(widen(b))))
145    }
146
147    /// `self + o`, usable in `const fn`.
148    #[inline(always)]
149    pub const fn add_w(self, o: Wide) -> Wide {
150        Wide(self.0.wrapping_add(o.0))
151    }
152
153    /// `self - o`, usable in `const fn`.
154    #[inline(always)]
155    pub const fn sub_w(self, o: Wide) -> Wide {
156        Wide(self.0.wrapping_sub(o.0))
157    }
158
159    /// `self * o`, the low 64 bits of the product (three multiplies).
160    #[inline(always)]
161    pub const fn mul_w(self, o: Wide) -> Wide {
162        Wide(self.0.wrapping_mul(o.0))
163    }
164
165    /// `self * k`, the low 64 bits of the product.
166    #[inline(always)]
167    pub const fn times(self, k: i32) -> Wide {
168        Wide(self.0.wrapping_mul(widen(k)))
169    }
170
171    /// `self + k` for a 32-bit `k`.
172    #[inline(always)]
173    pub const fn plus(self, k: i32) -> Wide {
174        Wide(self.0.wrapping_add(widen(k)))
175    }
176
177    /// `-self`, wrapping at [`Wide::MIN`].
178    #[inline(always)]
179    pub const fn negate(self) -> Wide {
180        Wide(self.0.wrapping_neg())
181    }
182
183    /// `|self|`, wrapping at [`Wide::MIN`].
184    #[inline(always)]
185    pub const fn abs(self) -> Wide {
186        Wide(self.0.wrapping_abs())
187    }
188
189    /// `|self|` as an unsigned value: exact for every input, `Wide::MIN` included
190    /// (`2^63`).
191    #[inline(always)]
192    pub const fn unsigned_abs(self) -> WideU {
193        WideU(self.0.unsigned_abs())
194    }
195
196    /// The same 64 bits read as unsigned, like `as u64`: a negative value becomes
197    /// `2^64 - |self|`.
198    #[inline(always)]
199    pub const fn cast_unsigned(self) -> WideU {
200        WideU(unsigned(self.0))
201    }
202
203    /// The dot product of two 3-vectors, three `mult`s and two 64-bit adds.
204    /// With `a == b` it is the squared length.
205    #[inline(always)]
206    pub const fn dot3(a: [i32; 3], b: [i32; 3]) -> Wide {
207        Wide(
208            widen(a[0])
209                .wrapping_mul(widen(b[0]))
210                .wrapping_add(widen(a[1]).wrapping_mul(widen(b[1])))
211                .wrapping_add(widen(a[2]).wrapping_mul(widen(b[2]))),
212        )
213    }
214
215    /// Arithmetic shift left; the count is taken modulo 64.
216    #[inline(always)]
217    pub const fn shl_by(self, n: u32) -> Wide {
218        Wide(self.0.wrapping_shl(n))
219    }
220
221    /// Arithmetic shift right (the sign is kept); the count is taken modulo 64.
222    #[inline(always)]
223    pub const fn sar(self, n: u32) -> Wide {
224        Wide(self.0.wrapping_shr(n))
225    }
226
227    /// Logical shift right of the 64-bit pattern (zeros come in at the top);
228    /// the count is taken modulo 64.
229    #[inline(always)]
230    pub const fn lshr(self, n: u32) -> Wide {
231        Wide(signed(unsigned(self.0).wrapping_shr(n)))
232    }
233
234    /// The low 32 bits as `i32` (truncating, like `as i32`).
235    #[inline(always)]
236    pub const fn low(self) -> i32 {
237        self.0 as i32
238    }
239
240    /// The low 32 bits as `u32` (the LO register).
241    #[inline(always)]
242    pub const fn low_u32(self) -> u32 {
243        self.0 as u32
244    }
245
246    /// The high 32 bits as `i32` (the HI register).
247    #[inline(always)]
248    pub const fn high(self) -> i32 {
249        self.0.wrapping_shr(32) as i32
250    }
251
252    /// `self >> n` (arithmetic, count modulo 64) truncated to its low 32
253    /// bits: the fixed-point "multiply, then drop the fraction" step.
254    #[inline(always)]
255    pub const fn shr_i32(self, n: u32) -> i32 {
256        self.0.wrapping_shr(n) as i32
257    }
258
259    /// The value clamped into `i32`.
260    #[inline(always)]
261    pub const fn saturate_i32(self) -> i32 {
262        if self.0 > widen(i32::MAX) {
263            i32::MAX
264        } else if self.0 < widen(i32::MIN) {
265            i32::MIN
266        } else {
267            self.0 as i32
268        }
269    }
270
271    /// The value as `i32` if it fits.
272    #[inline(always)]
273    pub const fn to_i32(self) -> Option<i32> {
274        if self.0 >= widen(i32::MIN) && self.0 <= widen(i32::MAX) {
275            Some(self.0 as i32)
276        } else {
277            None
278        }
279    }
280
281    /// The value clamped into `u32` (a negative value gives 0).
282    #[inline(always)]
283    pub const fn saturate_u32(self) -> u32 {
284        if self.0 < 0 {
285            0
286        } else if self.0 > signed(widen_unsigned(u32::MAX)) {
287            u32::MAX
288        } else {
289            self.0 as u32
290        }
291    }
292
293    /// The value as `u32` if it fits.
294    #[inline(always)]
295    pub const fn to_u32(self) -> Option<u32> {
296        if self.0 >= 0 && self.0 <= signed(widen_unsigned(u32::MAX)) {
297            Some(self.0 as u32)
298        } else {
299            None
300        }
301    }
302
303    /// Is the value below zero?
304    #[inline(always)]
305    pub const fn is_negative(self) -> bool {
306        self.0 < 0
307    }
308
309    /// Is the value above zero?
310    #[inline(always)]
311    pub const fn is_positive(self) -> bool {
312        self.0 > 0
313    }
314
315    /// Is the value zero?
316    #[inline(always)]
317    pub const fn is_zero(self) -> bool {
318        self.0 == 0
319    }
320
321    /// Compare with a 32-bit value.
322    #[inline(always)]
323    pub const fn cmp_i32(self, k: i32) -> Ordering {
324        let k = widen(k);
325        if self.0 < k {
326            Ordering::Less
327        } else if self.0 > k {
328            Ordering::Greater
329        } else {
330            Ordering::Equal
331        }
332    }
333
334    /// `floor(sqrt(self))`, 0 for a negative value ([`crate::int32::isqrt_u64`]).
335    #[inline]
336    pub const fn isqrt(self) -> u32 {
337        if self.0 <= 0 {
338            0
339        } else {
340            crate::int32::isqrt_u64(unsigned(self.0))
341        }
342    }
343}
344
345impl Add for Wide {
346    type Output = Wide;
347    #[inline(always)]
348    fn add(self, o: Wide) -> Wide {
349        self.add_w(o)
350    }
351}
352
353impl Sub for Wide {
354    type Output = Wide;
355    #[inline(always)]
356    fn sub(self, o: Wide) -> Wide {
357        self.sub_w(o)
358    }
359}
360
361impl Neg for Wide {
362    type Output = Wide;
363    #[inline(always)]
364    fn neg(self) -> Wide {
365        self.negate()
366    }
367}
368
369/// Arithmetic shift right; the count is taken modulo 64.
370impl Shr<u32> for Wide {
371    type Output = Wide;
372    #[inline(always)]
373    fn shr(self, n: u32) -> Wide {
374        self.sar(n)
375    }
376}
377
378/// Shift left; the count is taken modulo 64.
379impl Shl<u32> for Wide {
380    type Output = Wide;
381    #[inline(always)]
382    fn shl(self, n: u32) -> Wide {
383        self.shl_by(n)
384    }
385}
386
387/// Prints the two words, `Wide(HI:LO)` in hex. (Decimal formatting of 64 bits
388/// would pull in a software divide.)
389impl fmt::Debug for Wide {
390    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391        write!(f, "Wide({:08x}:{:08x})", self.high() as u32, self.low_u32())
392    }
393}
394
395/// An unsigned 64-bit value: a `u32 * u32` product needs all 64 bits.
396///
397/// Same rules as [`Wide`]: native operations only; division is in [`crate::wide_div`].
398#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
399pub struct WideU(
400    // psx-numeric-allow-next-line: the one unsigned wide word; every method is a native HI:LO operation
401    u64,
402);
403
404impl WideU {
405    /// Zero.
406    pub const ZERO: WideU = WideU(0);
407    /// The largest value, `2^64 - 1`.
408    // psx-numeric-allow-next-line: the largest unsigned wide value
409    pub const MAX: WideU = WideU(u64::MAX);
410
411    /// A 32-bit value widened.
412    #[inline(always)]
413    pub const fn of(a: u32) -> WideU {
414        WideU(widen_unsigned(a))
415    }
416
417    /// The value with high word `hi` and low word `lo`, the pair a `multu`
418    /// leaves in HI:LO.
419    #[inline(always)]
420    pub const fn from_parts(hi: u32, lo: u32) -> WideU {
421        WideU((widen_unsigned(hi).wrapping_shl(32)) | widen_unsigned(lo))
422    }
423
424    /// The full unsigned product of two words: one `multu`.
425    #[inline(always)]
426    pub const fn mul(a: u32, b: u32) -> WideU {
427        WideU(widen_unsigned(a).wrapping_mul(widen_unsigned(b)))
428    }
429
430    /// `self + a * b`: one `multu` and a 64-bit add (wrapping).
431    #[inline(always)]
432    pub const fn mul_add(self, a: u32, b: u32) -> WideU {
433        WideU(
434            self.0
435                .wrapping_add(widen_unsigned(a).wrapping_mul(widen_unsigned(b))),
436        )
437    }
438
439    /// `self + o`, wrapping.
440    #[inline(always)]
441    pub const fn add(self, o: WideU) -> WideU {
442        WideU(self.0.wrapping_add(o.0))
443    }
444
445    /// `self - o`, wrapping.
446    #[inline(always)]
447    pub const fn sub(self, o: WideU) -> WideU {
448        WideU(self.0.wrapping_sub(o.0))
449    }
450
451    /// `self + o`, stopping at [`WideU::MAX`].
452    #[inline(always)]
453    pub const fn saturating_add(self, o: WideU) -> WideU {
454        WideU(self.0.saturating_add(o.0))
455    }
456
457    /// `self * k`, the low 64 bits of the product.
458    #[inline(always)]
459    pub const fn times(self, k: u32) -> WideU {
460        WideU(self.0.wrapping_mul(widen_unsigned(k)))
461    }
462
463    /// Shift left; the count is taken modulo 64.
464    #[inline(always)]
465    pub const fn shl_by(self, n: u32) -> WideU {
466        WideU(self.0.wrapping_shl(n))
467    }
468
469    /// Shift right (zeros come in at the top); the count is taken modulo 64.
470    #[inline(always)]
471    pub const fn shr_by(self, n: u32) -> WideU {
472        WideU(self.0.wrapping_shr(n))
473    }
474
475    /// The low 32 bits (the LO register).
476    #[inline(always)]
477    pub const fn low(self) -> u32 {
478        self.0 as u32
479    }
480
481    /// The high 32 bits (the HI register).
482    #[inline(always)]
483    pub const fn high(self) -> u32 {
484        self.0.wrapping_shr(32) as u32
485    }
486
487    /// `self >> n` (count modulo 64) truncated to its low 32 bits.
488    #[inline(always)]
489    pub const fn shr_u32(self, n: u32) -> u32 {
490        self.0.wrapping_shr(n) as u32
491    }
492
493    /// The value clamped into `u32`.
494    #[inline(always)]
495    pub const fn saturate_u32(self) -> u32 {
496        if self.0 > widen_unsigned(u32::MAX) {
497            u32::MAX
498        } else {
499            self.0 as u32
500        }
501    }
502
503    /// The value as `u32` if it fits.
504    #[inline(always)]
505    pub const fn to_u32(self) -> Option<u32> {
506        if self.0 <= widen_unsigned(u32::MAX) {
507            Some(self.0 as u32)
508        } else {
509            None
510        }
511    }
512
513    /// The same 64 bits read as signed, like `as i64`: a value from `2^63` up becomes
514    /// negative.
515    #[inline(always)]
516    pub const fn cast_signed(self) -> Wide {
517        Wide(signed(self.0))
518    }
519
520    /// Is the value zero?
521    #[inline(always)]
522    pub const fn is_zero(self) -> bool {
523        self.0 == 0
524    }
525
526    /// `floor(sqrt(self))` ([`crate::int32::isqrt_u64`]).
527    #[inline]
528    pub const fn isqrt(self) -> u32 {
529        crate::int32::isqrt_u64(self.0)
530    }
531}
532
533impl Add for WideU {
534    type Output = WideU;
535    #[inline(always)]
536    fn add(self, o: WideU) -> WideU {
537        WideU::add(self, o)
538    }
539}
540
541impl Sub for WideU {
542    type Output = WideU;
543    #[inline(always)]
544    fn sub(self, o: WideU) -> WideU {
545        WideU::sub(self, o)
546    }
547}
548
549/// Shift right (logical); the count is taken modulo 64.
550impl Shr<u32> for WideU {
551    type Output = WideU;
552    #[inline(always)]
553    fn shr(self, n: u32) -> WideU {
554        self.shr_by(n)
555    }
556}
557
558/// Shift left; the count is taken modulo 64.
559impl Shl<u32> for WideU {
560    type Output = WideU;
561    #[inline(always)]
562    fn shl(self, n: u32) -> WideU {
563        self.shl_by(n)
564    }
565}
566
567/// Prints the two words, `WideU(HI:LO)` in hex.
568impl fmt::Debug for WideU {
569    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570        write!(f, "WideU({:08x}:{:08x})", self.high(), self.low())
571    }
572}
573
574/// A set of up to 64 flags in two words: what a `u64` bit mask was used for.
575/// It does no arithmetic, so it needs no wide integer at all.
576#[derive(Clone, Copy, PartialEq, Eq, Debug)]
577pub struct Mask64([u32; 2]);
578
579impl Mask64 {
580    /// No bit set.
581    pub const EMPTY: Mask64 = Mask64([0; 2]);
582
583    /// Set `bit` (0..64).
584    #[inline(always)]
585    pub fn set(&mut self, bit: usize) {
586        self.0[bit >> 5] |= 1 << (bit & 31);
587    }
588
589    /// Clear `bit` (0..64).
590    #[inline(always)]
591    pub fn clear(&mut self, bit: usize) {
592        self.0[bit >> 5] &= !(1 << (bit & 31));
593    }
594
595    /// Set or clear `bit` (0..64).
596    #[inline(always)]
597    pub fn assign(&mut self, bit: usize, value: bool) {
598        if value {
599            self.set(bit);
600        } else {
601            self.clear(bit);
602        }
603    }
604
605    /// Is `bit` set? A bit past 63 is not.
606    #[inline(always)]
607    pub fn test(&self, bit: usize) -> bool {
608        bit < 64 && self.0[bit >> 5] >> (bit & 31) & 1 != 0
609    }
610
611    /// The set with bits `low` (0..32) and `high` (32..64) as given: the two words of
612    /// a stored or transmitted mask.
613    #[inline(always)]
614    pub const fn from_words(low: u32, high: u32) -> Mask64 {
615        Mask64([low, high])
616    }
617
618    /// Bits 0..32.
619    #[inline(always)]
620    pub const fn low(self) -> u32 {
621        self.0[0]
622    }
623
624    /// Bits 32..64.
625    #[inline(always)]
626    pub const fn high(self) -> u32 {
627        self.0[1]
628    }
629
630    /// The set holding only `bit` (empty for a bit past 63).
631    #[inline(always)]
632    pub const fn bit(bit: usize) -> Mask64 {
633        if bit >= 64 {
634            Mask64::EMPTY
635        } else if bit < 32 {
636            Mask64([1 << bit, 0])
637        } else {
638            Mask64([0, 1 << (bit - 32)])
639        }
640    }
641
642    /// The set of the lowest `count` bits (all 64 for a count of 64 or more).
643    #[inline(always)]
644    pub const fn first(count: usize) -> Mask64 {
645        if count >= 64 {
646            Mask64([u32::MAX; 2])
647        } else if count >= 32 {
648            Mask64([u32::MAX, (1u32 << (count - 32)) - 1])
649        } else {
650            Mask64([(1u32 << count) - 1, 0])
651        }
652    }
653
654    /// Is no bit set?
655    #[inline(always)]
656    pub const fn is_empty(self) -> bool {
657        self.0[0] | self.0[1] == 0
658    }
659
660    /// The bits set in either.
661    #[inline(always)]
662    pub const fn or(self, o: Mask64) -> Mask64 {
663        Mask64([self.0[0] | o.0[0], self.0[1] | o.0[1]])
664    }
665
666    /// The bits set in both.
667    #[inline(always)]
668    pub const fn and(self, o: Mask64) -> Mask64 {
669        Mask64([self.0[0] & o.0[0], self.0[1] & o.0[1]])
670    }
671
672    /// The bits set in `self` and not in `o`.
673    #[inline(always)]
674    pub const fn and_not(self, o: Mask64) -> Mask64 {
675        Mask64([self.0[0] & !o.0[0], self.0[1] & !o.0[1]])
676    }
677}
678
679#[cfg(test)]
680mod tests {
681    extern crate std;
682    use super::*;
683    use std::vec;
684    use std::vec::Vec;
685
686    /// xorshift64*, the same stream on every run.
687    struct Rng(u64);
688    impl Rng {
689        fn next(&mut self) -> u64 {
690            let mut x = self.0;
691            x ^= x >> 12;
692            x ^= x << 25;
693            x ^= x >> 27;
694            self.0 = x;
695            x.wrapping_mul(0x2545_f491_4f6c_dd1d)
696        }
697        fn i32(&mut self) -> i32 {
698            // A mix of magnitudes: full range, small, and Q12-sized values.
699            let v = self.next();
700            match v & 3 {
701                0 => (v >> 8) as i32,
702                1 => ((v >> 8) as i32) >> 16,
703                2 => ((v >> 8) as i32) >> 8,
704                _ => ((v >> 8) as i32) >> 24,
705            }
706        }
707        fn wide(&mut self) -> i128 {
708            let v = self.next();
709            let w = self.next() as i64 as i128;
710            match v & 3 {
711                0 => w,
712                1 => w >> 20,
713                2 => w >> 40,
714                _ => (w >> 50) * 4096,
715            }
716        }
717        fn shift(&mut self) -> u32 {
718            (self.next() >> 20) as u32 % 96
719        }
720    }
721
722    const I32_EDGES: [i32; 17] = [
723        i32::MIN,
724        i32::MIN + 1,
725        -65_537,
726        -65_536,
727        -4097,
728        -4096,
729        -1,
730        0,
731        1,
732        4095,
733        4096,
734        65_535,
735        65_536,
736        65_537,
737        i32::MAX - 1,
738        i32::MAX,
739        0x5555_5555,
740    ];
741    const U32_EDGES: [u32; 12] = [
742        0,
743        1,
744        2,
745        4095,
746        4096,
747        65_535,
748        65_536,
749        0x7fff_ffff,
750        0x8000_0000,
751        0x8000_0001,
752        u32::MAX - 1,
753        u32::MAX,
754    ];
755    const I64_MIN: i128 = -(1 << 63);
756    const I64_MAX: i128 = (1 << 63) - 1;
757
758    /// Every signed value the oracle can hold, as the public words see it.
759    fn val(w: Wide) -> i128 {
760        ((w.high() as i128) << 32) | w.low_u32() as i128
761    }
762    fn valu(w: WideU) -> u128 {
763        ((w.high() as u128) << 32) | w.low() as u128
764    }
765    /// An oracle value wrapped to 64 bits, as a `Wide`.
766    fn wrap(v: i128) -> Wide {
767        Wide::from_parts((v >> 32) as i32, v as u32)
768    }
769    fn wrap_i64(v: i128) -> i128 {
770        v as i64 as i128
771    }
772    fn wrap_u64(v: u128) -> u128 {
773        v as u64 as u128
774    }
775
776    /// Wide values that exercise every carry and sign boundary.
777    fn wide_edges() -> Vec<i128> {
778        let mut v = vec![
779            0,
780            1,
781            -1,
782            2,
783            -2,
784            0x7fff_ffff,
785            0x8000_0000,
786            0xffff_ffff,
787            0x1_0000_0000,
788            0x1_0000_0001,
789            -0x7fff_ffff,
790            -0x8000_0000,
791            -0x8000_0001,
792            -0xffff_ffff,
793            -0x1_0000_0000,
794            -0x1_0000_0001,
795            I64_MAX,
796            I64_MAX - 1,
797            I64_MIN,
798            I64_MIN + 1,
799            1 << 40,
800            -(1 << 40),
801            0x1234_5678_9abc_def0,
802            -0x1234_5678_9abc_def0,
803        ];
804        for a in I32_EDGES {
805            for b in I32_EDGES {
806                v.push(a as i128 * b as i128);
807            }
808        }
809        v
810    }
811
812    fn isqrt_oracle(v: u128) -> u32 {
813        let (mut lo, mut hi) = (0u128, 1u128 << 32);
814        while hi - lo > 1 {
815            let mid = (lo + hi) / 2;
816            if mid * mid <= v {
817                lo = mid;
818            } else {
819                hi = mid;
820            }
821        }
822        lo as u32
823    }
824
825    #[test]
826    fn construction_and_extraction_round_trip() {
827        for v in wide_edges() {
828            let w = wrap(v);
829            assert_eq!(val(w), wrap_i64(v), "{v}");
830            assert_eq!(w.low(), v as i32);
831            assert_eq!(w.low_u32(), v as u32);
832            assert_eq!(w.high(), (wrap_i64(v) >> 32) as i32);
833            assert_eq!(Wide::from_parts(w.high(), w.low_u32()), w);
834        }
835        for a in I32_EDGES {
836            assert_eq!(val(Wide::of(a)), a as i128);
837        }
838        for a in U32_EDGES {
839            assert_eq!(val(Wide::of_u(a)), a as i128);
840            assert_eq!(valu(WideU::of(a)), a as u128);
841        }
842        assert_eq!(val(Wide::ZERO), 0);
843        assert_eq!(val(Wide::ONE), 1);
844        assert_eq!(val(Wide::MAX), I64_MAX);
845        assert_eq!(val(Wide::MIN), I64_MIN);
846        assert_eq!(Wide::default(), Wide::ZERO);
847        assert_eq!(valu(WideU::ZERO), 0);
848        assert_eq!(valu(WideU::MAX), u64::MAX as u128);
849    }
850
851    #[test]
852    fn signed_products_match_the_oracle() {
853        for a in I32_EDGES {
854            for b in I32_EDGES {
855                let p = a as i128 * b as i128;
856                assert_eq!(val(Wide::mul(a, b)), p, "{a} * {b}");
857                for acc in [0i128, 1, -1, I64_MAX, I64_MIN, 0x1_0000_0000, -0x8000_0000] {
858                    let w = wrap(acc);
859                    assert_eq!(val(w.mul_add(a, b)), wrap_i64(acc + p), "{acc} + {a} * {b}");
860                    assert_eq!(val(w.mul_sub(a, b)), wrap_i64(acc - p), "{acc} - {a} * {b}");
861                }
862            }
863        }
864    }
865
866    #[test]
867    fn unsigned_products_match_the_oracle() {
868        for a in U32_EDGES {
869            for b in U32_EDGES {
870                let p = a as u128 * b as u128;
871                assert_eq!(valu(WideU::mul(a, b)), p, "{a} * {b}");
872                for acc in [
873                    0u128,
874                    1,
875                    u64::MAX as u128,
876                    0x8000_0000_0000_0000,
877                    0x1_0000_0000,
878                ] {
879                    let w = WideU::from_parts((acc >> 32) as u32, acc as u32);
880                    assert_eq!(
881                        valu(w.mul_add(a, b)),
882                        wrap_u64(acc + p),
883                        "{acc} + {a} * {b}"
884                    );
885                }
886            }
887        }
888    }
889
890    /// The product of two `u32` needs all 64 unsigned bits (up to
891    /// `2^64 - 2^33 + 1`, past `i64::MAX`). A signed holder overflows there:
892    /// the private copy `mul_u` in the games did, and failed in a debug build.
893    /// `WideU::mul` has to be exact over the whole range, with the checks on.
894    #[test]
895    fn unsigned_product_is_exact_over_the_whole_u32_range() {
896        assert_eq!(valu(WideU::mul(u32::MAX, u32::MAX)), 0xffff_fffe_0000_0001);
897        assert!(valu(WideU::mul(u32::MAX, u32::MAX)) > I64_MAX as u128);
898        assert_eq!(WideU::mul(u32::MAX, u32::MAX).high(), u32::MAX - 1);
899        assert_eq!(WideU::mul(u32::MAX, u32::MAX).low(), 1);
900        // The smallest pair whose product passes i64::MAX, and its neighbours.
901        let (a, b) = (3_037_000_500u32, 3_037_000_500u32);
902        assert!(valu(WideU::mul(a, b)) > I64_MAX as u128);
903        assert!(valu(WideU::mul(a - 1, b - 1)) <= I64_MAX as u128);
904        let mut rng = Rng(0x00c0_ffee_1234_5678);
905        for _ in 0..100_000 {
906            let (a, b) = (
907                rng.next() as u32 | 0x8000_0000,
908                rng.next() as u32 | 0x8000_0000,
909            );
910            assert_eq!(valu(WideU::mul(a, b)), a as u128 * b as u128, "{a} * {b}");
911        }
912    }
913
914    #[test]
915    fn add_sub_neg_abs_match_the_oracle() {
916        let edges = wide_edges();
917        for &a in &edges {
918            let (wa, a64) = (wrap(a), wrap_i64(a));
919            assert_eq!(val(-wa), wrap_i64(-a64));
920            assert_eq!(val(wa.negate()), wrap_i64(-a64));
921            assert_eq!(val(wa.abs()), wrap_i64(a64.abs()));
922            for &b in &edges {
923                let (wb, b64) = (wrap(b), wrap_i64(b));
924                assert_eq!(val(wa + wb), wrap_i64(a64 + b64), "{a} + {b}");
925                assert_eq!(val(wa - wb), wrap_i64(a64 - b64), "{a} - {b}");
926                assert_eq!(val(wa.add_w(wb)), wrap_i64(a64 + b64));
927                assert_eq!(val(wa.sub_w(wb)), wrap_i64(a64 - b64));
928                assert_eq!(
929                    val(wa.mul_w(wb)),
930                    wrap_i64(a64.wrapping_mul(b64)),
931                    "{a} * {b}"
932                );
933            }
934        }
935    }
936
937    #[test]
938    fn unsigned_views_match_the_oracle() {
939        for &a in &wide_edges() {
940            let (wa, a64) = (wrap(a), wrap_i64(a));
941            assert_eq!(valu(wa.unsigned_abs()), a64.unsigned_abs(), "|{a}|");
942            assert_eq!(
943                valu(wa.cast_unsigned()),
944                wrap_u64(a64 as u128),
945                "{a} as u64"
946            );
947            assert_eq!(val(wa.cast_unsigned().cast_signed()), a64);
948        }
949        assert_eq!(valu(Wide::MIN.unsigned_abs()), 1 << 63);
950    }
951
952    #[test]
953    fn small_operand_forms_match_the_oracle() {
954        for &a in &wide_edges() {
955            let (wa, a64) = (wrap(a), wrap_i64(a));
956            for k in I32_EDGES {
957                assert_eq!(
958                    val(wa.times(k)),
959                    wrap_i64(a64.wrapping_mul(k as i128)),
960                    "{a} * {k}"
961                );
962                assert_eq!(val(wa.plus(k)), wrap_i64(a64 + k as i128), "{a} + {k}");
963                assert_eq!(wa.cmp_i32(k), a64.cmp(&(k as i128)), "{a} vs {k}");
964            }
965        }
966    }
967
968    #[test]
969    fn dot_products_match_the_oracle() {
970        let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
971        for _ in 0..20_000 {
972            let a = [rng.i32(), rng.i32(), rng.i32()];
973            let b = [rng.i32(), rng.i32(), rng.i32()];
974            let want: i128 = (0..3).map(|i| a[i] as i128 * b[i] as i128).sum();
975            assert_eq!(val(Wide::dot3(a, b)), wrap_i64(want), "{a:?} . {b:?}");
976        }
977        let m = [i32::MIN; 3];
978        assert_eq!(val(Wide::dot3(m, m)), wrap_i64(3 * (1i128 << 62)));
979        assert_eq!(Wide::dot3([3, 4, 12], [3, 4, 12]).isqrt(), 13);
980    }
981
982    #[test]
983    fn shifts_match_the_oracle_for_every_count() {
984        for &a in &wide_edges() {
985            let (wa, a64) = (wrap(a), wrap_i64(a));
986            for n in 0..64u32 {
987                assert_eq!(val(wa >> n), a64 >> n, "{a} >> {n}");
988                assert_eq!(val(wa.sar(n)), a64 >> n);
989                assert_eq!(val(wa << n), wrap_i64(a64 << n), "{a} << {n}");
990                assert_eq!(val(wa.shl_by(n)), wrap_i64(a64 << n));
991                assert_eq!(
992                    val(wa.lshr(n)),
993                    wrap_i64(((a64 as u128 & u64::MAX as u128) >> n) as i128)
994                );
995                assert_eq!(wa.shr_i32(n), (a64 >> n) as i32);
996            }
997            // The count is taken modulo 64.
998            for n in [64u32, 65, 95, 127, 128] {
999                assert_eq!(val(wa >> n), a64 >> (n & 63));
1000                assert_eq!(val(wa << n), wrap_i64(a64 << (n & 63)));
1001                assert_eq!(val(wa.lshr(n)), val(wa.lshr(n & 63)));
1002            }
1003        }
1004        for &a in &wide_edges() {
1005            let u = wrap_u64(a as u128);
1006            let w = WideU::from_parts((u >> 32) as u32, u as u32);
1007            for n in 0..64u32 {
1008                assert_eq!(valu(w >> n), u >> n, "{u} >> {n}");
1009                assert_eq!(valu(w << n), wrap_u64(u << n), "{u} << {n}");
1010                assert_eq!(w.shr_u32(n), (u >> n) as u32);
1011            }
1012            assert_eq!(valu(w >> 64), u);
1013            assert_eq!(valu(w << 70), wrap_u64(u << 6));
1014        }
1015    }
1016
1017    #[test]
1018    fn extraction_variants_agree_with_the_oracle() {
1019        for &a in &wide_edges() {
1020            let (w, a64) = (wrap(a), wrap_i64(a));
1021            assert_eq!(
1022                w.saturate_i32() as i128,
1023                a64.clamp(i32::MIN as i128, i32::MAX as i128)
1024            );
1025            assert_eq!(
1026                w.to_i32(),
1027                (a64 >= i32::MIN as i128 && a64 <= i32::MAX as i128).then_some(a64 as i32)
1028            );
1029            assert_eq!(w.saturate_u32() as i128, a64.clamp(0, u32::MAX as i128));
1030            assert_eq!(
1031                w.to_u32(),
1032                (a64 >= 0 && a64 <= u32::MAX as i128).then_some(a64 as u32)
1033            );
1034            let u = wrap_u64(a as u128);
1035            let wu = WideU::from_parts((u >> 32) as u32, u as u32);
1036            assert_eq!(wu.saturate_u32() as u128, u.min(u32::MAX as u128));
1037            assert_eq!(wu.to_u32(), (u <= u32::MAX as u128).then_some(u as u32));
1038        }
1039    }
1040
1041    #[test]
1042    fn comparisons_and_predicates_match_the_oracle() {
1043        let edges = wide_edges();
1044        for &a in &edges {
1045            let (wa, a64) = (wrap(a), wrap_i64(a));
1046            assert_eq!(wa.is_negative(), a64 < 0);
1047            assert_eq!(wa.is_positive(), a64 > 0);
1048            assert_eq!(wa.is_zero(), a64 == 0);
1049            for &b in &edges {
1050                let (wb, b64) = (wrap(b), wrap_i64(b));
1051                assert_eq!(wa.cmp(&wb), a64.cmp(&b64), "{a} vs {b}");
1052                assert_eq!(wa == wb, a64 == b64);
1053                assert_eq!(val(wa.max(wb)), a64.max(b64));
1054                assert_eq!(val(wa.min(wb)), a64.min(b64));
1055            }
1056        }
1057        let unsigned: Vec<u128> = edges.iter().map(|&v| wrap_u64(v as u128)).collect();
1058        for &a in &unsigned {
1059            let wa = WideU::from_parts((a >> 32) as u32, a as u32);
1060            assert_eq!(wa.is_zero(), a == 0);
1061            for &b in &unsigned {
1062                let wb = WideU::from_parts((b >> 32) as u32, b as u32);
1063                assert_eq!(wa.cmp(&wb), a.cmp(&b), "{a} vs {b}");
1064                assert_eq!(valu(wa + wb), wrap_u64(a + b));
1065                assert_eq!(valu(wa - wb), wrap_u64(a.wrapping_sub(b)));
1066                assert_eq!(valu(wa.saturating_add(wb)), (a + b).min(u64::MAX as u128));
1067            }
1068            for k in U32_EDGES {
1069                assert_eq!(
1070                    valu(wa.times(k)),
1071                    wrap_u64(a.wrapping_mul(k as u128)),
1072                    "{a} * {k}"
1073                );
1074            }
1075        }
1076    }
1077
1078    #[test]
1079    fn isqrt_is_the_floor_root() {
1080        for &a in &wide_edges() {
1081            let w = wrap(a);
1082            let a64 = wrap_i64(a);
1083            let want = if a64 <= 0 {
1084                0
1085            } else {
1086                isqrt_oracle(a64 as u128)
1087            };
1088            assert_eq!(w.isqrt(), want, "isqrt {a}");
1089            let u = wrap_u64(a as u128);
1090            assert_eq!(
1091                WideU::from_parts((u >> 32) as u32, u as u32).isqrt(),
1092                isqrt_oracle(u)
1093            );
1094        }
1095        assert_eq!(Wide::of(-5).isqrt(), 0);
1096        assert_eq!(Wide::mul(i32::MAX, i32::MAX).isqrt(), i32::MAX as u32);
1097        assert_eq!(WideU::MAX.isqrt(), u32::MAX);
1098        assert_eq!(WideU::mul(u32::MAX, u32::MAX).isqrt(), u32::MAX);
1099    }
1100
1101    #[test]
1102    fn random_properties_against_the_oracle() {
1103        let mut rng = Rng(0x0123_4567_89ab_cdef);
1104        for _ in 0..200_000 {
1105            let (a, b) = (rng.i32(), rng.i32());
1106            let (x, y) = (rng.wide(), rng.wide());
1107            let (wx, wy) = (wrap(x), wrap(y));
1108            let (x64, y64) = (wrap_i64(x), wrap_i64(y));
1109            assert_eq!(val(Wide::mul(a, b)), a as i128 * b as i128);
1110            assert_eq!(val(wx.mul_add(a, b)), wrap_i64(x64 + a as i128 * b as i128));
1111            assert_eq!(val(wx.mul_sub(a, b)), wrap_i64(x64 - a as i128 * b as i128));
1112            assert_eq!(val(wx + wy), wrap_i64(x64 + y64));
1113            assert_eq!(val(wx - wy), wrap_i64(x64 - y64));
1114            assert_eq!(val(wx.mul_w(wy)), wrap_i64(x64.wrapping_mul(y64)));
1115            assert_eq!(val(wx.times(a)), wrap_i64(x64.wrapping_mul(a as i128)));
1116            assert_eq!(wx.cmp(&wy), x64.cmp(&y64));
1117            assert_eq!(wx.cmp_i32(a), x64.cmp(&(a as i128)));
1118            let n = rng.shift();
1119            assert_eq!(val(wx >> n), x64 >> (n & 63));
1120            assert_eq!(val(wx << n), wrap_i64(x64 << (n & 63)));
1121            assert_eq!(wx.shr_i32(n), (x64 >> (n & 63)) as i32);
1122            assert_eq!(
1123                wx.saturate_i32() as i128,
1124                x64.clamp(i32::MIN as i128, i32::MAX as i128)
1125            );
1126            let (ua, ub) = (rng.next() as u32, rng.next() as u32);
1127            assert_eq!(valu(WideU::mul(ua, ub)), ua as u128 * ub as u128);
1128            let ux = wrap_u64(x as u128);
1129            let wux = WideU::from_parts((ux >> 32) as u32, ux as u32);
1130            assert_eq!(
1131                valu(wux.mul_add(ua, ub)),
1132                wrap_u64(ux + ua as u128 * ub as u128)
1133            );
1134            assert_eq!(valu(wux >> n), ux >> (n & 63));
1135            assert_eq!(wux.isqrt(), isqrt_oracle(ux));
1136        }
1137    }
1138
1139    #[test]
1140    fn the_games_call_shapes_still_compute_what_they_did() {
1141        // hl-psx proj_logic: Wide::mul(v, 819).mul_add(dir, along).plus(2048) >> 12.
1142        let (v, dir, along) = (-123_456, 7_777, 31_415);
1143        let want = (v as i128 * 819 + dir as i128 * along as i128 + 2048) >> 12;
1144        assert_eq!(
1145            Wide::mul(v, 819).mul_add(dir, along).plus(2048).shr_i32(12),
1146            want as i32
1147        );
1148        // wipeout fx::atan2: headroom compare and shifts on a Wide.
1149        let limit = Wide::of(1) << 40;
1150        assert_eq!(val(limit), 1 << 40);
1151        assert!(Wide::of(1_000_000_000).shl_by(11).abs() > limit);
1152        assert!(Wide::of(1_000_000_000).shl_by(9).abs() <= limit);
1153        // cs-psx view_space_facing: the cross terms and the final 64x64 dot.
1154        let n = [
1155            Wide::mul(3, 5).mul_sub(7, 11),
1156            Wide::mul(-3, 5),
1157            Wide::mul(i32::MAX, i32::MAX),
1158        ];
1159        let sum = Wide::of(2).mul_w(n[0]) + Wide::of(-4).mul_w(n[1]) + Wide::of(1).mul_w(n[2]);
1160        assert_eq!(
1161            val(sum),
1162            2 * (15 - 77) + (-4) * (-15) + (i32::MAX as i128).pow(2)
1163        );
1164    }
1165
1166    #[test]
1167    fn mask64_set_algebra_matches_the_oracle() {
1168        let mut rng = Rng(0x0123_4567_89ab_cdef);
1169        let m = |v: u128| Mask64::from_words(v as u32, (v >> 32) as u32);
1170        let v = |m: Mask64| (m.low() as u128) | ((m.high() as u128) << 32);
1171        for count in 0..=70usize {
1172            let want = if count >= 64 {
1173                u64::MAX as u128
1174            } else {
1175                (1u128 << count) - 1
1176            };
1177            assert_eq!(v(Mask64::first(count)), want, "first({count})");
1178            let single = if count >= 64 { 0 } else { 1u128 << count };
1179            assert_eq!(v(Mask64::bit(count)), single, "bit({count})");
1180        }
1181        for _ in 0..10_000 {
1182            let (a, b) = (rng.next() as u128, rng.next() as u128);
1183            assert_eq!(v(m(a).or(m(b))), a | b);
1184            assert_eq!(v(m(a).and(m(b))), a & b);
1185            assert_eq!(v(m(a).and_not(m(b))), a & !b & (u64::MAX as u128));
1186            assert_eq!(m(a).is_empty(), a & (u64::MAX as u128) == 0);
1187        }
1188        assert!(Mask64::EMPTY.is_empty());
1189    }
1190
1191    #[test]
1192    fn mask64_sets_and_clears_each_bit() {
1193        let mut mask = Mask64::EMPTY;
1194        for bit in [0usize, 1, 31, 32, 33, 63] {
1195            mask.set(bit);
1196            assert!(mask.test(bit));
1197        }
1198        assert!(!mask.test(2) && !mask.test(64) && !mask.test(200));
1199        mask.assign(32, false);
1200        mask.clear(0);
1201        mask.assign(5, true);
1202        assert!(!mask.test(32) && !mask.test(0) && mask.test(33) && mask.test(63) && mask.test(5));
1203        for bit in 0..64 {
1204            let mut one = Mask64::EMPTY;
1205            one.set(bit);
1206            assert!((0..64).all(|other| one.test(other) == (other == bit)));
1207            one.clear(bit);
1208            assert_eq!(one, Mask64::EMPTY);
1209        }
1210    }
1211
1212    #[test]
1213    fn debug_prints_the_two_words() {
1214        use core::fmt::Write;
1215        struct Buf([u8; 48], usize);
1216        impl Write for Buf {
1217            fn write_str(&mut self, s: &str) -> core::fmt::Result {
1218                self.0[self.1..self.1 + s.len()].copy_from_slice(s.as_bytes());
1219                self.1 += s.len();
1220                Ok(())
1221            }
1222        }
1223        let mut b = Buf([0; 48], 0);
1224        write!(b, "{:?} {:?}", Wide::from_parts(-1, 0x1234), WideU::MAX).unwrap();
1225        assert_eq!(
1226            &b.0[..b.1],
1227            b"Wide(ffffffff:00001234) WideU(ffffffff:ffffffff)"
1228        );
1229    }
1230}