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

psx_math/
wide_div.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Exact division of a [`Wide`] / [`WideU`] value, in 32-bit instructions only.
3//!
4//! [`crate::wide`] leaves division out on purpose: `i64 / i64` links the
5//! compiler's `__divdi3` / `u64_div_rem`, which the guest symbol gate refuses.
6//! A game that really has a wide numerator (a dot product over a Q12 length, a
7//! cross product against a cross product, a tick count over a rate) divides it
8//! here instead. Nothing below names a 64-bit integer type: every operation is
9//! built from `WideU::mul` (`multu`), 64-bit add / subtract / compare / shift
10//! and 32-bit `divu`, so it links no helper. The operations are exact; none
11//! estimates or drops low bits.
12//!
13//! # The operations
14//!
15//! | operation | divisor | result |
16//! |---|---|---|
17//! | [`WideU::div_rem_u32`] | `u32` | full 64-bit quotient and the remainder |
18//! | [`WideU::quotient`] | [`WideU`] | `floor(n / d)`, clamped to `u32` |
19//! | [`Wide::div_i32_wrap`] | `i32` | quotient (a chosen [`Rounding`]) as the low 32 bits |
20//! | [`Wide::div_i32_sat`] | `i32` | the same, clamped to the `i32` range |
21//! | [`Wide::div_wide_sat`] | [`Wide`] | the same for a wide divisor |
22//! | [`WideU::mul_full`] | [`WideU`] | the exact 128-bit product, as two words |
23//! | [`WideU::cmp_ratio`] | | order of `a / b` against `c / d`, no divide |
24//! | [`WideU::scale_by_ratio`] | [`WideU`] | `floor(a * t / den)` for `t <= den` |
25//! | [`Wide::div_pow2`] | `2^shift` | quotient truncated toward zero, still wide |
26//!
27//! A divisor of zero panics, like `/`.
28//!
29//! # Cost
30//!
31//! Measured on the emulator by `sdk/examples/hello-wide-div` (cycles per call,
32//! random operands of every magnitude, call and return included). The table is
33//! in that example's header and in `docs`; the shape is: a numerator that fits
34//! 32 bits is one native `divu`; otherwise a high-word `divu` plus the two-digit
35//! [`crate::int32::div_u64_by_u32`]; a divisor wider than 32 bits adds one
36//! `div_u64_by_u32` for the estimate and a 96-bit product and compare to settle
37//! it. The division bodies are `#[inline(never)]`: one shared copy per image,
38//! because an inlined copy is several hundred bytes.
39
40use crate::int32::div_u64_by_u32;
41use crate::wide::{Wide, WideU};
42use core::cmp::Ordering;
43
44/// How an inexact quotient is rounded to an integer.
45#[derive(Clone, Copy, PartialEq, Eq, Debug)]
46pub enum Rounding {
47    /// Toward zero, like Rust's `/`.
48    TowardZero,
49    /// Toward negative infinity, like `div_euclid` for a positive divisor.
50    Floor,
51    /// To the nearest integer; an exact half goes away from zero.
52    Nearest,
53}
54
55/// `floor(n / d)` and `n - floor(n / d) * d` for a divisor that fits 32 bits.
56#[inline(never)]
57fn divrem_word(n: WideU, d: u32) -> (WideU, u32) {
58    assert!(d != 0, "attempt to divide by zero");
59    if n.high() == 0 {
60        // One native divide (the compiler fuses the remainder): the common case.
61        return (WideU::of(n.low() / d), n.low() % d);
62    }
63    // n = (hi * 2^32 + lo). hi = qh * d + rh; the low quotient word is
64    // (rh * 2^32 + lo) / d, whose high part rh < d is the shape the two-digit
65    // divide needs, and the remainder is what is left of that low part.
66    let rh = n.high() % d;
67    let q_low = div_u64_by_u32(rh, n.low(), d);
68    let rest = WideU::from_parts(rh, n.low()).sub(WideU::mul(q_low, d));
69    (WideU::from_parts(n.high() / d, q_low), rest.low())
70}
71
72/// `q * d` as (bits 64.., bits 0..64) for a 32-bit `q`.
73#[inline(always)]
74fn mul_word_wide(q: u32, d: WideU) -> (u32, WideU) {
75    let low = WideU::mul(q, d.low());
76    let high = WideU::mul(q, d.high());
77    // high * 2^32 + low: the low word of `high` joins at bit 32, its high word
78    // is bits 64.., plus the carry out of that add.
79    let sum = low.add(WideU::from_parts(high.low(), 0));
80    let carry = u32::from(sum < low);
81    (high.high() + carry, sum)
82}
83
84/// Steps `q` down to the largest value with `q * d <= top * 2^64 + low` (a 96-bit
85/// numerator), from an estimate that is too large. Returns `q` and `q * d` as
86/// (bits 64.., bits 0..64). Correctness does not depend on how far off the estimate
87/// is, only the loop count does.
88#[inline(always)]
89fn settle_down(mut q: u32, top: u32, low: WideU, d: WideU) -> (u32, u32, WideU) {
90    let (mut over, mut product) = mul_word_wide(q, d);
91    while over > top || (over == top && product > low) {
92        q -= 1;
93        let next = product.sub(d);
94        over -= u32::from(product < d);
95        product = next;
96        #[cfg(test)]
97        tests::step(true);
98    }
99    (q, over, product)
100}
101
102/// `floor(n / d)` and the remainder for `d >= 2^32`, so the quotient fits `u32`.
103#[inline(never)]
104fn divrem_wide(n: WideU, d: WideU) -> (u32, WideU) {
105    // The top 32 bits of d (bit 31 is set) and the same shift of n give one two-digit
106    // divide. With n' = floor(n / 2^s) and d' = floor(d / 2^s) the estimate
107    // floor(n' / d') is never below the true quotient q (n >= q d, so
108    // n' >= floor(q d / 2^s) >= q d'), and the cut-off bits make it one too high at
109    // most in practice (two is the bound), so only the downward settle is needed.
110    let shift = 32 - d.high().leading_zeros();
111    let narrow = d.shr_by(shift).low();
112    let top = n.shr_by(shift);
113    // top.high() < 2^(32 - shift) <= 2^31 <= narrow: the two-digit divide's precondition.
114    let estimate = div_u64_by_u32(top.high(), top.low(), narrow);
115    let (q, _, product) = settle_down(estimate, 0, n, d);
116    // q * d <= n < 2^64: the product fits the low pair and nothing wraps.
117    (q, n.sub(product))
118}
119
120/// The quotient magnitude of `|n| / |d|` after rounding, for the signed forms.
121///
122/// `negative` is the sign of the true quotient. One shared copy for every rounding mode
123/// and both divisor widths.
124#[inline(never)]
125fn rounded_magnitude(n: WideU, d: WideU, negative: bool, round: Rounding) -> WideU {
126    if n.high() == 0 && d.high() == 0 {
127        // Both fit a word: one native divide and 32-bit rounding. The common case.
128        let (n, d) = (n.low(), d.low());
129        assert!(d != 0, "attempt to divide by zero");
130        let (q, rest) = (n / d, n % d);
131        let up = match round {
132            Rounding::TowardZero => false,
133            Rounding::Floor => negative && rest != 0,
134            Rounding::Nearest => rest >= d - rest,
135        };
136        // q + 1 cannot wrap: a rounded-up quotient has d >= 2.
137        return WideU::of(q + u32::from(up));
138    }
139    let (q, rest) = if d.high() == 0 {
140        let (q, r) = divrem_word(n, d.low());
141        (q, WideU::of(r))
142    } else {
143        let (q, r) = divrem_wide(n, d);
144        (WideU::of(q), r)
145    };
146    let up = match round {
147        Rounding::TowardZero => false,
148        Rounding::Floor => negative && !rest.is_zero(),
149        // rest * 2 >= d, without the doubling that could overflow.
150        Rounding::Nearest => rest >= d.sub(rest),
151    };
152    if up {
153        q.add(WideU::of(1))
154    } else {
155        q
156    }
157}
158
159impl WideU {
160    /// `(self / d, self % d)`: the exact 64-bit quotient and the remainder.
161    ///
162    /// A numerator below 2^32 is one `divu`. Panics if `d` is zero.
163    #[inline]
164    pub fn div_rem_u32(self, d: u32) -> (WideU, u32) {
165        divrem_word(self, d)
166    }
167
168    /// `floor(self / d)`, clamped to `u32::MAX` when the true quotient is
169    /// larger. Exact: no estimate survives to the result. Panics if `d` is zero.
170    ///
171    /// A divisor wider than 32 bits makes the quotient fit `u32` by itself; the
172    /// clamp only matters for a divisor that fits 32 bits.
173    #[inline]
174    pub fn quotient(self, d: WideU) -> u32 {
175        assert!(!d.is_zero(), "attempt to divide by zero");
176        if d.high() == 0 {
177            divrem_word(self, d.low()).0.saturate_u32()
178        } else {
179            divrem_wide(self, d).0
180        }
181    }
182
183    /// The exact 128-bit product of two values, as `(bits 64..128, bits 0..64)`.
184    #[inline(never)]
185    pub fn mul_full(self, o: WideU) -> (WideU, WideU) {
186        let low = WideU::mul(self.low(), o.low());
187        let cross_a = WideU::mul(self.low(), o.high());
188        let cross_b = WideU::mul(self.high(), o.low());
189        let high = WideU::mul(self.high(), o.high());
190        // Neither sum below wraps before the second: each stays under 2^64 until the
191        // second, whose carry is read off the compare.
192        let first = cross_a.add(WideU::of(low.high()));
193        let middle = first.add(cross_b);
194        let carry = u32::from(middle < first);
195        (
196            high.add(WideU::from_parts(carry, middle.high())),
197            WideU::from_parts(middle.low(), low.low()),
198        )
199    }
200
201    /// Orders `a / b` against `c / d` without dividing: `a * d` against `c * b`,
202    /// each an exact 128-bit product. `b` and `d` must be nonzero.
203    #[inline(never)]
204    pub fn cmp_ratio(a: WideU, b: WideU, c: WideU, d: WideU) -> Ordering {
205        debug_assert!(!b.is_zero() && !d.is_zero());
206        a.mul_full(d).cmp(&c.mul_full(b))
207    }
208
209    /// `floor(a * self / den)` for `self <= den` (a fraction of at most one), so the
210    /// result is at most `a`. Exact. Panics if `den` is zero or `self > den`.
211    #[inline(never)]
212    pub fn scale_by_ratio(self, a: u32, den: WideU) -> u32 {
213        assert!(!den.is_zero() && self <= den, "ratio outside [0, 1]");
214        if den.high() == 0 {
215            // self <= den < 2^32: the product is one multu.
216            return WideU::mul(a, self.low()).quotient(den);
217        }
218        // The estimate divides by the top 32 bits of den: self >> shift fits 32 bits
219        // because self <= den, and the quotient is at most a.
220        let shift = 32 - den.high().leading_zeros();
221        let narrow = den.shr_by(shift).low();
222        let estimate = crate::int32::mul_div_u32(a, self.shr_by(shift).low(), narrow).min(a);
223        let (high, low) = WideU::of(a).mul_full(self);
224        let top = high.low();
225        // The estimate cuts both numerator and denominator, so it can land either side.
226        let (mut q, mut over, mut product) = settle_down(estimate, top, low, den);
227        while q < a {
228            let next = product.add(den);
229            let carried = over + u32::from(next < product);
230            if carried > top || (carried == top && next > low) {
231                break;
232            }
233            q += 1;
234            over = carried;
235            product = next;
236            #[cfg(test)]
237            tests::step(false);
238        }
239        q
240    }
241}
242
243impl Wide {
244    /// `self / 2^shift`, truncated toward zero, for `shift < 63`: the bias and
245    /// arithmetic shift a compiler emits for `i64 / (1 << shift)`.
246    #[inline(always)]
247    pub const fn div_pow2(self, shift: u32) -> Wide {
248        if self.is_negative() {
249            self.add_w(Wide::ONE.shl_by(shift).plus(-1)).sar(shift)
250        } else {
251            self.sar(shift)
252        }
253    }
254
255    /// `self / d` rounded as asked, as the low 32 bits of the quotient: where the
256    /// quotient does not fit `i32` it wraps, exactly like `(n / d) as i32`.
257    ///
258    /// Exact for every `self` and every nonzero `d`; panics if `d` is zero.
259    #[inline]
260    pub fn div_i32_wrap(self, d: i32, round: Rounding) -> i32 {
261        let negative = self.is_negative() != (d < 0);
262        let q = rounded_magnitude(
263            self.unsigned_abs(),
264            WideU::of(d.unsigned_abs()),
265            negative,
266            round,
267        )
268        .low();
269        if negative {
270            q.wrapping_neg() as i32
271        } else {
272            q as i32
273        }
274    }
275
276    /// `self / d` rounded as asked and clamped to the `i32` range. Panics if `d` is zero.
277    #[inline]
278    pub fn div_i32_sat(self, d: i32, round: Rounding) -> i32 {
279        let negative = self.is_negative() != (d < 0);
280        let q = rounded_magnitude(
281            self.unsigned_abs(),
282            WideU::of(d.unsigned_abs()),
283            negative,
284            round,
285        );
286        clamp_signed(negative, q)
287    }
288
289    /// `self / d` for a wide divisor, rounded as asked and clamped to the `i32` range.
290    /// Panics if `d` is zero.
291    #[inline]
292    pub fn div_wide_sat(self, d: Wide, round: Rounding) -> i32 {
293        let negative = self.is_negative() != d.is_negative();
294        let q = rounded_magnitude(self.unsigned_abs(), d.unsigned_abs(), negative, round);
295        clamp_signed(negative, q)
296    }
297}
298
299/// A signed quotient from its sign and magnitude, clamped to `i32`.
300#[inline(always)]
301fn clamp_signed(negative: bool, magnitude: WideU) -> i32 {
302    if negative {
303        if magnitude > WideU::of(1 << 31) {
304            i32::MIN
305        } else {
306            (magnitude.low() as i32).wrapping_neg()
307        }
308    } else if magnitude > WideU::of(i32::MAX as u32) {
309        i32::MAX
310    } else {
311        magnitude.low() as i32
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    extern crate std;
318    use super::*;
319
320    /// xorshift64*, the same stream on every run.
321    struct Rng(u64);
322    impl Rng {
323        fn next(&mut self) -> u64 {
324            let mut x = self.0;
325            x ^= x >> 12;
326            x ^= x << 25;
327            x ^= x >> 27;
328            self.0 = x;
329            x.wrapping_mul(0x2545_f491_4f6c_dd1d)
330        }
331        /// A value of random bit length, so every magnitude occurs.
332        fn magnitude(&mut self) -> u64 {
333            let v = self.next();
334            v >> (self.next() % 64)
335        }
336        fn word(&mut self) -> u32 {
337            self.magnitude() as u32
338        }
339        fn signed(&mut self) -> i64 {
340            let m = self.magnitude() as i64;
341            if self.next() & 1 == 0 {
342                m
343            } else {
344                m.wrapping_neg()
345            }
346        }
347    }
348
349    fn wu(x: u64) -> WideU {
350        WideU::from_parts((x >> 32) as u32, x as u32)
351    }
352    fn uw(x: WideU) -> u64 {
353        (u64::from(x.high()) << 32) | u64::from(x.low())
354    }
355    fn ws(x: i64) -> Wide {
356        Wide::from_parts((x >> 32) as i32, x as u32)
357    }
358
359    const CASES: u32 = 1_500_000;
360
361    /// Edge values of a 64-bit magnitude: around every word boundary.
362    fn edges() -> std::vec::Vec<u64> {
363        let mut v = std::vec![0, 1, 2, 3, u64::MAX, u64::MAX - 1, 1 << 63, (1 << 63) - 1];
364        for s in [16u32, 31, 32, 33, 48, 62] {
365            for d in [-2i64, -1, 0, 1, 2] {
366                v.push(((1u64 << s) as i64 + d) as u64);
367            }
368        }
369        v
370    }
371
372    /// The reference rounding, on i128.
373    fn oracle(n: i128, d: i128, round: Rounding) -> i128 {
374        let (q, r) = (n / d, n % d);
375        match round {
376            Rounding::TowardZero => q,
377            Rounding::Floor => {
378                if r != 0 && ((n < 0) != (d < 0)) {
379                    q - 1
380                } else {
381                    q
382                }
383            }
384            Rounding::Nearest => {
385                // Round half away from zero: |n| / |d| + 1/2 on the magnitude.
386                let (an, ad) = (n.abs(), d.abs());
387                let m = (2 * an + ad) / (2 * ad);
388                if (n < 0) != (d < 0) {
389                    -m
390                } else {
391                    m
392                }
393            }
394        }
395    }
396    const ROUNDS: [Rounding; 3] = [Rounding::TowardZero, Rounding::Floor, Rounding::Nearest];
397
398    #[test]
399    fn div_rem_u32_matches() {
400        let mut r = Rng(0x1234_5678_9abc_def1);
401        let check = |n: u64, d: u32| {
402            let (q, rem) = wu(n).div_rem_u32(d);
403            assert_eq!(
404                (uw(q), u64::from(rem)),
405                (n / u64::from(d), n % u64::from(d)),
406                "{n} / {d}"
407            );
408        };
409        for &n in &edges() {
410            for d in [1u32, 2, 3, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0x1_0001 - 2] {
411                check(n, d);
412            }
413        }
414        for _ in 0..CASES {
415            check(r.magnitude(), r.word().max(1));
416        }
417    }
418
419    #[test]
420    fn quotient_matches_for_every_divisor_width() {
421        let mut r = Rng(0x0bad_5eed_1234_5678);
422        let check = |n: u64, d: u64| {
423            let want = (u128::from(n) / u128::from(d)).min(u128::from(u32::MAX)) as u32;
424            assert_eq!(wu(n).quotient(wu(d)), want, "{n} / {d}");
425        };
426        let e = edges();
427        for &n in &e {
428            for &d in e.iter().filter(|d| **d != 0) {
429                check(n, d);
430            }
431        }
432        for _ in 0..CASES {
433            check(r.magnitude(), r.magnitude().max(1));
434        }
435        // Quotients that are exact multiples and one short of one, the settle edge.
436        for _ in 0..CASES {
437            let d = r.magnitude().max(1);
438            let q = u64::from(r.word());
439            let Some(m) = d.checked_mul(q) else { continue };
440            check(m, d);
441            check(m.saturating_add(d - 1), d);
442            check(m.saturating_sub(1), d);
443        }
444    }
445
446    #[test]
447    fn signed_division_matches_i128() {
448        let mut r = Rng(0x9e37_79b9_7f4a_7c15);
449        let mut edge_n: std::vec::Vec<i64> = edges()
450            .iter()
451            .flat_map(|&u| [u as i64, (u as i64).wrapping_neg()])
452            .collect();
453        edge_n.dedup();
454        let edge_d: [i32; 11] = [
455            1,
456            -1,
457            2,
458            -2,
459            3,
460            -3,
461            32767,
462            0x7fff_ffff,
463            i32::MIN,
464            409_600,
465            -409_600,
466        ];
467        let check = |n: i64, d: i32, round: Rounding| {
468            let q = oracle(i128::from(n), i128::from(d), round);
469            assert_eq!(
470                ws(n).div_i32_wrap(d, round),
471                q as i32,
472                "wrap {n} / {d} {round:?}"
473            );
474            let sat = q.clamp(i128::from(i32::MIN), i128::from(i32::MAX)) as i32;
475            assert_eq!(ws(n).div_i32_sat(d, round), sat, "sat {n} / {d} {round:?}");
476        };
477        for &n in &edge_n {
478            for &d in &edge_d {
479                for round in ROUNDS {
480                    check(n, d, round);
481                }
482            }
483        }
484        for _ in 0..CASES {
485            let n = r.signed();
486            let d = r.signed() as i32;
487            if d == 0 {
488                continue;
489            }
490            check(n, d, ROUNDS[(r.next() % 3) as usize]);
491        }
492    }
493
494    #[test]
495    fn wide_divisor_matches_i128() {
496        let mut r = Rng(0x2468_ace0_1357_9bdf);
497        let check = |n: i64, d: i64, round: Rounding| {
498            let q = oracle(i128::from(n), i128::from(d), round);
499            let sat = q.clamp(i128::from(i32::MIN), i128::from(i32::MAX)) as i32;
500            assert_eq!(ws(n).div_wide_sat(ws(d), round), sat, "{n} / {d} {round:?}");
501        };
502        let e: std::vec::Vec<i64> = edges()
503            .iter()
504            .flat_map(|&u| [u as i64, (u as i64).wrapping_neg()])
505            .collect();
506        for &n in &e {
507            for &d in e.iter().filter(|d| **d != 0) {
508                for round in ROUNDS {
509                    check(n, d, round);
510                }
511            }
512        }
513        for _ in 0..CASES {
514            let d = r.signed();
515            if d == 0 {
516                continue;
517            }
518            // Bias toward quotients that fit, the case that matters.
519            let n = if r.next().is_multiple_of(2) {
520                r.signed()
521            } else {
522                let q = i64::from(r.word() as i32);
523                q.wrapping_mul(d).wrapping_add((r.next() % 5) as i64 - 2)
524            };
525            check(n, d, ROUNDS[(r.next() % 3) as usize]);
526        }
527    }
528
529    #[test]
530    fn div_pow2_matches() {
531        let mut r = Rng(77);
532        for _ in 0..CASES {
533            let n = r.signed();
534            let s = (r.next() % 63) as u32;
535            assert_eq!(ws(n).div_pow2(s), ws(n / (1i64 << s)), "{n} / 2^{s}");
536        }
537        assert_eq!(ws(-1).div_pow2(5), ws(0));
538        assert_eq!(ws(-33).div_pow2(5), ws(-1));
539    }
540
541    #[test]
542    fn mul_full_matches_u128() {
543        let mut r = Rng(31337);
544        let e = edges();
545        for &a in &e {
546            for &b in &e {
547                let (h, l) = wu(a).mul_full(wu(b));
548                assert_eq!(
549                    (u128::from(uw(h)) << 64) | u128::from(uw(l)),
550                    u128::from(a) * u128::from(b),
551                    "{a} {b}"
552                );
553            }
554        }
555        for _ in 0..CASES {
556            let (a, b) = (r.magnitude(), r.magnitude());
557            let (h, l) = wu(a).mul_full(wu(b));
558            assert_eq!(
559                (u128::from(uw(h)) << 64) | u128::from(uw(l)),
560                u128::from(a) * u128::from(b),
561                "{a} {b}"
562            );
563        }
564    }
565
566    #[test]
567    fn cmp_ratio_orders_like_u128() {
568        let mut r = Rng(12345);
569        for _ in 0..CASES {
570            let (a, c) = (r.magnitude(), r.magnitude());
571            let (b, d) = (r.magnitude().max(1), r.magnitude().max(1));
572            let want = (u128::from(a) * u128::from(d)).cmp(&(u128::from(c) * u128::from(b)));
573            assert_eq!(WideU::cmp_ratio(wu(a), wu(b), wu(c), wu(d)), want);
574            assert_eq!(
575                WideU::cmp_ratio(wu(a), wu(b), wu(a), wu(b)),
576                Ordering::Equal
577            );
578        }
579        // Equal ratios with different terms, and neighbours of them.
580        for _ in 0..CASES {
581            let (b, k) = (u64::from(r.word()).max(1), u64::from(r.word()).max(1));
582            let a = u64::from(r.word()).min(b);
583            let (c, d) = (a * k, b * k);
584            assert_eq!(
585                WideU::cmp_ratio(wu(a), wu(b), wu(c), wu(d)),
586                Ordering::Equal
587            );
588            assert_eq!(
589                WideU::cmp_ratio(wu(a + 1), wu(b), wu(c), wu(d)),
590                Ordering::Greater
591            );
592        }
593    }
594
595    #[test]
596    fn scale_by_ratio_matches_u128() {
597        let mut r = Rng(99);
598        let check = |a: u32, t: u64, den: u64| {
599            let want = (u128::from(a) * u128::from(t) / u128::from(den)) as u32;
600            assert_eq!(wu(t).scale_by_ratio(a, wu(den)), want, "{a} * {t} / {den}");
601        };
602        for _ in 0..CASES {
603            let den = r.magnitude().max(1);
604            let t = match r.next() % 4 {
605                0 => den,
606                1 => 0,
607                _ => (u128::from(r.next()) % (u128::from(den) + 1)) as u64,
608            };
609            check(r.word(), t, den);
610        }
611        for &den in edges().iter().filter(|d| **d != 0) {
612            for t in [0, 1, den / 2, den - 1, den] {
613                for a in [0, 1, 255, u32::MAX] {
614                    check(a, t, den);
615                }
616            }
617        }
618    }
619
620    std::thread_local! {
621        static STEPS: core::cell::Cell<(u32, u32)> = const { core::cell::Cell::new((0, 0)) };
622    }
623    pub(super) fn step(down: bool) {
624        STEPS.with(|c| {
625            let (d, u) = c.get();
626            c.set(if down { (d + 1, u) } else { (d, u + 1) });
627        });
628    }
629
630    /// The estimate from the top 32 bits of the divisor is a couple off at most: count the
631    /// steps `settle` takes and bound them per call and on average.
632    #[test]
633    fn settle_loops_stay_short() {
634        let mut r = Rng(5150);
635        let calls = 400_000u32;
636        let (mut worst, mut down_total, mut up_total) = (0u32, 0u32, 0u32);
637        for _ in 0..calls {
638            let d = (r.magnitude() | (1 << 32)).max(1 << 32);
639            let n = r.next();
640            STEPS.with(|c| c.set((0, 0)));
641            let q = wu(n).quotient(wu(d));
642            assert_eq!(u64::from(q), n / d);
643            let (down, up) = STEPS.with(|c| c.get());
644            worst = worst.max(down + up);
645            down_total += down;
646            up_total += up;
647        }
648        assert!(worst <= 2, "settle took {worst} steps in one call");
649        std::eprintln!(
650            "quotient steps over {calls} calls: down {down_total}, up {up_total}, worst {worst}"
651        );
652        let (mut worst, mut down_total, mut up_total) = (0u32, 0u32, 0u32);
653        for _ in 0..calls {
654            let den = (r.magnitude() | (1 << 32)).max(1 << 32);
655            let t = (u128::from(r.next()) % (u128::from(den) + 1)) as u64;
656            STEPS.with(|c| c.set((0, 0)));
657            let _ = wu(t).scale_by_ratio(r.word(), wu(den));
658            let (down, up) = STEPS.with(|c| c.get());
659            worst = worst.max(down + up);
660            down_total += down;
661            up_total += up;
662        }
663        assert!(worst <= 3, "scale_by_ratio took {worst} steps in one call");
664        std::eprintln!(
665            "scale steps over {calls} calls: down {down_total}, up {up_total}, worst {worst}"
666        );
667    }
668
669    #[test]
670    #[should_panic(expected = "divide by zero")]
671    fn zero_divisor_panics() {
672        let _ = ws(5).div_i32_wrap(0, Rounding::TowardZero);
673    }
674}