Skip to main content

decimal_scaled/wide_int/
mod.rs

1//! Generic wide-integer arithmetic.
2//!
3//! A self-contained fixed-width big-integer layer: signed `Int*` and
4//! unsigned `Uint*` two's-complement integers from 256 to 4096 bits,
5//! plus the `WideInt` trait that casts losslessly between any two
6//! widths (or a primitive `i128` / `i64` / `u128`). The module depends
7//! on nothing else in the crate and is structured so it can later be
8//! lifted into a standalone crate.
9//!
10//! # Structure
11//!
12//! - **Slice primitives** — the actual arithmetic, written once over
13//!   `&[u128]` limb slices (little-endian, `limbs[0]` least
14//!   significant). Operating on slices sidesteps the const-generic
15//!   return-type problem a widening multiply would otherwise hit. The
16//!   core routines are `const fn` so the integer types built on them
17//!   can expose `const` constructors and constants.
18//! - **`macros`** — the `decl_wide_int!` macro: emits a concrete
19//!   two's-complement signed integer type and its unsigned sibling for
20//!   a fixed limb count, delegating arithmetic to the slice primitives.
21//! - The concrete `Uint* / Int*` type pairs generated by that macro.
22
23// ─────────────────────────────────────────────────────────────────────
24// Slice primitives — unsigned limb-array arithmetic.
25//
26// Every routine treats its slices as little-endian unsigned integers.
27// Lengths are taken from the slices; callers size output buffers.
28// ─────────────────────────────────────────────────────────────────────
29
30/// Full 128×128 → 256 unsigned product, `(high, low)`.
31#[inline]
32const fn mul_128(a: u128, b: u128) -> (u128, u128) {
33    let (a_hi, a_lo) = (a >> 64, a & u64::MAX as u128);
34    let (b_hi, b_lo) = (b >> 64, b & u64::MAX as u128);
35    let (mid, carry1) = (a_lo * b_hi).overflowing_add(a_hi * b_lo);
36    let (low, carry2) = (a_lo * b_lo).overflowing_add(mid << 64);
37    let high = a_hi * b_hi + (mid >> 64) + ((carry1 as u128) << 64) + carry2 as u128;
38    (high, low)
39}
40
41/// `a == 0`.
42#[inline]
43pub(crate) const fn limbs_is_zero(a: &[u128]) -> bool {
44    let mut i = 0;
45    while i < a.len() {
46        if a[i] != 0 {
47            return false;
48        }
49        i += 1;
50    }
51    true
52}
53
54/// `a == b` for two limb slices of possibly different lengths.
55#[inline]
56pub(crate) const fn limbs_eq(a: &[u128], b: &[u128]) -> bool {
57    let n = if a.len() > b.len() { a.len() } else { b.len() };
58    let mut i = 0;
59    while i < n {
60        let av = if i < a.len() { a[i] } else { 0 };
61        let bv = if i < b.len() { b[i] } else { 0 };
62        if av != bv {
63            return false;
64        }
65        i += 1;
66    }
67    true
68}
69
70/// Three-way comparison of two limb slices of possibly different
71/// lengths. Returns `-1`, `0`, or `1` for less / equal / greater.
72#[inline]
73pub(crate) const fn limbs_cmp(a: &[u128], b: &[u128]) -> i32 {
74    let n = if a.len() > b.len() { a.len() } else { b.len() };
75    let mut i = n;
76    while i > 0 {
77        i -= 1;
78        let av = if i < a.len() { a[i] } else { 0 };
79        let bv = if i < b.len() { b[i] } else { 0 };
80        if av < bv {
81            return -1;
82        }
83        if av > bv {
84            return 1;
85        }
86    }
87    0
88}
89
90/// Bit length (`0` for zero, else `floor(log2)+1`).
91#[inline]
92pub(crate) const fn limbs_bit_len(a: &[u128]) -> u32 {
93    let mut i = a.len();
94    while i > 0 {
95        i -= 1;
96        if a[i] != 0 {
97            return (i as u32) * 128 + (128 - a[i].leading_zeros());
98        }
99    }
100    0
101}
102
103/// `a += b`, returning the carry out. `a.len() >= b.len()`.
104#[inline]
105pub(crate) const fn limbs_add_assign(a: &mut [u128], b: &[u128]) -> bool {
106    let mut carry = 0u128;
107    let mut i = 0;
108    while i < a.len() {
109        let bv = if i < b.len() { b[i] } else { 0 };
110        let (s1, c1) = a[i].overflowing_add(bv);
111        let (s2, c2) = s1.overflowing_add(carry);
112        a[i] = s2;
113        carry = (c1 as u128) + (c2 as u128);
114        i += 1;
115    }
116    carry != 0
117}
118
119/// `a -= b`, returning the borrow out. `a.len() >= b.len()`.
120#[inline]
121pub(crate) const fn limbs_sub_assign(a: &mut [u128], b: &[u128]) -> bool {
122    let mut borrow = 0u128;
123    let mut i = 0;
124    while i < a.len() {
125        let bv = if i < b.len() { b[i] } else { 0 };
126        let (d1, b1) = a[i].overflowing_sub(bv);
127        let (d2, b2) = d1.overflowing_sub(borrow);
128        a[i] = d2;
129        borrow = (b1 as u128) + (b2 as u128);
130        i += 1;
131    }
132    borrow != 0
133}
134
135/// `out = a << shift`. `out` is zeroed then filled; bits shifted past
136/// `out`'s width are dropped.
137pub(crate) const fn limbs_shl(a: &[u128], shift: u32, out: &mut [u128]) {
138    let mut z = 0;
139    while z < out.len() {
140        out[z] = 0;
141        z += 1;
142    }
143    let limb_shift = (shift / 128) as usize;
144    let bit = shift % 128;
145    let mut i = 0;
146    while i < a.len() {
147        let dst = i + limb_shift;
148        if dst < out.len() {
149            if bit == 0 {
150                out[dst] |= a[i];
151            } else {
152                out[dst] |= a[i] << bit;
153                if dst + 1 < out.len() {
154                    out[dst + 1] |= a[i] >> (128 - bit);
155                }
156            }
157        }
158        i += 1;
159    }
160}
161
162/// `out = a >> shift`. `out` is zeroed then filled.
163pub(crate) const fn limbs_shr(a: &[u128], shift: u32, out: &mut [u128]) {
164    let mut z = 0;
165    while z < out.len() {
166        out[z] = 0;
167        z += 1;
168    }
169    let limb_shift = (shift / 128) as usize;
170    let bit = shift % 128;
171    let mut i = limb_shift;
172    while i < a.len() {
173        let dst = i - limb_shift;
174        if dst < out.len() {
175            if bit == 0 {
176                out[dst] |= a[i];
177            } else {
178                out[dst] |= a[i] >> bit;
179                if dst >= 1 {
180                    out[dst - 1] |= a[i] << (128 - bit);
181                }
182            }
183        }
184        i += 1;
185    }
186}
187
188/// `out = a · b` (schoolbook). `out.len() >= a.len() + b.len()` and
189/// `out` must be zeroed by the caller.
190pub(crate) const fn limbs_mul(a: &[u128], b: &[u128], out: &mut [u128]) {
191    // Fast path for the 2-limb × 2-limb → 4-limb shape used by
192    // `Int256::wrapping_mul` (the densest wide-int call site). Hand
193    // unrolled so the compiler sees four independent `mul_128`
194    // sub-products that can issue in parallel; the inner loop variant
195    // can't express that.
196    if a.len() == 2 && b.len() == 2 && out.len() >= 4 {
197        let (a0, a1) = (a[0], a[1]);
198        let (b0, b1) = (b[0], b[1]);
199        // (a1·2^128 + a0)·(b1·2^128 + b0) = h3·2^384 + (h1+h2+l3)·2^256
200        // + (h0+l1+l2)·2^128 + l0
201        let (h0, l0) = mul_128(a0, b0);
202        let (h1, l1) = mul_128(a0, b1);
203        let (h2, l2) = mul_128(a1, b0);
204        let (h3, l3) = mul_128(a1, b1);
205
206        out[0] = l0;
207
208        let (s1, c1a) = h0.overflowing_add(l1);
209        let (s1, c1b) = s1.overflowing_add(l2);
210        out[1] = s1;
211        let mid_carry = (c1a as u128) + (c1b as u128);
212
213        let (s2, c2a) = h1.overflowing_add(h2);
214        let (s2, c2b) = s2.overflowing_add(l3);
215        let (s2, c2c) = s2.overflowing_add(mid_carry);
216        out[2] = s2;
217        let top_carry = (c2a as u128) + (c2b as u128) + (c2c as u128);
218
219        out[3] = h3.wrapping_add(top_carry);
220        return;
221    }
222
223    let mut i = 0;
224    while i < a.len() {
225        if a[i] != 0 {
226            let mut carry = 0u128;
227            let mut j = 0;
228            while j < b.len() {
229                // Skip zero-limb contributions: every `*` for `b[j] = 0`
230                // produces (0, 0) and the only effect is propagating the
231                // carry. Adds a hot fast path for widened-from-narrower
232                // operands (their upper limbs are zero) and for
233                // small-magnitude multipliers like `10^SCALE` at modest
234                // scales (one nonzero limb in `b`).
235                if b[j] != 0 || carry != 0 {
236                    let (hi, lo) = mul_128(a[i], b[j]);
237                    let idx = i + j;
238                    let (s1, c1) = out[idx].overflowing_add(lo);
239                    let (s2, c2) = s1.overflowing_add(carry);
240                    out[idx] = s2;
241                    carry = hi + (c1 as u128) + (c2 as u128);
242                }
243                j += 1;
244            }
245            let mut idx = i + b.len();
246            while carry != 0 && idx < out.len() {
247                let (s, c) = out[idx].overflowing_add(carry);
248                out[idx] = s;
249                carry = c as u128;
250                idx += 1;
251            }
252        }
253        i += 1;
254    }
255}
256
257/// Karatsuba multiplication threshold. For `a.len() < KARATSUBA_MIN`
258/// the schoolbook kernel wins because Karatsuba's recursive split
259/// allocates six `Vec`s of scratch per level (`z0`, `z1`, `z2`,
260/// `sum_a`, `sum_b`, plus the merge buffer). On `[u128]` limbs the
261/// `mul_128` savings (3·(n/2)² vs n² calls per level) only outpay
262/// that heap-alloc tax at n ≥ 32 limbs. Below that, the alloc + carry
263/// merges cost more than the limb-mul work they save — verified by
264/// `examples/karabench.rs`: at n=16 the schoolbook beats single-level
265/// Karatsuba ~800 ns vs ~880 ns; at n=32 Karatsuba wins back ~15%
266/// (~2.6 µs vs ~3.0 µs). Below 32 limbs the dispatcher therefore
267/// short-circuits straight to schoolbook.
268const KARATSUBA_MIN: usize = 32;
269
270/// `out = a · b` for equal-length inputs, dispatching to Karatsuba
271/// when the operand size warrants it.
272///
273/// Not `const fn` — Karatsuba's half-sum scratch needs heap allocation.
274/// Callers in `const` context (parsing string-literal constants, etc.)
275/// keep using [`limbs_mul`].
276///
277/// `out.len() >= 2 · a.len()`. `a.len() == b.len()` required for the
278/// Karatsuba path; mismatched lengths fall through to schoolbook.
279#[cfg(feature = "alloc")]
280pub(crate) fn limbs_mul_fast(a: &[u128], b: &[u128], out: &mut [u128]) {
281    if a.len() == b.len() && a.len() >= KARATSUBA_MIN {
282        limbs_mul_karatsuba(a, b, out);
283    } else {
284        limbs_mul(a, b, out);
285    }
286}
287
288#[cfg(not(feature = "alloc"))]
289pub(crate) fn limbs_mul_fast(a: &[u128], b: &[u128], out: &mut [u128]) {
290    limbs_mul(a, b, out);
291}
292
293/// Karatsuba multiplication, equal-length inputs.
294///
295/// Split `a = a_hi·B^h + a_lo`, `b = b_hi·B^h + b_lo` with
296/// `B = 2^128` and `h = a.len() / 2`. Compute three sub-products:
297///
298/// - `z0 = a_lo · b_lo`
299/// - `z2 = a_hi · b_hi`
300/// - `z1 = (a_lo + a_hi)·(b_lo + b_hi) − z0 − z2`
301///
302/// Then `a·b = z2·B^(2h) + z1·B^h + z0`.
303///
304/// Reference: Karatsuba, A. and Ofman, Yu. (1962). "Multiplication of
305/// Multidigit Numbers on Automata." *Doklady Akad. Nauk SSSR* 145,
306/// 293–294.
307#[cfg(feature = "alloc")]
308fn limbs_mul_karatsuba(a: &[u128], b: &[u128], out: &mut [u128]) {
309    debug_assert_eq!(a.len(), b.len());
310    debug_assert!(out.len() >= 2 * a.len());
311    let n = a.len();
312    if n < KARATSUBA_MIN {
313        // Zero out and run schoolbook.
314        for o in out.iter_mut().take(2 * n) {
315            *o = 0;
316        }
317        limbs_mul(a, b, out);
318        return;
319    }
320    let h = n / 2;
321    let (a_lo, a_hi_full) = a.split_at(h);
322    let (b_lo, b_hi_full) = b.split_at(h);
323    let a_hi = a_hi_full;
324    let b_hi = b_hi_full;
325
326    // z0 = a_lo · b_lo (length 2h)
327    let mut z0 = alloc::vec![0u128; 2 * h];
328    limbs_mul_karatsuba_padded(a_lo, b_lo, &mut z0);
329
330    // z2 = a_hi · b_hi (length 2*(n-h))
331    let hi_len = n - h;
332    let mut z2 = alloc::vec![0u128; 2 * hi_len];
333    limbs_mul_karatsuba_padded(a_hi, b_hi, &mut z2);
334
335    // sum_a = a_lo + a_hi (length max(h, hi_len) + 1)
336    let sum_len = core::cmp::max(h, hi_len) + 1;
337    let mut sum_a = alloc::vec![0u128; sum_len];
338    let mut sum_b = alloc::vec![0u128; sum_len];
339    sum_a[..h].copy_from_slice(a_lo);
340    sum_b[..h].copy_from_slice(b_lo);
341    limbs_add_assign(&mut sum_a[..], a_hi);
342    limbs_add_assign(&mut sum_b[..], b_hi);
343
344    // z1 = sum_a · sum_b (length 2 * sum_len)
345    let mut z1 = alloc::vec![0u128; 2 * sum_len];
346    limbs_mul_karatsuba_padded(&sum_a, &sum_b, &mut z1);
347
348    // z1 -= z0
349    limbs_sub_assign(&mut z1[..], &z0);
350    // z1 -= z2
351    limbs_sub_assign(&mut z1[..], &z2);
352
353    // Combine: out[..2h] = z0; out[2h..] = z2 shifted up by 2h;
354    // then add z1 shifted up by h.
355    for o in out.iter_mut().take(2 * n) {
356        *o = 0;
357    }
358    let z0_take = core::cmp::min(z0.len(), out.len());
359    out[..z0_take].copy_from_slice(&z0[..z0_take]);
360    let z2_take = core::cmp::min(z2.len(), out.len().saturating_sub(2 * h));
361    if z2_take > 0 {
362        out[2 * h..2 * h + z2_take].copy_from_slice(&z2[..z2_take]);
363    }
364    // Add z1 << h.
365    let z1_take = core::cmp::min(z1.len(), out.len().saturating_sub(h));
366    if z1_take > 0 {
367        limbs_add_assign(&mut out[h..h + z1_take], &z1[..z1_take]);
368    }
369}
370
371/// Karatsuba helper that pads to equal lengths if the caller passes
372/// uneven slices (happens at the recursion boundary when `n` is odd
373/// and `n_hi = n - h > h`).
374#[cfg(feature = "alloc")]
375fn limbs_mul_karatsuba_padded(a: &[u128], b: &[u128], out: &mut [u128]) {
376    if a.len() == b.len() && a.len() >= KARATSUBA_MIN {
377        limbs_mul_karatsuba(a, b, out);
378    } else {
379        for o in out.iter_mut() {
380            *o = 0;
381        }
382        limbs_mul(a, b, out);
383    }
384}
385
386/// Single-bit left shift in place; returns the bit shifted out of the
387/// top.
388#[inline]
389const fn limbs_shl1(a: &mut [u128]) -> u128 {
390    let mut carry = 0u128;
391    let mut i = 0;
392    while i < a.len() {
393        let new_carry = a[i] >> 127;
394        a[i] = (a[i] << 1) | carry;
395        carry = new_carry;
396        i += 1;
397    }
398    carry
399}
400
401/// `true` if every limb above index 0 is zero — the value fits a
402/// single 128-bit word.
403#[inline]
404const fn limbs_fit_one(a: &[u128]) -> bool {
405    let mut i = 1;
406    while i < a.len() {
407        if a[i] != 0 {
408            return false;
409        }
410        i += 1;
411    }
412    true
413}
414
415/// `quot = num / den`, `rem = num % den`. `quot.len() >= num.len()`,
416/// `rem.len() >= num.len()`; both are zeroed by this routine. `den`
417/// must be non-zero.
418///
419/// Two hardware fast paths short-circuit the binary long-division
420/// loop — they cover the dominant decimal cases (moderate magnitudes,
421/// divisor `10^scale` for `scale <= 19`):
422///
423/// - both operands fit a single 128-bit word → one hardware divide;
424/// - the divisor fits a 64-bit word → schoolbook base-2^64 division,
425///   one hardware divide per limb-half.
426///
427/// Otherwise it falls back to a binary shift-subtract loop bounded by
428/// the dividend's actual bit length.
429pub(crate) const fn limbs_divmod(
430    num: &[u128],
431    den: &[u128],
432    quot: &mut [u128],
433    rem: &mut [u128],
434) {
435    let mut z = 0;
436    while z < quot.len() {
437        quot[z] = 0;
438        z += 1;
439    }
440    z = 0;
441    while z < rem.len() {
442        rem[z] = 0;
443        z += 1;
444    }
445
446    let den_one_limb = limbs_fit_one(den);
447
448    // Fast path A: both dividend and divisor fit one 128-bit word.
449    if den_one_limb && limbs_fit_one(num) {
450        if !quot.is_empty() {
451            quot[0] = num[0] / den[0];
452        }
453        if !rem.is_empty() {
454            rem[0] = num[0] % den[0];
455        }
456        return;
457    }
458
459    // Fast path B: divisor fits a 64-bit word — schoolbook base-2^64
460    // long division, one hardware divide per 64-bit half of the
461    // dividend. Every `10^scale` for `scale <= 19` lands here.
462    if den_one_limb && den[0] <= u64::MAX as u128 {
463        let d = den[0];
464        let mut r: u128 = 0;
465        // Skip leading zero limbs of the numerator — every wide-tier
466        // call widens narrower operands into a `2 × $L`-limb buffer,
467        // so the top limbs are zero by construction. Each skipped
468        // limb saves two hardware divides.
469        let mut top = num.len();
470        while top > 0 && num[top - 1] == 0 {
471            top -= 1;
472        }
473        let mut i = top;
474        while i > 0 {
475            i -= 1;
476            let hi = num[i] >> 64;
477            let acc_hi = (r << 64) | hi;
478            let q_hi = acc_hi / d;
479            r = acc_hi % d;
480            let lo = num[i] & u64::MAX as u128;
481            let acc_lo = (r << 64) | lo;
482            let q_lo = acc_lo / d;
483            r = acc_lo % d;
484            if i < quot.len() {
485                quot[i] = (q_hi << 64) | q_lo;
486            }
487        }
488        if !rem.is_empty() {
489            rem[0] = r;
490        }
491        return;
492    }
493
494    // General path: binary shift-subtract, bounded by the dividend's
495    // actual bit length.
496    let bits = limbs_bit_len(num);
497    let mut i = bits;
498    while i > 0 {
499        i -= 1;
500        limbs_shl1(rem);
501        let bit = (num[(i / 128) as usize] >> (i % 128)) & 1;
502        rem[0] |= bit;
503        limbs_shl1(quot);
504        if limbs_cmp(rem, den) >= 0 {
505            limbs_sub_assign(rem, den);
506            quot[0] |= 1;
507        }
508    }
509}
510
511/// Capacity of the internal scratch buffers — 72 limbs (9216 bits),
512/// comfortably above the widest work integer in the crate (4096-bit →
513/// 32 limbs, with isqrt scratch ≤ 33).
514const SCRATCH_LIMBS: usize = 72;
515
516/// Runtime divide dispatcher. Picks the cheapest correct algorithm
517/// for the operand shape:
518///
519/// * **Single-limb divisor** — defer to the existing `const fn`
520///   [`limbs_divmod`] which carries hardware-divide fast paths for
521///   `1 / 1` and `n / u64` (every `10^scale` with `scale ≤ 19`).
522/// * **Multi-limb divisor below `BZ_THRESHOLD`** — [`limbs_divmod_knuth`].
523///   Algorithm D in base 2^128: `O(m·n)` multi-limb ops, vs the
524///   const path's `O((m+n)·n·128)` shift-subtract fallback. Net win
525///   on every wide-tier divide (D76 and above) with `SCALE > 19`.
526/// * **Very-wide divisor (`n ≥ BZ_THRESHOLD` and `top ≥ 2·n`)** —
527///   [`limbs_divmod_bz`]. Burnikel–Ziegler chunked schoolbook over
528///   Knuth. Wins at D307 deep scales where the divisor exceeds 8
529///   limbs.
530///
531/// Not `const fn` (the kernels aren't either). The wide-int
532/// `Div` / `Rem` operator impls take this path; the const-fn
533/// `wrapping_div` / `wrapping_rem` siblings stay on
534/// [`limbs_divmod`] for compile-time evaluation.
535pub(crate) fn limbs_divmod_dispatch(
536    num: &[u128],
537    den: &[u128],
538    quot: &mut [u128],
539    rem: &mut [u128],
540) {
541    const BZ_THRESHOLD: usize = 8;
542
543    let mut n = den.len();
544    while n > 0 && den[n - 1] == 0 {
545        n -= 1;
546    }
547    assert!(n > 0, "limbs_divmod_dispatch: divide by zero");
548
549    let mut top = num.len();
550    while top > 0 && num[top - 1] == 0 {
551        top -= 1;
552    }
553
554    // Fast path A: both operands fit one 128-bit word.
555    if n == 1 && top <= 1 {
556        limbs_divmod(num, den, quot, rem);
557        return;
558    }
559
560    // Fast path B (covered by const limbs_divmod): single-limb
561    // divisor that also fits a u64. Every `10^scale` with
562    // `scale ≤ 19` lands here. Larger single-limb divisors
563    // (10^20 ≤ den ≤ 10^38) fall through to Knuth — the const
564    // path's only remaining option for those is the O(bits)
565    // shift-subtract, which is the bottleneck we're closing.
566    if n == 1 && den[0] <= u64::MAX as u128 {
567        limbs_divmod(num, den, quot, rem);
568        return;
569    }
570
571    // Multi-limb arithmetic OR oversized single-limb divisor —
572    // Knuth handles both efficiently; BZ wraps Knuth for very
573    // wide divisors.
574    if n >= BZ_THRESHOLD && top >= 2 * n {
575        limbs_divmod_bz(num, den, quot, rem);
576    } else {
577        limbs_divmod_knuth(num, den, quot, rem);
578    }
579}
580
581/// Möller–Granlund 2-by-1 invariant divisor.
582///
583/// Precomputes the reciprocal `v = ⌊(B² − 1) / d⌋ − B` (where
584/// `B = 2¹²⁸`) so each subsequent `(u₁·B + u₀) / d` reduces to two
585/// `mul_128`s plus a constant fix-up — vs the 128-iteration
586/// shift-subtract of [`div_2_by_1`].
587///
588/// Reference: Möller, N. and Granlund, T. (2011). *Improved Division
589/// by Invariant Integers*, IEEE Trans. Computers 60(2), 165–175,
590/// Algorithm 4 (div) and Algorithm 6 (reciprocal). PDF:
591/// <https://gmplib.org/~tege/division-paper.pdf>.
592///
593/// Setup amortises one bit-recovery `div_2_by_1` across every
594/// quotient limb of a [`limbs_divmod_knuth`] call, which is the
595/// difference between the wide-tier divide being ~50× a 2-by-1 step
596/// per limb (today) and ~2 multiplies per limb (with this struct).
597#[derive(Clone, Copy)]
598pub(crate) struct MG2by1 {
599    /// Normalised divisor (top bit set).
600    d: u128,
601    /// Reciprocal `v = ⌊(B² − 1) / d⌋ − B`.
602    v: u128,
603}
604
605impl MG2by1 {
606    /// Setup. `d` must be normalised (`d >> 127 == 1`).
607    ///
608    /// Computes `v` as `⌊(B² − 1 − d·B) / d⌋`, using the algebraic
609    /// rewrite `(B² − 1)/d − B = (B² − 1 − d·B)/d`. The numerator
610    /// `B² − 1 − d·B = (B − d − 1)·B + (B − 1)`, a u256 with
611    /// `high = !d` (since `!d = (B − 1) − d`) and `low = u128::MAX`.
612    /// `high < d` for any normalised `d`, so the existing
613    /// bit-recovery [`div_2_by_1`] handles it without precondition
614    /// violation.
615    #[inline]
616    pub(crate) const fn new(d: u128) -> Self {
617        debug_assert!(d >> 127 == 1, "MG2by1::new: divisor must be normalised");
618        let (v, _r) = div_2_by_1(!d, u128::MAX, d);
619        Self { d, v }
620    }
621
622    /// Divide `(u1·B + u0)` by the stored divisor. `u1 < d` is
623    /// required (else the quotient wouldn't fit `u128`).
624    ///
625    /// Per MG Algorithm 4:
626    /// 1. `(q1, q0) = v·u1 + ⟨u1, u0⟩` (u257; high word may wrap u128)
627    /// 2. `q1 += 1`
628    /// 3. `r = u0 − q1·d  (mod B)`
629    /// 4. if `r > q0`: `q1 -= 1`; `r += d` (wraps mod B)
630    /// 5. if `r >= d`: `q1 += 1`; `r -= d`
631    ///
632    /// Wrap-around in step 1/2/4 is fine: step 3 only depends on
633    /// `q1 mod B` (since `q1·d mod B == (q1 mod B)·d mod B`), and the
634    /// `r > q0` / `r >= d` corrections recover the true quotient
635    /// modulo `B`. The final `q1` always fits `u128` because the true
636    /// quotient is `< B` (per the `u1 < d` precondition).
637    #[inline]
638    pub(crate) const fn div_rem(&self, u1: u128, u0: u128) -> (u128, u128) {
639        debug_assert!(u1 < self.d, "MG2by1::div_rem: high word must be < divisor");
640        // Step 1.
641        let (vu1_hi, vu1_lo) = mul_128(self.v, u1);
642        let (q0, c_lo) = vu1_lo.overflowing_add(u0);
643        let (q1, _c_hi_a) = vu1_hi.overflowing_add(u1);
644        let (q1, _c_hi_b) = q1.overflowing_add(c_lo as u128);
645        // Step 2.
646        let q1 = q1.wrapping_add(1);
647        // Step 3.
648        let r = u0.wrapping_sub(q1.wrapping_mul(self.d));
649        // Step 4.
650        let (q1, r) = if r > q0 {
651            (q1.wrapping_sub(1), r.wrapping_add(self.d))
652        } else {
653            (q1, r)
654        };
655        // Step 5.
656        if r >= self.d {
657            (q1.wrapping_add(1), r.wrapping_sub(self.d))
658        } else {
659            (q1, r)
660        }
661    }
662}
663
664/// 2-by-1 unsigned divide: `(high · 2^128 + low) / d` and the matching
665/// remainder. Requires `high < d` so the quotient fits a single
666/// `u128`.
667///
668/// Implementation: bit-by-bit recovery (128 iterations, constant work
669/// per iter). Kept as the const-context fallback and as the setup
670/// path for [`MG2by1::new`]. Runtime callers that need many divides
671/// against the same divisor should use [`MG2by1`] instead — it cuts
672/// each subsequent divide from 128 iterations down to ~2 multiplies.
673#[inline]
674const fn div_2_by_1(high: u128, low: u128, d: u128) -> (u128, u128) {
675    // The classical recovery loop: at each step shift `r` left by 1,
676    // pull the next bit of `low` in, then conditionally subtract `d`
677    // and set the matching quotient bit. The catch is that `r` can
678    // grow past `2^128 − 1` between the shift and the subtract; we
679    // track that as the `r_top` carry-out bit so the comparison stays
680    // correct.
681    let mut q: u128 = 0;
682    let mut r = high;
683    let mut i = 128;
684    while i > 0 {
685        i -= 1;
686        let r_top = r >> 127;
687        r = (r << 1) | ((low >> i) & 1);
688        q <<= 1;
689        // r real = r_top·2^128 + r. Subtract if r_real ≥ d, i.e.
690        // r_top == 1 OR r ≥ d.
691        if r_top != 0 || r >= d {
692            r = r.wrapping_sub(d);
693            q |= 1;
694        }
695    }
696    (q, r)
697}
698
699/// Knuth Algorithm D — base-2^128 multi-limb long division. The
700/// algorithm-of-record base case for `limbs_divmod_bz` below.
701///
702/// Computes `quot = num / den`, `rem = num % den`. Requires
703/// `den` non-zero. `quot` and `rem` are zeroed by this routine.
704///
705/// This is the textbook Knuth Algorithm D (TAOCP Vol. 2, §4.3.1)
706/// adapted to base `2^128`: normalise the divisor so its top bit
707/// is set, then for each quotient limb estimate `q̂` from the top
708/// two limbs of the running dividend divided by the top limb of
709/// the divisor, refine `q̂` once if necessary against the second-
710/// from-top divisor limb, multiply-and-subtract, and add-back-and-
711/// decrement on the rare miss.
712///
713/// Complexity is `O(m·n)` multi-limb ops on `m+n / n`-limb inputs,
714/// versus the binary shift-subtract path's `O((m+n)·n·128)`. For
715/// `n = 32` limbs (Int4096) the difference is ~14×. For `n ≤ 2`
716/// limbs there's no win and the caller should keep using the
717/// existing single-limb fast paths in `limbs_divmod`.
718///
719/// Not `const fn`: the inner loops use `[u128; SCRATCH_LIMBS]`
720/// scratch buffers and mutate them via overflowing arithmetic
721/// that the const evaluator doesn't yet permit. None of the
722/// crate's const-contexts depend on this routine.
723pub(crate) fn limbs_divmod_knuth(
724    num: &[u128],
725    den: &[u128],
726    quot: &mut [u128],
727    rem: &mut [u128],
728) {
729    for q in quot.iter_mut() {
730        *q = 0;
731    }
732    for r in rem.iter_mut() {
733        *r = 0;
734    }
735
736    // Effective lengths after stripping leading zeros.
737    let mut n = den.len();
738    while n > 0 && den[n - 1] == 0 {
739        n -= 1;
740    }
741    assert!(n > 0, "limbs_divmod_knuth: divide by zero");
742
743    let mut top = num.len();
744    while top > 0 && num[top - 1] == 0 {
745        top -= 1;
746    }
747    if top < n {
748        // quotient is zero, remainder is num.
749        let copy_n = num.len().min(rem.len());
750        let mut i = 0;
751        while i < copy_n {
752            rem[i] = num[i];
753            i += 1;
754        }
755        return;
756    }
757
758    // D1. Normalise: shift divisor (and dividend) left by `shift` bits
759    // so the divisor's top limb has its high bit set. Knuth's q̂
760    // refinement guarantee only holds in that regime.
761    let shift = den[n - 1].leading_zeros();
762
763    let mut u = [0u128; SCRATCH_LIMBS];
764    let mut v = [0u128; SCRATCH_LIMBS];
765    debug_assert!(top < SCRATCH_LIMBS && n <= SCRATCH_LIMBS);
766
767    if shift == 0 {
768        u[..top].copy_from_slice(&num[..top]);
769        u[top] = 0;
770        v[..n].copy_from_slice(&den[..n]);
771    } else {
772        let mut carry: u128 = 0;
773        for i in 0..top {
774            let val = num[i];
775            u[i] = (val << shift) | carry;
776            carry = val >> (128 - shift);
777        }
778        u[top] = carry;
779        carry = 0;
780        for i in 0..n {
781            let val = den[i];
782            v[i] = (val << shift) | carry;
783            carry = val >> (128 - shift);
784        }
785    }
786
787    let m_plus_n = if u[top] != 0 { top + 1 } else { top };
788    debug_assert!(m_plus_n >= n);
789    let m = m_plus_n - n;
790
791    // Precompute the Möller–Granlund 2-by-1 reciprocal of the top
792    // divisor limb. After D1 the top limb has its high bit set
793    // (`v[n-1] >> 127 == 1` by construction), so the MG normalisation
794    // precondition is satisfied. One amortised setup cost spread
795    // across `m + 1` quotient-limb estimations.
796    let mg_top = MG2by1::new(v[n - 1]);
797
798    // D2. For j from m down to 0.
799    let mut j_plus_one = m + 1;
800    while j_plus_one > 0 {
801        j_plus_one -= 1;
802        let j = j_plus_one;
803
804        // D3. Estimate q̂.
805        let u_top = u[j + n];
806        let u_next = u[j + n - 1];
807        let v_top = v[n - 1];
808
809        let (mut q_hat, mut r_hat) = if u_top >= v_top {
810            // q̂ would exceed 2^128 − 1. Cap at the max and let the
811            // refinement / add-back step correct any over-estimate.
812            // r̂ = u_top·2^128 + u_next − q̂·v_top, computed mod 2^128
813            // with q̂ = 2^128 − 1: r̂ = u_top·2^128 + u_next − (2^128
814            // − 1)·v_top = (u_top − v_top)·2^128 + u_next + v_top.
815            // We only need r̂ ≤ 2^128 − 1 for the refinement step; if
816            // (u_top − v_top) ≥ 1, r̂ overflows and we skip the
817            // refinement (the multiply-subtract handles it).
818            let q = u128::MAX;
819            let (r, of) = u_next.overflowing_add(v_top);
820            // If overflow OR (u_top − v_top) ≥ 1 we treat r̂ as
821            // "above 2^128"; signal by returning r_overflow == true.
822            if of || u_top > v_top {
823                (q, u128::MAX) // sentinel; refinement loop will see r̂ "large" and not subtract.
824            } else {
825                (q, r)
826            }
827        } else {
828            mg_top.div_rem(u_top, u_next)
829        };
830
831        // Refinement: while q̂·v[n−2] > r̂·2^128 + u[j+n−2], decrement.
832        if n >= 2 {
833            let v_below = v[n - 2];
834            loop {
835                let (hi, lo) = mul_128(q_hat, v_below);
836                let rhs_lo = u[j + n - 2];
837                let rhs_hi = r_hat;
838                // Compare (hi, lo) vs (rhs_hi, rhs_lo).
839                if hi < rhs_hi || (hi == rhs_hi && lo <= rhs_lo) {
840                    break;
841                }
842                q_hat = q_hat.wrapping_sub(1);
843                let (new_r, of) = r_hat.overflowing_add(v_top);
844                if of {
845                    break;
846                }
847                r_hat = new_r;
848            }
849        }
850
851        // D4. Multiply-and-subtract: u[j..=j+n] -= q̂ · v[0..n].
852        let mut mul_carry: u128 = 0;
853        let mut borrow: u128 = 0;
854        for i in 0..n {
855            let (hi, lo) = mul_128(q_hat, v[i]);
856            let (prod_lo, c1) = lo.overflowing_add(mul_carry);
857            let new_mul_carry = hi + u128::from(c1);
858            let (s1, b1) = u[j + i].overflowing_sub(prod_lo);
859            let (s2, b2) = s1.overflowing_sub(borrow);
860            u[j + i] = s2;
861            borrow = u128::from(b1) + u128::from(b2);
862            mul_carry = new_mul_carry;
863        }
864        let (s1, b1) = u[j + n].overflowing_sub(mul_carry);
865        let (s2, b2) = s1.overflowing_sub(borrow);
866        u[j + n] = s2;
867        let final_borrow = u128::from(b1) + u128::from(b2);
868
869        // D5/D6. If multiply-subtract went negative, decrement q̂ and
870        // add v back.
871        if final_borrow != 0 {
872            q_hat = q_hat.wrapping_sub(1);
873            let mut carry: u128 = 0;
874            for i in 0..n {
875                let (s1, c1) = u[j + i].overflowing_add(v[i]);
876                let (s2, c2) = s1.overflowing_add(carry);
877                u[j + i] = s2;
878                carry = u128::from(c1) + u128::from(c2);
879            }
880            // Final carry cancels with the earlier borrow.
881            u[j + n] = u[j + n].wrapping_add(carry);
882        }
883
884        if j < quot.len() {
885            quot[j] = q_hat;
886        }
887    }
888
889    // D8. Denormalise the remainder: u[0..n] >> shift → rem.
890    if shift == 0 {
891        let copy_n = n.min(rem.len());
892        rem[..copy_n].copy_from_slice(&u[..copy_n]);
893    } else {
894        for i in 0..n {
895            if i < rem.len() {
896                let lo = u[i] >> shift;
897                let hi_into_lo = if i + 1 < n {
898                    u[i + 1] << (128 - shift)
899                } else {
900                    0
901                };
902                rem[i] = lo | hi_into_lo;
903            }
904        }
905    }
906}
907
908/// Burnikel–Ziegler recursive divide (MPI-I-98-1-022, 1998).
909///
910/// Splits an unbalanced `m+n / n` divide into a chain of balanced
911/// `2n / n` sub-divides, each of which recursively halves. The base
912/// case is [`limbs_divmod_knuth`] for divisors below `BZ_THRESHOLD`.
913/// On Karatsuba-multiplied operands BZ runs in `O(n^{1.58} · log n)`
914/// time vs Knuth's `O(n²)`.
915///
916/// For the widths this crate actually uses (Int256 … Int4096, ≤ 32
917/// limbs) the recursion only saves a constant factor over Knuth and
918/// the canonical `limbs_divmod` path stays untouched. BZ is exposed
919/// here so a bench-driven follow-up can promote it once a clear win
920/// shows up on the wide-tier divides.
921///
922/// Threshold: recurses only when both `num.len() ≥ 2·BZ_THRESHOLD`
923/// and `den.len() ≥ BZ_THRESHOLD`. Below that the cost of splitting
924/// dominates and Knuth wins outright.
925pub(crate) fn limbs_divmod_bz(
926    num: &[u128],
927    den: &[u128],
928    quot: &mut [u128],
929    rem: &mut [u128],
930) {
931    const BZ_THRESHOLD: usize = 8;
932
933    let mut n = den.len();
934    while n > 0 && den[n - 1] == 0 {
935        n -= 1;
936    }
937    assert!(n > 0, "limbs_divmod_bz: divide by zero");
938
939    let mut top = num.len();
940    while top > 0 && num[top - 1] == 0 {
941        top -= 1;
942    }
943
944    if n < BZ_THRESHOLD || top < 2 * n {
945        // Base case — Knuth handles every shape efficiently.
946        limbs_divmod_knuth(num, den, quot, rem);
947        return;
948    }
949
950    // BZ recursion: split the dividend into chunks of size `n` from
951    // the top, process each chunk with a `2n / n` sub-divide, carry
952    // the remainder forward. Each `2n / n` sub-divide itself does
953    // two `(3n/2) / n` calls via the recursive structure that — at
954    // these widths — Knuth handles inside its own quotient loop, so
955    // for now BZ here is essentially the chunked schoolbook outer
956    // loop with Knuth as the kernel. The full §3 two-by-one /
957    // three-by-two recursion is recorded in ALGORITHMS.md as the
958    // next layer to add once a bench shows it winning.
959    for q in quot.iter_mut() {
960        *q = 0;
961    }
962    for r in rem.iter_mut() {
963        *r = 0;
964    }
965
966    // Number of `n`-limb chunks in the dividend, rounded up so the
967    // top chunk may be short.
968    let chunks = top.div_ceil(n);
969    let mut carry = [0u128; SCRATCH_LIMBS];
970    let mut buf = [0u128; SCRATCH_LIMBS];
971    let mut q_chunk = [0u128; SCRATCH_LIMBS];
972    let mut r_chunk = [0u128; SCRATCH_LIMBS];
973
974    let mut idx = chunks;
975    while idx > 0 {
976        idx -= 1;
977        let lo = idx * n;
978        let hi = ((idx + 1) * n).min(top);
979        // buf = carry · 2^(n·128) + num[lo..hi]. carry holds the
980        // running remainder from the previous step (≤ n limbs).
981        buf.fill(0);
982        let chunk_len = hi - lo;
983        buf[..chunk_len].copy_from_slice(&num[lo..lo + chunk_len]);
984        buf[chunk_len..chunk_len + n].copy_from_slice(&carry[..n]);
985        let buf_len = chunk_len + n;
986        // Divide.
987        limbs_divmod_knuth(
988            &buf[..buf_len],
989            &den[..n],
990            &mut q_chunk[..buf_len],
991            &mut r_chunk[..n],
992        );
993        // Store quotient chunk.
994        let store_end = (lo + n).min(quot.len());
995        let store_len = store_end.saturating_sub(lo);
996        quot[lo..lo + store_len].copy_from_slice(&q_chunk[..store_len]);
997        // Carry the remainder.
998        carry[..n].copy_from_slice(&r_chunk[..n]);
999    }
1000    let rem_n = n.min(rem.len());
1001    rem[..rem_n].copy_from_slice(&carry[..rem_n]);
1002}
1003
1004/// `out = floor(sqrt(n))` via Newton's method. `out` is zeroed then
1005/// filled.
1006pub(crate) fn limbs_isqrt(n: &[u128], out: &mut [u128]) {
1007    for o in out.iter_mut() {
1008        *o = 0;
1009    }
1010    let bits = limbs_bit_len(n);
1011    if bits == 0 {
1012        return;
1013    }
1014    if bits <= 1 {
1015        out[0] = 1;
1016        return;
1017    }
1018    let work = n.len() + 1;
1019    debug_assert!(work <= SCRATCH_LIMBS, "wide-int isqrt scratch overflow");
1020    let mut x = [0u128; SCRATCH_LIMBS];
1021    let e = bits.div_ceil(2);
1022    x[(e / 128) as usize] |= 1u128 << (e % 128);
1023    loop {
1024        let mut q = [0u128; SCRATCH_LIMBS];
1025        let mut r = [0u128; SCRATCH_LIMBS];
1026        limbs_divmod(n, &x[..work], &mut q[..work], &mut r[..work]);
1027        limbs_add_assign(&mut q[..work], &x[..work]);
1028        let mut y = [0u128; SCRATCH_LIMBS];
1029        limbs_shr(&q[..work], 1, &mut y[..work]);
1030        if limbs_cmp(&y[..work], &x[..work]) >= 0 {
1031            break;
1032        }
1033        x = y;
1034    }
1035    let copy_len = if out.len() < work { out.len() } else { work };
1036    out[..copy_len].copy_from_slice(&x[..copy_len]);
1037}
1038
1039/// `limbs /= radix` in place, returning the remainder. `radix` must fit
1040/// a `u64` so the per-limb division stays within `u128`.
1041fn limbs_div_small(limbs: &mut [u128], radix: u128) -> u128 {
1042    let mut rem = 0u128;
1043    for limb in limbs.iter_mut().rev() {
1044        let hi = (*limb) >> 64;
1045        let lo = (*limb) & u128::from(u64::MAX);
1046        let acc_hi = (rem << 64) | hi;
1047        let q_hi = acc_hi / radix;
1048        let r1 = acc_hi % radix;
1049        let acc_lo = (r1 << 64) | lo;
1050        let q_lo = acc_lo / radix;
1051        rem = acc_lo % radix;
1052        *limb = (q_hi << 64) | q_lo;
1053    }
1054    rem
1055}
1056
1057/// Formats a limb slice into `buf` in the given radix (`2..=16`),
1058/// returning the written digit subslice. The slice is treated as an
1059/// unsigned magnitude.
1060pub(crate) fn limbs_fmt_into<'a>(
1061    limbs: &[u128],
1062    radix: u128,
1063    lower: bool,
1064    buf: &'a mut [u8],
1065) -> &'a str {
1066    let digits: &[u8] = if lower {
1067        b"0123456789abcdef"
1068    } else {
1069        b"0123456789ABCDEF"
1070    };
1071    if limbs_is_zero(limbs) {
1072        let last = buf.len() - 1;
1073        buf[last] = b'0';
1074        return core::str::from_utf8(&buf[last..]).unwrap();
1075    }
1076    let mut work = [0u128; SCRATCH_LIMBS];
1077    work[..limbs.len()].copy_from_slice(limbs);
1078    let wl = limbs.len();
1079    let mut pos = buf.len();
1080    while !limbs_is_zero(&work[..wl]) {
1081        let r = limbs_div_small(&mut work[..wl], radix);
1082        pos -= 1;
1083        buf[pos] = digits[r as usize];
1084    }
1085    core::str::from_utf8(&buf[pos..]).unwrap()
1086}
1087
1088// ─────────────────────────────────────────────────────────────────────
1089// u64 limb primitives.
1090//
1091// Drop-in shape replacements for the `[u128]`-based primitives above,
1092// but operating on `&[u64]` slices instead. The point: hardware has a
1093// native `u64 × u64 → u128` widening multiply and a native `u128 / u64`
1094// hardware divide, neither of which exists for `u128 × u128 → u256` or
1095// `u256 / u128`. The u128 primitives above are forced to soft-emulate
1096// both via the `mul_128` four-mul decomposition and the 128-iteration
1097// `div_2_by_1` bit-recovery loop. The u64 versions get the hardware
1098// instructions directly.
1099//
1100// During the in-progress storage migration these live alongside the
1101// u128 versions; the wrapper types (`$U` / `$S` in `decl_wide_int!`)
1102// continue to call the u128 entry points. A follow-up commit flips
1103// the storage to `[u64; 2 * $L]` and rewires every call site.
1104// ─────────────────────────────────────────────────────────────────────
1105
1106/// `a == 0`. u64-limb counterpart of [`limbs_is_zero`].
1107#[inline]
1108pub(crate) const fn limbs_is_zero_u64(a: &[u64]) -> bool {
1109    let mut i = 0;
1110    while i < a.len() {
1111        if a[i] != 0 {
1112            return false;
1113        }
1114        i += 1;
1115    }
1116    true
1117}
1118
1119/// `a == b` for two limb slices of possibly different lengths.
1120#[inline]
1121pub(crate) const fn limbs_eq_u64(a: &[u64], b: &[u64]) -> bool {
1122    let n = if a.len() > b.len() { a.len() } else { b.len() };
1123    let mut i = 0;
1124    while i < n {
1125        let av = if i < a.len() { a[i] } else { 0 };
1126        let bv = if i < b.len() { b[i] } else { 0 };
1127        if av != bv {
1128            return false;
1129        }
1130        i += 1;
1131    }
1132    true
1133}
1134
1135/// Three-way comparison `-1`/`0`/`1`.
1136#[inline]
1137pub(crate) const fn limbs_cmp_u64(a: &[u64], b: &[u64]) -> i32 {
1138    let n = if a.len() > b.len() { a.len() } else { b.len() };
1139    let mut i = n;
1140    while i > 0 {
1141        i -= 1;
1142        let av = if i < a.len() { a[i] } else { 0 };
1143        let bv = if i < b.len() { b[i] } else { 0 };
1144        if av < bv {
1145            return -1;
1146        }
1147        if av > bv {
1148            return 1;
1149        }
1150    }
1151    0
1152}
1153
1154/// Bit length (`0` for zero, else `floor(log2)+1`).
1155#[inline]
1156pub(crate) const fn limbs_bit_len_u64(a: &[u64]) -> u32 {
1157    let mut i = a.len();
1158    while i > 0 {
1159        i -= 1;
1160        if a[i] != 0 {
1161            return (i as u32) * 64 + (64 - a[i].leading_zeros());
1162        }
1163    }
1164    0
1165}
1166
1167/// `a += b`, returns carry out. `a.len() >= b.len()`.
1168#[inline]
1169pub(crate) const fn limbs_add_assign_u64(a: &mut [u64], b: &[u64]) -> bool {
1170    let mut carry: u64 = 0;
1171    let mut i = 0;
1172    while i < a.len() {
1173        let bv = if i < b.len() { b[i] } else { 0 };
1174        let (s1, c1) = a[i].overflowing_add(bv);
1175        let (s2, c2) = s1.overflowing_add(carry);
1176        a[i] = s2;
1177        carry = (c1 as u64) + (c2 as u64);
1178        i += 1;
1179    }
1180    carry != 0
1181}
1182
1183/// `a -= b`, returns borrow out. `a.len() >= b.len()`.
1184#[inline]
1185pub(crate) const fn limbs_sub_assign_u64(a: &mut [u64], b: &[u64]) -> bool {
1186    let mut borrow: u64 = 0;
1187    let mut i = 0;
1188    while i < a.len() {
1189        let bv = if i < b.len() { b[i] } else { 0 };
1190        let (d1, b1) = a[i].overflowing_sub(bv);
1191        let (d2, b2) = d1.overflowing_sub(borrow);
1192        a[i] = d2;
1193        borrow = (b1 as u64) + (b2 as u64);
1194        i += 1;
1195    }
1196    borrow != 0
1197}
1198
1199/// `out = a << shift`. `out` is zeroed then filled.
1200pub(crate) const fn limbs_shl_u64(a: &[u64], shift: u32, out: &mut [u64]) {
1201    let mut z = 0;
1202    while z < out.len() {
1203        out[z] = 0;
1204        z += 1;
1205    }
1206    let limb_shift = (shift / 64) as usize;
1207    let bit = shift % 64;
1208    let mut i = 0;
1209    while i < a.len() {
1210        let dst = i + limb_shift;
1211        if dst < out.len() {
1212            if bit == 0 {
1213                out[dst] |= a[i];
1214            } else {
1215                out[dst] |= a[i] << bit;
1216                if dst + 1 < out.len() {
1217                    out[dst + 1] |= a[i] >> (64 - bit);
1218                }
1219            }
1220        }
1221        i += 1;
1222    }
1223}
1224
1225/// `out = a >> shift`. `out` is zeroed then filled.
1226pub(crate) const fn limbs_shr_u64(a: &[u64], shift: u32, out: &mut [u64]) {
1227    let mut z = 0;
1228    while z < out.len() {
1229        out[z] = 0;
1230        z += 1;
1231    }
1232    let limb_shift = (shift / 64) as usize;
1233    let bit = shift % 64;
1234    let mut i = limb_shift;
1235    while i < a.len() {
1236        let dst = i - limb_shift;
1237        if dst < out.len() {
1238            if bit == 0 {
1239                out[dst] |= a[i];
1240            } else {
1241                out[dst] |= a[i] >> bit;
1242                if dst >= 1 {
1243                    out[dst - 1] |= a[i] << (64 - bit);
1244                }
1245            }
1246        }
1247        i += 1;
1248    }
1249}
1250
1251/// Single-bit left shift in place; returns the bit shifted out.
1252#[inline]
1253const fn limbs_shl1_u64(a: &mut [u64]) -> u64 {
1254    let mut carry: u64 = 0;
1255    let mut i = 0;
1256    while i < a.len() {
1257        let new_carry = a[i] >> 63;
1258        a[i] = (a[i] << 1) | carry;
1259        carry = new_carry;
1260        i += 1;
1261    }
1262    carry
1263}
1264
1265/// `true` if every limb above index 0 is zero — fits a single u64.
1266#[inline]
1267const fn limbs_fit_one_u64(a: &[u64]) -> bool {
1268    let mut i = 1;
1269    while i < a.len() {
1270        if a[i] != 0 {
1271            return false;
1272        }
1273        i += 1;
1274    }
1275    true
1276}
1277
1278/// `out = a · b` schoolbook. `out.len() >= a.len() + b.len()` and
1279/// `out` must be zeroed by the caller.
1280///
1281/// Inner step uses the native `u64 × u64 → u128` widening mul
1282/// (`MUL` + `UMULH` on x86-64 / aarch64), avoiding the 4-way
1283/// `mul_128` decomposition every u128 schoolbook step pays.
1284pub(crate) const fn limbs_mul_u64(a: &[u64], b: &[u64], out: &mut [u64]) {
1285    let mut i = 0;
1286    while i < a.len() {
1287        if a[i] != 0 {
1288            let mut carry: u64 = 0;
1289            let mut j = 0;
1290            while j < b.len() {
1291                if b[j] != 0 || carry != 0 {
1292                    let prod = (a[i] as u128) * (b[j] as u128);
1293                    let prod_lo = prod as u64;
1294                    let prod_hi = (prod >> 64) as u64;
1295                    let idx = i + j;
1296                    let (s1, c1) = out[idx].overflowing_add(prod_lo);
1297                    let (s2, c2) = s1.overflowing_add(carry);
1298                    out[idx] = s2;
1299                    carry = prod_hi + (c1 as u64) + (c2 as u64);
1300                }
1301                j += 1;
1302            }
1303            let mut idx = i + b.len();
1304            while carry != 0 && idx < out.len() {
1305                let (s, c) = out[idx].overflowing_add(carry);
1306                out[idx] = s;
1307                carry = c as u64;
1308                idx += 1;
1309            }
1310        }
1311        i += 1;
1312    }
1313}
1314
1315/// `quot = num / den`, `rem = num % den`, u64 limbs.
1316///
1317/// Hardware fast paths:
1318/// - both fit a single u64 → one native `u64 / u64`
1319/// - divisor fits a single u64 → native `u128 / u64` per dividend limb
1320/// - otherwise → bit shift-subtract (only reached when divisor is
1321///   multi-limb; the dispatcher routes those to Knuth instead)
1322pub(crate) const fn limbs_divmod_u64(
1323    num: &[u64],
1324    den: &[u64],
1325    quot: &mut [u64],
1326    rem: &mut [u64],
1327) {
1328    let mut z = 0;
1329    while z < quot.len() {
1330        quot[z] = 0;
1331        z += 1;
1332    }
1333    z = 0;
1334    while z < rem.len() {
1335        rem[z] = 0;
1336        z += 1;
1337    }
1338
1339    let den_one_limb = limbs_fit_one_u64(den);
1340
1341    // Fast path A: both fit a single u64 → hardware divide.
1342    if den_one_limb && limbs_fit_one_u64(num) {
1343        if !quot.is_empty() {
1344            quot[0] = num[0] / den[0];
1345        }
1346        if !rem.is_empty() {
1347            rem[0] = num[0] % den[0];
1348        }
1349        return;
1350    }
1351
1352    // Fast path B: divisor fits a single u64 — schoolbook base-2^64
1353    // long divide using the native u128/u64 hardware divide. Note this
1354    // is the SAME shape as the u128 path's Fast B (which manually
1355    // splits u128 into 64-bit halves), but here it's one hardware
1356    // divide per limb instead of two.
1357    if den_one_limb {
1358        let d = den[0];
1359        let mut r: u64 = 0;
1360        let mut top = num.len();
1361        while top > 0 && num[top - 1] == 0 {
1362            top -= 1;
1363        }
1364        let mut i = top;
1365        while i > 0 {
1366            i -= 1;
1367            let acc = ((r as u128) << 64) | (num[i] as u128);
1368            let q = (acc / (d as u128)) as u64;
1369            r = (acc % (d as u128)) as u64;
1370            if i < quot.len() {
1371                quot[i] = q;
1372            }
1373        }
1374        if !rem.is_empty() {
1375            rem[0] = r;
1376        }
1377        return;
1378    }
1379
1380    // General path: binary shift-subtract. Only reached for multi-limb
1381    // divisors when the dispatcher isn't routing to Knuth (i.e. in
1382    // const contexts where Knuth isn't available).
1383    let bits = limbs_bit_len_u64(num);
1384    let mut i = bits;
1385    while i > 0 {
1386        i -= 1;
1387        limbs_shl1_u64(rem);
1388        let bit = (num[(i / 64) as usize] >> (i % 64)) & 1;
1389        rem[0] |= bit;
1390        limbs_shl1_u64(quot);
1391        if limbs_cmp_u64(rem, den) >= 0 {
1392            limbs_sub_assign_u64(rem, den);
1393            quot[0] |= 1;
1394        }
1395    }
1396}
1397
1398/// Scratch capacity for the runtime u64-limb kernels — 144 u64 limbs
1399/// (9216 bits), matching the u128 path's 72-limb scratch.
1400// 288 u64 limbs = 18432 bits — covers the widest work integer in
1401// the crate (Int16384 used by D1231 cbrt, 256 u64 limbs) with isqrt
1402// scratch slack.
1403const SCRATCH_LIMBS_U64: usize = 288;
1404
1405/// Equal-length u64 multiplier dispatcher.
1406///
1407/// In testing against `examples/karabench.rs` u64 Karatsuba never won
1408/// over schoolbook at the tiers this crate actually emits — the
1409/// hardware `u64 × u64 → u128` widening multiply is single-cycle on
1410/// x86-64 Zen 4 / Intel Golden Cove, so schoolbook's n² muls finish
1411/// in fewer cycles than Karatsuba's 3 × (n/2)² + add/sub overhead at
1412/// n ≤ 64. We keep `limbs_mul_u64` as the only multiplier and reserve
1413/// the Karatsuba/Toom path for a future SIMD or wider-tier expansion.
1414pub(crate) fn limbs_mul_fast_u64(a: &[u64], b: &[u64], out: &mut [u64]) {
1415    limbs_mul_u64(a, b, out);
1416}
1417
1418/// Möller–Granlund 2-by-1 invariant divisor at u64 base.
1419///
1420/// Reference: same as [`MG2by1`] (Möller & Granlund 2011, Algorithm 4).
1421///
1422/// The u64 base implementation is materially simpler than its u128
1423/// sibling because the doubled type (u128) is *native* — every step
1424/// that the u128 path does via `mul_128` + carry-merge is just one
1425/// `u128` op here.
1426#[derive(Clone, Copy)]
1427pub(crate) struct MG2by1U64 {
1428    d: u64,
1429    v: u64,
1430}
1431
1432impl MG2by1U64 {
1433    /// `d` must be normalised: `d >> 63 == 1`.
1434    #[inline]
1435    pub(crate) const fn new(d: u64) -> Self {
1436        debug_assert!(d >> 63 == 1, "MG2by1U64::new: divisor must be normalised");
1437        // v = floor((B² - 1 - d·B) / d) where B = 2^64.
1438        // Numerator high = !d (= B-1-d), low = u64::MAX (= B-1).
1439        // High < d for normalised d, so native u128/u128 with the
1440        // divisor cast to u128 returns a quotient fitting u64.
1441        let num = ((!d as u128) << 64) | (u64::MAX as u128);
1442        let v = (num / (d as u128)) as u64;
1443        Self { d, v }
1444    }
1445
1446    /// Divide `(u1·B + u0)` by `d`. Requires `u1 < d`.
1447    #[inline]
1448    pub(crate) const fn div_rem(&self, u1: u64, u0: u64) -> (u64, u64) {
1449        debug_assert!(u1 < self.d, "MG2by1U64::div_rem: high word must be < divisor");
1450        // (q1, q0) = v·u1 + ⟨u1, u0⟩ as u128
1451        let q128 = (self.v as u128).wrapping_mul(u1 as u128)
1452            .wrapping_add(((u1 as u128) << 64) | (u0 as u128));
1453        let mut q1 = (q128 >> 64) as u64;
1454        let q0 = q128 as u64;
1455        q1 = q1.wrapping_add(1);
1456        let mut r = u0.wrapping_sub(q1.wrapping_mul(self.d));
1457        if r > q0 {
1458            q1 = q1.wrapping_sub(1);
1459            r = r.wrapping_add(self.d);
1460        }
1461        if r >= self.d {
1462            q1 = q1.wrapping_add(1);
1463            r = r.wrapping_sub(self.d);
1464        }
1465        (q1, r)
1466    }
1467}
1468
1469/// Möller–Granlund 3-by-2 invariant divisor at u64 base.
1470///
1471/// Divides `(n2·B² + n1·B + n0)` by `(d1·B + d0)` for a normalised
1472/// 2-limb divisor (`d1`'s top bit set) using *two* limbs of divisor
1473/// information, returning a quotient that is exactly correct in one
1474/// pass — no refinement loop is needed in the Knuth Algorithm D
1475/// caller. Compared to [`MG2by1U64`] + the historic Knuth refinement
1476/// loop, the 3-by-2 form trades:
1477///
1478/// - +1 hardware multiply per call (the d0·q step), against
1479/// - up to 2 refinement-loop iterations per quotient limb saved.
1480///
1481/// Net win at every Knuth call with `n ≥ 2` divisor limbs.
1482///
1483/// Reference: Möller & Granlund 2011, Algorithm 5 (the divide) and
1484/// Algorithm 6 (the reciprocal precompute). `MG2by1U64` is the 2-by-1
1485/// cousin used by `limbs_divmod_knuth_u64`'s q̂ estimator.
1486#[derive(Clone, Copy)]
1487pub(crate) struct MG3by2U64 {
1488    d1: u64,
1489    d0: u64,
1490    /// Reciprocal of the top divisor limb (same formula as MG2by1U64::v).
1491    dinv: u64,
1492}
1493
1494impl MG3by2U64 {
1495    /// Setup. `d1` must be normalised (`d1 >> 63 == 1`).
1496    ///
1497    /// Computes the *3-by-2* invariant reciprocal, which differs from
1498    /// the [`MG2by1U64`] 2-by-1 reciprocal by an extra refinement step
1499    /// that accounts for `d0`. Without that refinement the algorithm
1500    /// fails on inputs where the divisor's low limb is large enough
1501    /// to push the q estimate over by more than the corrections can
1502    /// recover (test case: `n=(B-2, B-1, B-1)`, `d=(B-1, B-1)`, where
1503    /// the naive 2-by-1 reciprocal hands back q=0 instead of B-1).
1504    ///
1505    /// Reference: Möller & Granlund 2011, Algorithm 6 (the
1506    /// reciprocal refinement that accounts for `d0`).
1507    #[inline]
1508    pub(crate) const fn new(d1: u64, d0: u64) -> Self {
1509        debug_assert!(d1 >> 63 == 1, "MG3by2U64::new: top divisor limb must be normalised");
1510        // Step 1: 2-by-1 reciprocal of d1 alone.
1511        let num = ((!d1 as u128) << 64) | (u64::MAX as u128);
1512        let mut v = (num / (d1 as u128)) as u64;
1513
1514        // Step 2: refine for d0. `p = d1·v + d0` (mod B). If the sum
1515        // overflows, v was over-estimated → decrement.
1516        let mut p = d1.wrapping_mul(v).wrapping_add(d0);
1517        if p < d0 {
1518            v = v.wrapping_sub(1);
1519            let mask = if p >= d1 { u64::MAX } else { 0 };
1520            p = p.wrapping_sub(d1);
1521            v = v.wrapping_add(mask);
1522            p = p.wrapping_sub(mask & d1);
1523        }
1524
1525        // Step 3: account for d0·v. `(t1, t0) = d0·v`; check if
1526        // `p + t1` overflows; one or two more decrements may be
1527        // required.
1528        let prod = (d0 as u128) * (v as u128);
1529        let t1 = (prod >> 64) as u64;
1530        let t0 = prod as u64;
1531        let (new_p, carry) = p.overflowing_add(t1);
1532        let _p_final = new_p;
1533        if carry {
1534            v = v.wrapping_sub(1);
1535            if new_p >= d1 && (new_p > d1 || t0 >= d0) {
1536                v = v.wrapping_sub(1);
1537            }
1538        }
1539
1540        Self { d1, d0, dinv: v }
1541    }
1542
1543    /// Divide `(n2·B² + n1·B + n0)` by `(d1·B + d0)`. Requires
1544    /// `(n2, n1) < (d1, d0)` so the quotient fits a single u64.
1545    /// Returns `(q, r1, r0)` where the remainder is `r1·B + r0`.
1546    ///
1547    /// Algorithm decomposition (Möller & Granlund 2011, Algorithm 5):
1548    /// 1. Initial `q` from a 2-by-1 divide of `(n2, n1)` by `d1` via
1549    ///    the precomputed reciprocal `dinv`.
1550    /// 2. Subtract `(q·d1, q·d0)` from `(n1, n0)`; this stages the
1551    ///    candidate remainder `(r1, r0)`.
1552    /// 3. Two add-back corrections that fire 0–1 times each: the
1553    ///    first catches `q` over by 1, the second catches the rare
1554    ///    `q` over by 2 (only possible if the initial 2-by-1 reciprocal
1555    ///    over-shot).
1556    #[inline]
1557    pub(crate) const fn div_rem(&self, n2: u64, n1: u64, n0: u64) -> (u64, u64, u64) {
1558        debug_assert!(
1559            n2 < self.d1 || (n2 == self.d1 && n1 < self.d0),
1560            "MG3by2U64::div_rem: numerator high pair must be < divisor"
1561        );
1562
1563        // Step 1: q estimate from (n2, n1) / d1 via dinv.
1564        // (q_hi, q_lo) = n2 * dinv + (n2, n1) — overflow into a 257th
1565        // bit is fine, the mask-based correction (step 4a) recovers
1566        // from it without needing to materialise the lost bit.
1567        let prod = (n2 as u128).wrapping_mul(self.dinv as u128)
1568            .wrapping_add(((n2 as u128) << 64) | (n1 as u128));
1569        let mut q = (prod >> 64) as u64;
1570        let q_lo = prod as u64;
1571
1572        // Step 2a: r1 = n1 - q·d1 (mod B).
1573        let mut r1 = n1.wrapping_sub(q.wrapping_mul(self.d1));
1574
1575        // Step 2b: (r1, r0) = (r1, n0) - (d1, d0).
1576        let r256 = (((r1 as u128) << 64) | (n0 as u128))
1577            .wrapping_sub(((self.d1 as u128) << 64) | (self.d0 as u128));
1578        r1 = (r256 >> 64) as u64;
1579        let mut r0 = r256 as u64;
1580
1581        // Step 2c: (r1, r0) -= d0·q (mod B²).
1582        let t = (self.d0 as u128).wrapping_mul(q as u128);
1583        let r256 = (((r1 as u128) << 64) | (r0 as u128)).wrapping_sub(t);
1584        r1 = (r256 >> 64) as u64;
1585        r0 = r256 as u64;
1586
1587        // Step 3: q += 1; provisional.
1588        q = q.wrapping_add(1);
1589
1590        // Step 4a: first conditional correction.
1591        // If r1 >= q_lo (in u64 numeric), the provisional q was over
1592        // by 1; decrement q and add (d1, d0) back to the remainder.
1593        // Branchless via mask.
1594        let mask = if r1 >= q_lo { u64::MAX } else { 0 };
1595        q = q.wrapping_add(mask); // adds u64::MAX = -1.
1596        let add = ((mask & self.d1) as u128) << 64 | ((mask & self.d0) as u128);
1597        let r256 = (((r1 as u128) << 64) | (r0 as u128)).wrapping_add(add);
1598        r1 = (r256 >> 64) as u64;
1599        r0 = r256 as u64;
1600
1601        // Step 4b: final correction (rare).
1602        // If (r1, r0) >= (d1, d0), q was *still* off by 1; bump q and
1603        // subtract the divisor once more.
1604        if r1 > self.d1 || (r1 == self.d1 && r0 >= self.d0) {
1605            q = q.wrapping_add(1);
1606            let r256 = (((r1 as u128) << 64) | (r0 as u128))
1607                .wrapping_sub(((self.d1 as u128) << 64) | (self.d0 as u128));
1608            r1 = (r256 >> 64) as u64;
1609            r0 = r256 as u64;
1610        }
1611
1612        (q, r1, r0)
1613    }
1614}
1615
1616/// Runtime divide dispatcher at u64 base.
1617pub(crate) fn limbs_divmod_dispatch_u64(
1618    num: &[u64],
1619    den: &[u64],
1620    quot: &mut [u64],
1621    rem: &mut [u64],
1622) {
1623    const BZ_THRESHOLD_U64: usize = 16; // doubled from u128 path's 8.
1624
1625    let mut n = den.len();
1626    while n > 0 && den[n - 1] == 0 {
1627        n -= 1;
1628    }
1629    assert!(n > 0, "limbs_divmod_dispatch_u64: divide by zero");
1630
1631    let mut top = num.len();
1632    while top > 0 && num[top - 1] == 0 {
1633        top -= 1;
1634    }
1635
1636    // Single-limb divisor: defer to const limbs_divmod_u64 (its Fast B
1637    // is one hardware u128/u64 per dividend limb — already optimal).
1638    if n == 1 {
1639        limbs_divmod_u64(num, den, quot, rem);
1640        return;
1641    }
1642
1643    if n >= BZ_THRESHOLD_U64 && top >= 2 * n {
1644        limbs_divmod_bz_u64(num, den, quot, rem);
1645    } else {
1646        limbs_divmod_knuth_u64(num, den, quot, rem);
1647    }
1648}
1649
1650/// Knuth Algorithm D at base 2^64.
1651///
1652/// Same structure as [`limbs_divmod_knuth`] but every limb is a u64
1653/// and the q̂ estimator uses [`MG2by1U64`]. The multiply-subtract pass
1654/// uses native `u64 × u64 → u128`, which collapses one carry-merge
1655/// layer compared to the u128 version's `mul_128`.
1656pub(crate) fn limbs_divmod_knuth_u64(
1657    num: &[u64],
1658    den: &[u64],
1659    quot: &mut [u64],
1660    rem: &mut [u64],
1661) {
1662    for q in quot.iter_mut() {
1663        *q = 0;
1664    }
1665    for r in rem.iter_mut() {
1666        *r = 0;
1667    }
1668
1669    let mut n = den.len();
1670    while n > 0 && den[n - 1] == 0 {
1671        n -= 1;
1672    }
1673    assert!(n > 0, "limbs_divmod_knuth_u64: divide by zero");
1674
1675    let mut top = num.len();
1676    while top > 0 && num[top - 1] == 0 {
1677        top -= 1;
1678    }
1679    if top < n {
1680        let copy_n = num.len().min(rem.len());
1681        let mut i = 0;
1682        while i < copy_n {
1683            rem[i] = num[i];
1684            i += 1;
1685        }
1686        return;
1687    }
1688
1689    let shift = den[n - 1].leading_zeros();
1690    let mut u = [0u64; SCRATCH_LIMBS_U64];
1691    let mut v = [0u64; SCRATCH_LIMBS_U64];
1692    debug_assert!(top < SCRATCH_LIMBS_U64 && n <= SCRATCH_LIMBS_U64);
1693
1694    if shift == 0 {
1695        u[..top].copy_from_slice(&num[..top]);
1696        u[top] = 0;
1697        v[..n].copy_from_slice(&den[..n]);
1698    } else {
1699        let mut carry: u64 = 0;
1700        for i in 0..top {
1701            let val = num[i];
1702            u[i] = (val << shift) | carry;
1703            carry = val >> (64 - shift);
1704        }
1705        u[top] = carry;
1706        carry = 0;
1707        for i in 0..n {
1708            let val = den[i];
1709            v[i] = (val << shift) | carry;
1710            carry = val >> (64 - shift);
1711        }
1712    }
1713
1714    let m_plus_n = if u[top] != 0 { top + 1 } else { top };
1715    debug_assert!(m_plus_n >= n);
1716    let m = m_plus_n - n;
1717
1718    // MG 2-by-1 q̂ estimator + refinement loop. We previously
1719    // experimented with MG 3-by-2 (which would absorb the refinement
1720    // into a single call) but it lost in the bench: for decimal
1721    // divisors the refinement loop almost never fires, and the
1722    // 3-by-2's extra per-call multiply costs more than the 0–1
1723    // refinement iterations it would eliminate. MG3by2U64 stays
1724    // available in the module for future use cases with arbitrary
1725    // divisors.
1726    let mg_top = MG2by1U64::new(v[n - 1]);
1727
1728    let mut j_plus_one = m + 1;
1729    while j_plus_one > 0 {
1730        j_plus_one -= 1;
1731        let j = j_plus_one;
1732
1733        let u_top = u[j + n];
1734        let u_next = u[j + n - 1];
1735        let v_top = v[n - 1];
1736
1737        let (mut q_hat, mut r_hat) = if u_top >= v_top {
1738            let q = u64::MAX;
1739            let (r, of) = u_next.overflowing_add(v_top);
1740            if of || u_top > v_top {
1741                (q, u64::MAX)
1742            } else {
1743                (q, r)
1744            }
1745        } else {
1746            mg_top.div_rem(u_top, u_next)
1747        };
1748
1749        if n >= 2 {
1750            let v_below = v[n - 2];
1751            loop {
1752                let prod = (q_hat as u128) * (v_below as u128);
1753                let hi = (prod >> 64) as u64;
1754                let lo = prod as u64;
1755                let rhs_lo = u[j + n - 2];
1756                let rhs_hi = r_hat;
1757                if hi < rhs_hi || (hi == rhs_hi && lo <= rhs_lo) {
1758                    break;
1759                }
1760                q_hat = q_hat.wrapping_sub(1);
1761                let (new_r, of) = r_hat.overflowing_add(v_top);
1762                if of {
1763                    break;
1764                }
1765                r_hat = new_r;
1766            }
1767        }
1768
1769        // D4. u[j..=j+n] -= q̂ · v[0..n]
1770        let mut mul_carry: u64 = 0;
1771        let mut borrow: u64 = 0;
1772        for i in 0..n {
1773            let prod = (q_hat as u128) * (v[i] as u128);
1774            let prod_lo = prod as u64;
1775            let prod_hi = (prod >> 64) as u64;
1776            let (s_prod, c1) = prod_lo.overflowing_add(mul_carry);
1777            let new_mul_carry = prod_hi + (c1 as u64);
1778            let (s1, b1) = u[j + i].overflowing_sub(s_prod);
1779            let (s2, b2) = s1.overflowing_sub(borrow);
1780            u[j + i] = s2;
1781            borrow = (b1 as u64) + (b2 as u64);
1782            mul_carry = new_mul_carry;
1783        }
1784        let (s1, b1) = u[j + n].overflowing_sub(mul_carry);
1785        let (s2, b2) = s1.overflowing_sub(borrow);
1786        u[j + n] = s2;
1787        let final_borrow = (b1 as u64) + (b2 as u64);
1788
1789        if final_borrow != 0 {
1790            q_hat = q_hat.wrapping_sub(1);
1791            let mut carry: u64 = 0;
1792            for i in 0..n {
1793                let (s1, c1) = u[j + i].overflowing_add(v[i]);
1794                let (s2, c2) = s1.overflowing_add(carry);
1795                u[j + i] = s2;
1796                carry = (c1 as u64) + (c2 as u64);
1797            }
1798            u[j + n] = u[j + n].wrapping_add(carry);
1799        }
1800
1801        if j < quot.len() {
1802            quot[j] = q_hat;
1803        }
1804    }
1805
1806    if shift == 0 {
1807        let copy_n = n.min(rem.len());
1808        rem[..copy_n].copy_from_slice(&u[..copy_n]);
1809    } else {
1810        for i in 0..n {
1811            if i < rem.len() {
1812                let lo = u[i] >> shift;
1813                let hi_into_lo = if i + 1 < n {
1814                    u[i + 1] << (64 - shift)
1815                } else {
1816                    0
1817                };
1818                rem[i] = lo | hi_into_lo;
1819            }
1820        }
1821    }
1822}
1823
1824/// Burnikel–Ziegler outer chunking, u64 base.
1825pub(crate) fn limbs_divmod_bz_u64(
1826    num: &[u64],
1827    den: &[u64],
1828    quot: &mut [u64],
1829    rem: &mut [u64],
1830) {
1831    const BZ_THRESHOLD_U64: usize = 16;
1832
1833    let mut n = den.len();
1834    while n > 0 && den[n - 1] == 0 {
1835        n -= 1;
1836    }
1837    assert!(n > 0, "limbs_divmod_bz_u64: divide by zero");
1838
1839    let mut top = num.len();
1840    while top > 0 && num[top - 1] == 0 {
1841        top -= 1;
1842    }
1843
1844    if n < BZ_THRESHOLD_U64 || top < 2 * n {
1845        limbs_divmod_knuth_u64(num, den, quot, rem);
1846        return;
1847    }
1848
1849    for q in quot.iter_mut() {
1850        *q = 0;
1851    }
1852    for r in rem.iter_mut() {
1853        *r = 0;
1854    }
1855
1856    let chunks = top.div_ceil(n);
1857    let mut carry = [0u64; SCRATCH_LIMBS_U64];
1858    let mut buf = [0u64; SCRATCH_LIMBS_U64];
1859    let mut q_chunk = [0u64; SCRATCH_LIMBS_U64];
1860    let mut r_chunk = [0u64; SCRATCH_LIMBS_U64];
1861
1862    let mut idx = chunks;
1863    while idx > 0 {
1864        idx -= 1;
1865        let lo = idx * n;
1866        let hi = ((idx + 1) * n).min(top);
1867        buf.fill(0);
1868        let chunk_len = hi - lo;
1869        buf[..chunk_len].copy_from_slice(&num[lo..lo + chunk_len]);
1870        buf[chunk_len..chunk_len + n].copy_from_slice(&carry[..n]);
1871        let buf_len = chunk_len + n;
1872        limbs_divmod_knuth_u64(
1873            &buf[..buf_len],
1874            &den[..n],
1875            &mut q_chunk[..buf_len],
1876            &mut r_chunk[..n],
1877        );
1878        let store_end = (lo + n).min(quot.len());
1879        let store_len = store_end.saturating_sub(lo);
1880        quot[lo..lo + store_len].copy_from_slice(&q_chunk[..store_len]);
1881        carry[..n].copy_from_slice(&r_chunk[..n]);
1882    }
1883    let rem_n = n.min(rem.len());
1884    rem[..rem_n].copy_from_slice(&carry[..rem_n]);
1885}
1886
1887/// `out = floor(sqrt(n))`. Newton iteration on top of the runtime
1888/// divide dispatcher.
1889///
1890/// History: this routine previously called the *const* [`limbs_divmod_u64`]
1891/// per iteration, which routes multi-limb divisors through the
1892/// O(bits²) shift-subtract path. At Int4096 (n=64 u64 limbs) that
1893/// dominates wall time — Newton converges in ~log₂(b) ≈ 12 iterations,
1894/// each one a `~65k`-limb-op divmod. Switching to
1895/// [`limbs_divmod_dispatch_u64`] gets Knuth-base-2⁶⁴ per iteration
1896/// (~`~32²` = 1024 limb-ops), worth ~40× on D307 sqrt.
1897pub(crate) fn limbs_isqrt_u64(n: &[u64], out: &mut [u64]) {
1898    for o in out.iter_mut() {
1899        *o = 0;
1900    }
1901    let bits = limbs_bit_len_u64(n);
1902    if bits == 0 {
1903        return;
1904    }
1905    if bits <= 1 {
1906        out[0] = 1;
1907        return;
1908    }
1909    let work = n.len() + 1;
1910    debug_assert!(work <= SCRATCH_LIMBS_U64, "isqrt scratch overflow");
1911    let mut x = [0u64; SCRATCH_LIMBS_U64];
1912    let e = bits.div_ceil(2);
1913    x[(e / 64) as usize] |= 1u64 << (e % 64);
1914    loop {
1915        let mut q = [0u64; SCRATCH_LIMBS_U64];
1916        let mut r = [0u64; SCRATCH_LIMBS_U64];
1917        limbs_divmod_dispatch_u64(n, &x[..work], &mut q[..work], &mut r[..work]);
1918        limbs_add_assign_u64(&mut q[..work], &x[..work]);
1919        let mut y = [0u64; SCRATCH_LIMBS_U64];
1920        limbs_shr_u64(&q[..work], 1, &mut y[..work]);
1921        if limbs_cmp_u64(&y[..work], &x[..work]) >= 0 {
1922            break;
1923        }
1924        x = y;
1925    }
1926    let copy_len = if out.len() < work { out.len() } else { work };
1927    out[..copy_len].copy_from_slice(&x[..copy_len]);
1928}
1929
1930/// `limbs /= radix` in place, returning the remainder. `radix` must
1931/// be a u64 (so the per-limb divide stays inside `u128 / u64`).
1932fn limbs_div_small_u64(limbs: &mut [u64], radix: u64) -> u64 {
1933    let mut rem: u64 = 0;
1934    for limb in limbs.iter_mut().rev() {
1935        let acc = ((rem as u128) << 64) | (*limb as u128);
1936        *limb = (acc / (radix as u128)) as u64;
1937        rem = (acc % (radix as u128)) as u64;
1938    }
1939    rem
1940}
1941
1942/// Format a u64 limb slice into `buf` in the given radix (`2..=16`).
1943pub(crate) fn limbs_fmt_into_u64<'a>(
1944    limbs: &[u64],
1945    radix: u64,
1946    lower: bool,
1947    buf: &'a mut [u8],
1948) -> &'a str {
1949    let digits: &[u8] = if lower {
1950        b"0123456789abcdef"
1951    } else {
1952        b"0123456789ABCDEF"
1953    };
1954    if limbs_is_zero_u64(limbs) {
1955        let last = buf.len() - 1;
1956        buf[last] = b'0';
1957        return core::str::from_utf8(&buf[last..]).unwrap();
1958    }
1959    let mut work = [0u64; SCRATCH_LIMBS_U64];
1960    work[..limbs.len()].copy_from_slice(limbs);
1961    let wl = limbs.len();
1962    let mut pos = buf.len();
1963    while !limbs_is_zero_u64(&work[..wl]) {
1964        let r = limbs_div_small_u64(&mut work[..wl], radix);
1965        pos -= 1;
1966        buf[pos] = digits[r as usize];
1967    }
1968    core::str::from_utf8(&buf[pos..]).unwrap()
1969}
1970
1971/// Signed three-way compare for u64-limb magnitudes with signs.
1972#[inline]
1973pub(crate) const fn scmp_u64(a_neg: bool, a: &[u64], b_neg: bool, b: &[u64]) -> i32 {
1974    match (a_neg, b_neg) {
1975        (true, false) => -1,
1976        (false, true) => 1,
1977        _ => limbs_cmp_u64(a, b),
1978    }
1979}
1980
1981// ─────────────────────────────────────────────────────────────────────
1982// End of u64 primitives.
1983// ─────────────────────────────────────────────────────────────────────
1984
1985mod macros;
1986use macros::decl_wide_int;
1987
1988
1989/// Signed three-way comparison of two magnitude-limb slices given their
1990/// signs. Returns `-1` / `0` / `1`.
1991#[inline]
1992pub(crate) const fn scmp(a_neg: bool, a: &[u128], b_neg: bool, b: &[u128]) -> i32 {
1993    match (a_neg, b_neg) {
1994        (true, false) => -1,
1995        (false, true) => 1,
1996        _ => limbs_cmp(a, b),
1997    }
1998}
1999
2000/// A signed integer that can be decomposed into a magnitude + sign and
2001/// rebuilt from one — the basis of `wide_cast` (widen / narrow between
2002/// any two widths, or between a wide integer and a primitive
2003/// `i128` / `i64` / `u128`). u64-limb representation throughout, so
2004/// every wide-int's magnitude buffer is directly compatible without
2005/// boundary conversion.
2006pub(crate) trait WideInt: Copy {
2007    /// Magnitude limbs (little-endian u64, zero-padded to 128) and sign.
2008    /// 128 u64 limbs = 8192 bits, comfortably above the widest type
2009    /// the crate ships (Int4096, which is 64 u64 limbs).
2010    fn to_mag_sign(self) -> ([u64; 288], bool);
2011    /// Rebuilds from a magnitude limb slice and a sign, truncating
2012    /// the magnitude to this type's width.
2013    fn from_mag_sign(mag: &[u64], negative: bool) -> Self;
2014}
2015
2016/// Implements `WideInt` for a signed primitive integer. The
2017/// magnitude is split into two u64 limbs (low, high) regardless of
2018/// the source primitive's width — for `i64` the high limb is always
2019/// zero; for `i128` the split carries the upper 64 bits.
2020macro_rules! impl_wideint_signed_prim {
2021    ($($t:ty),*) => {$(
2022        impl WideInt for $t {
2023            #[inline]
2024            fn to_mag_sign(self) -> ([u64; 288], bool) {
2025                let mut out = [0u64; 288];
2026                let mag = self.unsigned_abs() as u128;
2027                out[0] = mag as u64;
2028                out[1] = (mag >> 64) as u64;
2029                (out, self < 0)
2030            }
2031            #[inline]
2032            fn from_mag_sign(mag: &[u64], negative: bool) -> $t {
2033                let lo = mag.first().copied().unwrap_or(0) as u128;
2034                let hi = mag.get(1).copied().unwrap_or(0) as u128;
2035                let combined = lo | (hi << 64);
2036                let m = combined as $t;
2037                if negative { m.wrapping_neg() } else { m }
2038            }
2039        }
2040    )*};
2041}
2042impl_wideint_signed_prim!(i8, i16, i32, i64, i128);
2043
2044impl WideInt for u128 {
2045    #[inline]
2046    fn to_mag_sign(self) -> ([u64; 288], bool) {
2047        let mut out = [0u64; 288];
2048        out[0] = self as u64;
2049        out[1] = (self >> 64) as u64;
2050        (out, false)
2051    }
2052    #[inline]
2053    fn from_mag_sign(mag: &[u64], _negative: bool) -> u128 {
2054        let lo = mag.first().copied().unwrap_or(0) as u128;
2055        let hi = mag.get(1).copied().unwrap_or(0) as u128;
2056        lo | (hi << 64)
2057    }
2058}
2059
2060/// Widening / narrowing cast between any two `WideInt` types via a
2061/// shared magnitude + sign representation.
2062#[inline]
2063pub(crate) fn wide_cast<S: WideInt, T: WideInt>(src: S) -> T {
2064    let (mag, negative) = src.to_mag_sign();
2065    T::from_mag_sign(&mag, negative)
2066}
2067
2068// The concrete wide integer type pairs. The 256/512/1024-bit widths
2069// back the wide decimal tiers; 2048/4096-bit widths are the
2070// strict-transcendental work integers.
2071// $L = u64 limb count; $D = doubled (= 2 · $L) for widening
2072// products. Each Int*'s name encodes the bit width = $L · 64.
2073decl_wide_int!(Uint192, Int192, 3, 6);
2074decl_wide_int!(Uint256, Int256, 4, 8);
2075decl_wide_int!(Uint384, Int384, 6, 12);
2076decl_wide_int!(Uint512, Int512, 8, 16);
2077decl_wide_int!(Uint768, Int768, 12, 24);
2078decl_wide_int!(Uint1024, Int1024, 16, 32);
2079decl_wide_int!(Uint1536, Int1536, 24, 48);
2080decl_wide_int!(Uint2048, Int2048, 32, 64);
2081decl_wide_int!(Uint3072, Int3072, 48, 96);
2082decl_wide_int!(Uint4096, Int4096, 64, 128);
2083decl_wide_int!(Uint6144, Int6144, 96, 192);
2084decl_wide_int!(Uint8192, Int8192, 128, 256);
2085decl_wide_int!(Uint12288, Int12288, 192, 384);
2086decl_wide_int!(Uint16384, Int16384, 256, 512);
2087
2088// Short aliases used by the decimal-tier macros (replacing the former
2089// `crate::wide` re-export shim). The signed alias is exposed at each
2090// width where it backs storage *or* serves as the next-width mul/div
2091// widening step; the unsigned alias only where `Display`'s magnitude
2092// path needs it. The feature gates mirror the call-site features.
2093// Tier aliases — each width gets an `I*` (signed) alias when it
2094// backs storage or serves as a mul/div widening step for some tier,
2095// and a matching `U*` (unsigned) when `Display`'s magnitude path
2096// needs it.
2097#[cfg(any(feature = "d56", feature = "wide"))]
2098pub(crate) use self::{Int192 as I192, Uint192 as U192};
2099#[cfg(any(feature = "d56", feature = "d76", feature = "wide"))]
2100pub(crate) use self::Int384 as I384;
2101#[cfg(any(feature = "d114", feature = "wide"))]
2102pub(crate) use self::Uint384 as U384;
2103#[cfg(any(feature = "d76", feature = "wide"))]
2104pub(crate) use self::{Int256 as I256, Uint256 as U256};
2105#[cfg(any(feature = "d76", feature = "d114", feature = "d153", feature = "wide"))]
2106pub(crate) use self::Int512 as I512;
2107#[cfg(any(feature = "d153", feature = "wide"))]
2108pub(crate) use self::Uint512 as U512;
2109#[cfg(any(feature = "d114", feature = "d153", feature = "d230", feature = "wide"))]
2110pub(crate) use self::Int768 as I768;
2111#[cfg(any(feature = "d230", feature = "wide"))]
2112pub(crate) use self::Uint768 as U768;
2113#[cfg(any(feature = "d153", feature = "d230", feature = "d307", feature = "wide", feature = "x-wide"))]
2114pub(crate) use self::Int1024 as I1024;
2115#[cfg(any(feature = "d230", feature = "d307", feature = "d461", feature = "wide", feature = "x-wide"))]
2116pub(crate) use self::Int1536 as I1536;
2117#[cfg(any(feature = "d461", feature = "x-wide"))]
2118pub(crate) use self::Uint1536 as U1536;
2119#[cfg(any(feature = "d307", feature = "d461", feature = "d615", feature = "wide", feature = "x-wide"))]
2120pub(crate) use self::{Int2048 as I2048, Uint1024 as U1024};
2121#[cfg(any(feature = "d615", feature = "x-wide"))]
2122pub(crate) use self::Uint2048 as U2048;
2123#[cfg(any(feature = "d461", feature = "d615", feature = "d923", feature = "x-wide", feature = "xx-wide"))]
2124pub(crate) use self::Int3072 as I3072;
2125#[cfg(any(feature = "d923", feature = "xx-wide"))]
2126pub(crate) use self::Uint3072 as U3072;
2127#[cfg(any(feature = "d615", feature = "d923", feature = "d1231", feature = "x-wide", feature = "xx-wide"))]
2128pub(crate) use self::Int4096 as I4096;
2129#[cfg(any(feature = "d1231", feature = "xx-wide"))]
2130pub(crate) use self::Uint4096 as U4096;
2131#[cfg(any(feature = "d923", feature = "d1231", feature = "xx-wide"))]
2132pub(crate) use self::Int6144 as I6144;
2133#[cfg(any(feature = "d1231", feature = "xx-wide"))]
2134pub(crate) use self::Int8192 as I8192;
2135#[cfg(any(feature = "d923", feature = "xx-wide"))]
2136#[allow(unused_imports)]
2137pub(crate) use self::Int12288 as I12288;
2138#[cfg(any(feature = "d1231", feature = "xx-wide"))]
2139#[allow(unused_imports)]
2140pub(crate) use self::Int16384 as I16384;
2141
2142#[cfg(test)]
2143mod karatsuba_tests {
2144    use super::*;
2145
2146    /// Karatsuba and schoolbook must agree bit-for-bit on every
2147    /// equal-length input that meets the threshold.
2148    #[test]
2149    fn karatsuba_matches_schoolbook_at_n16() {
2150        let a: [u128; 16] = core::array::from_fn(|i| (i as u128) * 0xdead_beef + 1);
2151        let b: [u128; 16] = core::array::from_fn(|i| 0xcafe_babe ^ ((i as u128) << 5));
2152        let mut s = [0u128; 32];
2153        let mut k = [0u128; 32];
2154        limbs_mul(&a, &b, &mut s);
2155        limbs_mul_karatsuba(&a, &b, &mut k);
2156        assert_eq!(s, k);
2157    }
2158
2159    #[test]
2160    fn karatsuba_matches_schoolbook_at_n32() {
2161        let a: [u128; 32] = core::array::from_fn(|i| (i as u128).wrapping_mul(0x1234_5678_9abc));
2162        let b: [u128; 32] = core::array::from_fn(|i| (i as u128 + 1).wrapping_mul(0xfedc_ba98));
2163        let mut s = [0u128; 64];
2164        let mut k = [0u128; 64];
2165        limbs_mul(&a, &b, &mut s);
2166        limbs_mul_karatsuba(&a, &b, &mut k);
2167        assert_eq!(s, k);
2168    }
2169
2170    #[test]
2171    fn karatsuba_handles_zero_inputs() {
2172        let a = [0u128; 16];
2173        let b: [u128; 16] = core::array::from_fn(|i| (i as u128) + 1);
2174        let mut k = [0u128; 32];
2175        limbs_mul_karatsuba(&a, &b, &mut k);
2176        for o in &k {
2177            assert_eq!(*o, 0);
2178        }
2179    }
2180}
2181
2182#[cfg(test)]
2183mod hint_tests {
2184    use super::*;
2185
2186    #[test]
2187    fn signed_add_sub_neg() {
2188        let a = Int256::from_i128(5);
2189        let b = Int256::from_i128(3);
2190        assert_eq!(a.wrapping_add(b), Int256::from_i128(8));
2191        assert_eq!(a.wrapping_sub(b), Int256::from_i128(2));
2192        assert_eq!(b.wrapping_sub(a), Int256::from_i128(-2));
2193        assert_eq!(a.negate(), Int256::from_i128(-5));
2194        assert_eq!(Int256::ZERO.negate(), Int256::ZERO);
2195    }
2196
2197    #[test]
2198    fn signed_mul_div_rem() {
2199        let six = Int512::from_i128(6);
2200        let two = Int512::from_i128(2);
2201        let three = Int512::from_i128(3);
2202        assert_eq!(six.wrapping_mul(three), Int512::from_i128(18));
2203        assert_eq!(six.wrapping_div(two), three);
2204        assert_eq!(Int512::from_i128(7).wrapping_rem(three), Int512::from_i128(1));
2205        assert_eq!(Int512::from_i128(-7).wrapping_rem(three), Int512::from_i128(-1));
2206        assert_eq!(six.negate().wrapping_mul(three), Int512::from_i128(-18));
2207    }
2208
2209    #[test]
2210    fn checked_overflow() {
2211        assert_eq!(Int256::MAX.checked_add(Int256::ONE), None);
2212        assert_eq!(Int256::MIN.checked_sub(Int256::ONE), None);
2213        assert_eq!(Int256::MIN.checked_neg(), None);
2214        assert_eq!(
2215            Int256::from_i128(2).checked_add(Int256::from_i128(3)),
2216            Some(Int256::from_i128(5))
2217        );
2218    }
2219
2220    #[test]
2221    fn from_str_and_pow() {
2222        let ten = Int1024::from_str_radix("10", 10).unwrap();
2223        assert_eq!(ten, Int1024::from_i128(10));
2224        assert_eq!(ten.pow(3), Int1024::from_i128(1000));
2225        let big = Int1024::from_str_radix("10", 10).unwrap().pow(40);
2226        let from_str = Int1024::from_str_radix(
2227            "10000000000000000000000000000000000000000",
2228            10,
2229        )
2230        .unwrap();
2231        assert_eq!(big, from_str);
2232        assert_eq!(Int256::from_str_radix("-42", 10).unwrap(), Int256::from_i128(-42));
2233    }
2234
2235    #[test]
2236    fn ordering_and_resize() {
2237        assert!(Int256::from_i128(-1) < Int256::ZERO);
2238        assert!(Int256::MIN < Int256::MAX);
2239        let v = Int256::from_i128(-123_456_789);
2240        let wide: Int1024 = v.resize();
2241        let back: Int256 = wide.resize();
2242        assert_eq!(back, v);
2243        assert_eq!(wide, Int1024::from_i128(-123_456_789));
2244    }
2245
2246    #[test]
2247    fn isqrt_and_f64() {
2248        assert_eq!(Int512::from_i128(144).isqrt(), Int512::from_i128(12));
2249        assert_eq!(Int256::from_i128(1_000_000).as_f64(), 1_000_000.0);
2250        assert_eq!(Int256::from_f64(-2_500.0), Int256::from_i128(-2500));
2251    }
2252
2253    /// `Uint256` (the unsigned macro emission) supports the same
2254    /// bit/sign-manipulation surface as the signed sibling. Methods
2255    /// here are reachable through the wide decimal types but not always
2256    /// exercised by name; verify the contracts directly.
2257    #[test]
2258    fn uint256_is_zero_and_bit_helpers() {
2259        let zero = Uint256::ZERO;
2260        let one = Uint256::from_str_radix("1", 10).unwrap();
2261        let two = Uint256::from_str_radix("2", 10).unwrap();
2262        assert!(zero.is_zero());
2263        assert!(!one.is_zero());
2264        assert!(one.is_power_of_two());
2265        assert!(two.is_power_of_two());
2266        let three = Uint256::from_str_radix("3", 10).unwrap();
2267        assert!(!three.is_power_of_two());
2268        // next_power_of_two(0) == 1
2269        assert_eq!(zero.next_power_of_two(), one);
2270        // next_power_of_two(1) == 1 (already power of two)
2271        assert_eq!(one.next_power_of_two(), one);
2272        // next_power_of_two(3) == 4
2273        let four = Uint256::from_str_radix("4", 10).unwrap();
2274        assert_eq!(three.next_power_of_two(), four);
2275        // count_ones / leading_zeros
2276        assert_eq!(zero.count_ones(), 0);
2277        assert_eq!(one.count_ones(), 1);
2278        assert_eq!(zero.leading_zeros(), Uint256::BITS);
2279        assert_eq!(one.leading_zeros(), Uint256::BITS - 1);
2280    }
2281
2282    #[test]
2283    fn uint256_parse_arithmetic_and_pow() {
2284        // from_str_radix only accepts radix 10.
2285        assert!(Uint256::from_str_radix("10", 2).is_err());
2286        // Non-digit byte rejected.
2287        assert!(Uint256::from_str_radix("1a", 10).is_err());
2288        // Arithmetic: 3 - 2 = 1, 6 / 2 = 3, 7 % 3 = 1, 3·3 = 9.
2289        let two = Uint256::from_str_radix("2", 10).unwrap();
2290        let three = Uint256::from_str_radix("3", 10).unwrap();
2291        let six = Uint256::from_str_radix("6", 10).unwrap();
2292        let seven = Uint256::from_str_radix("7", 10).unwrap();
2293        assert_eq!(three - two, Uint256::from_str_radix("1", 10).unwrap());
2294        assert_eq!(six / two, three);
2295        assert_eq!(seven % three, Uint256::from_str_radix("1", 10).unwrap());
2296        // BitAnd / BitOr / BitXor
2297        let five = Uint256::from_str_radix("5", 10).unwrap();  // 101
2298        let four = Uint256::from_str_radix("4", 10).unwrap();  // 100
2299        let one = Uint256::from_str_radix("1", 10).unwrap();   // 001
2300        assert_eq!(five & four, four);                       // 100
2301        assert_eq!(five | one, five);                        // 101
2302        assert_eq!(five ^ four, one);                        // 001
2303        // pow: 2^10 = 1024
2304        let p10 = two.pow(10);
2305        assert_eq!(p10, Uint256::from_str_radix("1024", 10).unwrap());
2306        // cast_signed round-trip
2307        let signed = three.cast_signed();
2308        assert_eq!(signed, Int256::from_i128(3));
2309    }
2310
2311    /// `Int256::bit` reports the two's-complement bit at any index;
2312    /// indices past the storage width return the sign bit.
2313    #[test]
2314    fn signed_bit_and_trailing_zeros() {
2315        let v = Int256::from_i128(0b1100);
2316        assert!(v.bit(2));
2317        assert!(v.bit(3));
2318        assert!(!v.bit(0));
2319        assert!(!v.bit(1));
2320        // Out-of-range bit returns the sign — non-negative for v.
2321        assert!(!v.bit(1000));
2322        // Negative input: sign bit returns true past the storage.
2323        let n = Int256::from_i128(-1);
2324        assert!(n.bit(1000));
2325        // trailing_zeros
2326        assert_eq!(Int256::from_i128(8).trailing_zeros(), 3);
2327        assert_eq!(Int256::ZERO.trailing_zeros(), Int256::BITS);
2328    }
2329}
2330
2331#[cfg(test)]
2332mod slice_tests {
2333    use super::*;
2334
2335    #[test]
2336    fn mul_and_divmod_round_trip() {
2337        let a = [123u128, 7, 0, 0];
2338        let b = [456u128, 0, 0, 0];
2339        let mut prod = [0u128; 8];
2340        limbs_mul(&a, &b, &mut prod);
2341        let mut q = [0u128; 8];
2342        let mut r = [0u128; 8];
2343        limbs_divmod(&prod, &b, &mut q, &mut r);
2344        assert_eq!(&q[..4], &a, "quotient");
2345        assert!(limbs_is_zero(&r), "remainder");
2346    }
2347
2348    #[test]
2349    fn shifts() {
2350        let a = [1u128, 0];
2351        let mut out = [0u128; 2];
2352        limbs_shl(&a, 130, &mut out);
2353        assert_eq!(out, [0, 4]);
2354        let mut back = [0u128; 2];
2355        limbs_shr(&out, 130, &mut back);
2356        assert_eq!(back, [1, 0]);
2357    }
2358
2359    #[test]
2360    fn isqrt_basic() {
2361        let n = [0u128, 0, 1, 0];
2362        let mut out = [0u128; 4];
2363        limbs_isqrt(&n, &mut out);
2364        assert_eq!(out, [0, 1, 0, 0]);
2365        let n = [144u128, 0];
2366        let mut out = [0u128; 2];
2367        limbs_isqrt(&n, &mut out);
2368        assert_eq!(out, [12, 0]);
2369        let n = [2u128, 0];
2370        let mut out = [0u128; 2];
2371        limbs_isqrt(&n, &mut out);
2372        assert_eq!(out, [1, 0]);
2373    }
2374
2375    #[test]
2376    fn add_sub_carry() {
2377        let mut a = [u128::MAX, 0];
2378        let carry = limbs_add_assign(&mut a, &[1, 0]);
2379        assert!(!carry);
2380        assert_eq!(a, [0, 1]);
2381        let borrow = limbs_sub_assign(&mut a, &[1, 0]);
2382        assert!(!borrow);
2383        assert_eq!(a, [u128::MAX, 0]);
2384    }
2385
2386    /// `div_2_by_1` matches the obvious `(high·2^128 + low) / d`
2387    /// formula on representative inputs.
2388    #[test]
2389    fn div_2_by_1_basics() {
2390        // 1 / 1 = 1 r 0.
2391        assert_eq!(div_2_by_1(0, 1, 1), (1, 0));
2392        // 5 / 2 = 2 r 1.
2393        assert_eq!(div_2_by_1(0, 5, 2), (2, 1));
2394        // (3·2^128) / 4 = 3·2^126 r 0.
2395        assert_eq!(div_2_by_1(3, 0, 4), (3 << 126, 0));
2396        // High limb just under divisor — exercises the r_top overflow
2397        // recovery in the inner loop.
2398        let d = u128::MAX - 7;
2399        let (q, r) = div_2_by_1(d - 1, u128::MAX, d);
2400        // q · d + r == (d−1)·2^128 + (2^128 − 1)
2401        let (mul_hi, mul_lo) = mul_128(q, d);
2402        let (sum_lo, c) = mul_lo.overflowing_add(r);
2403        let sum_hi = mul_hi + c as u128;
2404        assert_eq!(sum_hi, d - 1);
2405        assert_eq!(sum_lo, u128::MAX);
2406        assert!(r < d);
2407    }
2408
2409    // ── u64-primitive equivalence: u64 versions vs u128 oracle ──────
2410
2411    /// Pack a `[u128; N]` little-endian limb array into `[u64; 2*N]`.
2412    fn pack(limbs: &[u128]) -> alloc::vec::Vec<u64> {
2413        let mut out = alloc::vec![0u64; 2 * limbs.len()];
2414        for (i, &l) in limbs.iter().enumerate() {
2415            out[2 * i] = l as u64;
2416            out[2 * i + 1] = (l >> 64) as u64;
2417        }
2418        out
2419    }
2420
2421    /// Unpack a `[u64; 2*N]` slice into a `[u128; N]` vec.
2422    fn unpack(words: &[u64]) -> alloc::vec::Vec<u128> {
2423        assert!(words.len() % 2 == 0);
2424        let mut out = alloc::vec![0u128; words.len() / 2];
2425        for i in 0..out.len() {
2426            out[i] = (words[2 * i] as u128) | ((words[2 * i + 1] as u128) << 64);
2427        }
2428        out
2429    }
2430
2431    fn corpus() -> alloc::vec::Vec<alloc::vec::Vec<u128>> {
2432        alloc::vec![
2433            alloc::vec![0u128, 0, 0, 0],
2434            alloc::vec![1u128, 0, 0, 0],
2435            alloc::vec![u128::MAX, 0, 0, 0],
2436            alloc::vec![u128::MAX, u128::MAX, 0, 0],
2437            alloc::vec![u128::MAX, u128::MAX, u128::MAX, u128::MAX],
2438            alloc::vec![123u128, 456, 0, 0],
2439            alloc::vec![
2440                0x1234_5678_9abc_def0_fedc_ba98_7654_3210_u128,
2441                0xa5a5_a5a5_5a5a_5a5a_3c3c_3c3c_c3c3_c3c3,
2442                0,
2443                0,
2444            ],
2445        ]
2446    }
2447
2448    /// `limbs_mul_u64` matches `limbs_mul` after pack/unpack on the
2449    /// shared corpus.
2450    #[test]
2451    fn limbs_mul_u64_matches_u128() {
2452        for a in corpus() {
2453            for b in corpus() {
2454                let mut out128 = alloc::vec![0u128; a.len() + b.len()];
2455                limbs_mul(&a, &b, &mut out128);
2456
2457                let a64 = pack(&a);
2458                let b64 = pack(&b);
2459                let mut out64 = alloc::vec![0u64; a64.len() + b64.len()];
2460                limbs_mul_u64(&a64, &b64, &mut out64);
2461
2462                assert_eq!(unpack(&out64), out128, "limbs_mul mismatch");
2463            }
2464        }
2465    }
2466
2467    /// `limbs_divmod_u64` matches `limbs_divmod`.
2468    #[test]
2469    fn limbs_divmod_u64_matches_u128() {
2470        for num in corpus() {
2471            for den in corpus() {
2472                if den.iter().all(|&x| x == 0) {
2473                    continue;
2474                }
2475                let mut q128 = alloc::vec![0u128; num.len()];
2476                let mut r128 = alloc::vec![0u128; num.len()];
2477                limbs_divmod(&num, &den, &mut q128, &mut r128);
2478
2479                let n64 = pack(&num);
2480                let d64 = pack(&den);
2481                let mut q64 = alloc::vec![0u64; n64.len()];
2482                let mut r64 = alloc::vec![0u64; n64.len()];
2483                limbs_divmod_u64(&n64, &d64, &mut q64, &mut r64);
2484
2485                assert_eq!(unpack(&q64), q128, "divmod q mismatch");
2486                assert_eq!(unpack(&r64), r128, "divmod r mismatch");
2487            }
2488        }
2489    }
2490
2491    /// `limbs_divmod_knuth_u64` matches `limbs_divmod_knuth`.
2492    #[test]
2493    fn limbs_divmod_knuth_u64_matches_u128() {
2494        for num in corpus() {
2495            for den in corpus() {
2496                if den.iter().all(|&x| x == 0) {
2497                    continue;
2498                }
2499                let mut q128 = alloc::vec![0u128; num.len()];
2500                let mut r128 = alloc::vec![0u128; num.len()];
2501                limbs_divmod_knuth(&num, &den, &mut q128, &mut r128);
2502
2503                let n64 = pack(&num);
2504                let d64 = pack(&den);
2505                let mut q64 = alloc::vec![0u64; n64.len()];
2506                let mut r64 = alloc::vec![0u64; n64.len()];
2507                limbs_divmod_knuth_u64(&n64, &d64, &mut q64, &mut r64);
2508
2509                assert_eq!(unpack(&q64), q128, "knuth q mismatch");
2510                assert_eq!(unpack(&r64), r128, "knuth r mismatch");
2511            }
2512        }
2513    }
2514
2515    /// `MG3by2U64` matches the `limbs_divmod_u64` oracle on a
2516    /// representative corpus. Tests the corner cases that historically
2517    /// broke MG 3-by-2 implementations: numerator near divisor (so the
2518    /// initial q estimate may overshoot by 2), minimal normalised d1
2519    /// (= B/2), maximal d1, and the paper's worst-case corner where r1
2520    /// must compare against q_lo without underflow.
2521    #[test]
2522    fn mg3by2_u64_matches_reference() {
2523        let cases: &[(u64, u64, u64, u64, u64)] = &[
2524            // (n2, n1, n0, d1, d0) — d1 normalised, (n2, n1) < (d1, d0).
2525            // Minimal normalised d1 = B/2.
2526            (0, 0, 1, 1u64 << 63, 0),
2527            (0, 1, 0, 1u64 << 63, 0),
2528            ((1u64 << 63) - 1, u64::MAX, u64::MAX, 1u64 << 63, 1),
2529            // Maximal d1 = B-1.
2530            (u64::MAX - 1, u64::MAX, u64::MAX, u64::MAX, u64::MAX),
2531            (0, 0, 1, u64::MAX, 1),
2532            // Mid-range divisor; numerator just under (d1, d0).
2533            (0xc0ffee, 0xdead_beef, 0xface_b00c, (1u64 << 63) | 0xc0ffee_u64, 0xdead_beef_face_b00c),
2534            // Small numerator vs large divisor (quotient = 0).
2535            (0, 1, 2, (1u64 << 63) | 1, 2),
2536            // Numerator = divisor (quotient = 1, remainder = 0). Need to
2537            // express (d1, d0, 0) carefully: n2 = 0, then we'd violate
2538            // the precondition. Skip; this is a degenerate corner the
2539            // Knuth caller never hits.
2540        ];
2541        for &(n2, n1, n0, d1, d0) in cases {
2542            assert!(d1 >> 63 == 1, "d1 not normalised: {d1:#x}");
2543            assert!(
2544                n2 < d1 || (n2 == d1 && n1 < d0),
2545                "test precondition (n2, n1) < (d1, d0) violated"
2546            );
2547            let mg = MG3by2U64::new(d1, d0);
2548            let (q, r1, r0) = mg.div_rem(n2, n1, n0);
2549
2550            // Reference: 3-limb numerator / 2-limb divisor via
2551            // limbs_divmod_u64. The function requires
2552            // `rem.len() >= num.len()` so size both at 3.
2553            let num = alloc::vec![n0, n1, n2];
2554            let den = alloc::vec![d0, d1];
2555            let mut q_ref = alloc::vec![0u64; 3];
2556            let mut r_ref = alloc::vec![0u64; 3];
2557            limbs_divmod_u64(&num, &den, &mut q_ref, &mut r_ref);
2558
2559            assert_eq!(q_ref[0], q, "MG3by2 q mismatch for n=({n2:#x},{n1:#x},{n0:#x}) d=({d1:#x},{d0:#x})");
2560            assert_eq!(q_ref[1], 0, "MG3by2 q higher limb non-zero — precondition violated");
2561            assert_eq!(q_ref[2], 0, "MG3by2 q higher limb non-zero — precondition violated");
2562            assert_eq!(r_ref[0], r0, "MG3by2 r0 mismatch");
2563            assert_eq!(r_ref[1], r1, "MG3by2 r1 mismatch");
2564        }
2565    }
2566
2567    /// `MG2by1U64` matches a reference 2-by-1 divide.
2568    #[test]
2569    fn mg2by1_u64_matches_reference() {
2570        let cases: &[(u64, u64, u64)] = &[
2571            (0, 1, 1u64 << 63),
2572            (0, u64::MAX, 1u64 << 63),
2573            ((1u64 << 63) - 1, u64::MAX, 1u64 << 63),
2574            (0, 1, u64::MAX),
2575            (u64::MAX - 1, u64::MAX, u64::MAX),
2576            (12345, 67890, (1u64 << 63) | 0xdead_beef_u64),
2577            (u64::MAX - 1, 0, u64::MAX),
2578        ];
2579        for &(u1, u0, d) in cases {
2580            assert!(d >> 63 == 1);
2581            assert!(u1 < d);
2582            let mg = MG2by1U64::new(d);
2583            let (q, r) = mg.div_rem(u1, u0);
2584            // Reference: ((u1 as u128) << 64 | u0 as u128) / (d as u128)
2585            let num = ((u1 as u128) << 64) | (u0 as u128);
2586            let exp_q = (num / (d as u128)) as u64;
2587            let exp_r = (num % (d as u128)) as u64;
2588            assert_eq!((q, r), (exp_q, exp_r), "MG u64 mismatch for {u1:#x}, {u0:#x}, d={d:#x}");
2589        }
2590    }
2591
2592    /// `MG2by1::div_rem` bit-exact matches `div_2_by_1` on a
2593    /// battery of corner cases that historically broke 2-by-1 MG
2594    /// implementations: maximal numerator with minimal-normalised
2595    /// divisor (forces the +1 step's u128 overflow), boundary
2596    /// q̂ = u128::MAX, exact divides, and the smallest divisor that
2597    /// satisfies the normalisation requirement (`d` with top bit
2598    /// set and otherwise zero, i.e. `B/2`).
2599    #[test]
2600    fn mg2by1_matches_div_2_by_1() {
2601        // For each (u1, u0, d), the precondition is `u1 < d` and
2602        // `d >> 127 == 1` (normalised).
2603        let cases: &[(u128, u128, u128)] = &[
2604            // Minimal normalised divisor (d = B/2).
2605            (0, 1, 1u128 << 127),
2606            (0, u128::MAX, 1u128 << 127),
2607            ((1u128 << 127) - 1, u128::MAX, 1u128 << 127),
2608            // Maximal divisor (d = u128::MAX = B-1).
2609            (0, 1, u128::MAX),
2610            (u128::MAX - 1, u128::MAX, u128::MAX),
2611            // The exact corner case worked through in the docs:
2612            // u1 = B-2, u0 = B-1, d = B-1 → (q, r) = (B-1, B-2).
2613            (u128::MAX - 1, u128::MAX, u128::MAX),
2614            // Mid-range with mid-range divisor.
2615            (12345, 67890, (1u128 << 127) | 0xdead_beefu128),
2616            // Numerator equals divisor minus one in the high limb —
2617            // exercises the "q̂ = u128::MAX" path.
2618            (u128::MAX - 1, 0, u128::MAX),
2619            // Random spread.
2620            (0x1234_5678_9abc_def0_u128 ^ 0xa5a5, 0xfedc_ba98_7654_3210_u128, (1u128 << 127) | 0xc0ffee_u128),
2621        ];
2622        for &(u1, u0, d) in cases {
2623            assert!(d >> 127 == 1, "test divisor not normalised: {d:#x}");
2624            assert!(u1 < d, "test precondition u1 < d violated: {u1:#x} >= {d:#x}");
2625            let (q_ref, r_ref) = div_2_by_1(u1, u0, d);
2626            let mg = MG2by1::new(d);
2627            let (q_mg, r_mg) = mg.div_rem(u1, u0);
2628            assert_eq!(
2629                (q_mg, r_mg),
2630                (q_ref, r_ref),
2631                "MG2by1 disagrees with div_2_by_1 for (u1={u1:#x}, u0={u0:#x}, d={d:#x})"
2632            );
2633        }
2634    }
2635
2636    /// `limbs_divmod_knuth` agrees with the canonical `limbs_divmod`
2637    /// on a battery of representative shapes — single-limb divisors,
2638    /// multi-limb divisors, zero remainders, partial overflows in the
2639    /// q̂ refinement step.
2640    #[test]
2641    fn knuth_matches_canonical_divmod() {
2642        let cases: &[(&[u128], &[u128])] = &[
2643            // Simple
2644            (&[42], &[7]),
2645            (&[u128::MAX, 0], &[2]),
2646            // Multi-limb numerator, single-limb denominator.
2647            (&[1, 1, 0, 0], &[3]),
2648            // Multi-limb both — three-limb numerator by two-limb den.
2649            (&[u128::MAX, u128::MAX, 1, 0], &[5, 9]),
2650            // Three-limb both.
2651            (&[u128::MAX, u128::MAX, u128::MAX, 0], &[1, 2, 3]),
2652            // Numerator < denominator — quotient zero, remainder = num.
2653            (&[100, 0, 0], &[200, 0, 1]),
2654            // Equal high limbs (forces the u_top ≥ v_top branch).
2655            (
2656                &[0, 0, u128::MAX, u128::MAX],
2657                &[1, 2, u128::MAX],
2658            ),
2659        ];
2660        for (num, den) in cases {
2661            let mut q_canon = [0u128; 8];
2662            let mut r_canon = [0u128; 8];
2663            limbs_divmod(num, den, &mut q_canon, &mut r_canon);
2664            let mut q_knuth = [0u128; 8];
2665            let mut r_knuth = [0u128; 8];
2666            limbs_divmod_knuth(num, den, &mut q_knuth, &mut r_knuth);
2667            assert_eq!(q_canon, q_knuth, "quotient mismatch on {:?} / {:?}", num, den);
2668            assert_eq!(r_canon, r_knuth, "remainder mismatch on {:?} / {:?}", num, den);
2669        }
2670    }
2671
2672    /// `limbs_divmod_bz` agrees with the canonical path on
2673    /// medium-and-large operands. Recursion engages only above the
2674    /// `BZ_THRESHOLD = 8` limb cutoff.
2675    #[test]
2676    fn bz_matches_canonical_divmod() {
2677        // Builds a 16-limb dividend with a 10-limb divisor — well
2678        // above BZ_THRESHOLD so the recursive path is exercised.
2679        let mut num = [0u128; 16];
2680        for (i, slot) in num.iter_mut().enumerate() {
2681            *slot = (i as u128)
2682                .wrapping_mul(0x9E37_79B9_7F4A_7C15)
2683                .wrapping_add(i as u128);
2684        }
2685        let mut den = [0u128; 10];
2686        for (i, slot) in den.iter_mut().enumerate() {
2687            *slot = ((i + 1) as u128).wrapping_mul(0xBF58_476D_1CE4_E5B9);
2688        }
2689        let mut q_canon = [0u128; 16];
2690        let mut r_canon = [0u128; 16];
2691        limbs_divmod(&num, &den, &mut q_canon, &mut r_canon);
2692        let mut q_bz = [0u128; 16];
2693        let mut r_bz = [0u128; 16];
2694        limbs_divmod_bz(&num, &den, &mut q_bz, &mut r_bz);
2695        assert_eq!(q_canon, q_bz, "BZ quotient mismatch");
2696        assert_eq!(r_canon, r_bz, "BZ remainder mismatch");
2697    }
2698
2699    /// `limbs_mul_fast` dispatches to Karatsuba when both operands are
2700    /// equal-length ≥ `KARATSUBA_MIN`. Verify by comparing the result
2701    /// against schoolbook (`limbs_mul`) on a 16-limb pair.
2702    #[cfg(feature = "alloc")]
2703    #[test]
2704    fn fast_mul_dispatches_to_karatsuba_at_threshold() {
2705        let a: [u128; 16] = core::array::from_fn(|i| (i as u128).wrapping_mul(0xABCD) + 1);
2706        let b: [u128; 16] = core::array::from_fn(|i| (i as u128).wrapping_mul(0xBEEF) + 7);
2707        let mut fast = [0u128; 32];
2708        let mut school = [0u128; 32];
2709        limbs_mul_fast(&a, &b, &mut fast);
2710        limbs_mul(&a, &b, &mut school);
2711        assert_eq!(fast, school, "fast (Karatsuba) and schoolbook disagree");
2712    }
2713
2714    /// `limbs_mul_fast` falls through to schoolbook for unequal lengths
2715    /// or below the threshold. The 8-limb pair below skips Karatsuba.
2716    #[cfg(feature = "alloc")]
2717    #[test]
2718    fn fast_mul_falls_through_to_schoolbook_below_threshold() {
2719        let a: [u128; 8] = core::array::from_fn(|i| (i as u128).wrapping_mul(0x1234) + 1);
2720        let b: [u128; 8] = core::array::from_fn(|i| (i as u128).wrapping_mul(0x5678) + 3);
2721        let mut fast = [0u128; 16];
2722        let mut school = [0u128; 16];
2723        limbs_mul_fast(&a, &b, &mut fast);
2724        limbs_mul(&a, &b, &mut school);
2725        assert_eq!(fast, school);
2726    }
2727
2728    /// Karatsuba called directly below the threshold should still
2729    /// produce the correct product via its internal schoolbook
2730    /// fall-through. This exercises the safety branch in
2731    /// `limbs_mul_karatsuba` that zeros out and delegates back to
2732    /// schoolbook when `n < KARATSUBA_MIN`.
2733    #[cfg(feature = "alloc")]
2734    #[test]
2735    fn karatsuba_safety_fallback_below_threshold() {
2736        let a: [u128; 4] = [123, 456, 789, 0];
2737        let b: [u128; 4] = [987, 654, 321, 0];
2738        let mut karatsuba_out = [0u128; 8];
2739        let mut school_out = [0u128; 8];
2740        limbs_mul_karatsuba(&a, &b, &mut karatsuba_out);
2741        limbs_mul(&a, &b, &mut school_out);
2742        assert_eq!(karatsuba_out, school_out);
2743    }
2744
2745    /// `limbs_isqrt` of `1` returns `1` via the `bits <= 1` short-
2746    /// circuit.
2747    #[test]
2748    fn isqrt_one_short_circuit() {
2749        let n = [1u128, 0];
2750        let mut out = [0u128; 2];
2751        limbs_isqrt(&n, &mut out);
2752        assert_eq!(out, [1, 0]);
2753    }
2754
2755    /// `limbs_isqrt` of `0` returns `0` via the `bits == 0` short-
2756    /// circuit.
2757    #[test]
2758    fn isqrt_zero_short_circuit() {
2759        let n = [0u128, 0];
2760        let mut out = [0u128; 2];
2761        limbs_isqrt(&n, &mut out);
2762        assert_eq!(out, [0, 0]);
2763    }
2764
2765    /// `WideInt::from_mag_sign` for `u128` reads the first limb and
2766    /// ignores the sign flag. Exercised through a chained `wide_cast`
2767    /// `Int256 → u128`.
2768    #[test]
2769    fn wide_cast_into_u128_returns_first_limb() {
2770        let src = Int256::from_i128(123_456_789);
2771        let dst: u128 = wide_cast(src);
2772        assert_eq!(dst, 123_456_789);
2773        // Casting ZERO yields 0.
2774        let dst: u128 = wide_cast(Int256::ZERO);
2775        assert_eq!(dst, 0);
2776    }
2777
2778    /// Knuth's q̂-cap path fires when `u_top >= v_top` in the
2779    /// per-quotient-limb loop. We engineer a dividend whose normalised
2780    /// top limb equals the normalised divisor top so the cap (`q̂ =
2781    /// u128::MAX`, plus the subsequent multiply-subtract correction)
2782    /// runs, then verify the resulting quotient matches the canonical
2783    /// `limbs_divmod`.
2784    #[test]
2785    fn knuth_q_hat_cap_branch_matches_canonical() {
2786        // num top limb == den top limb; div quotient's first chunk hits
2787        // the cap. Picking the divisor's top close to u128::MAX
2788        // tightens the normalisation shift.
2789        let num: [u128; 4] = [0, 0, u128::MAX, u128::MAX >> 1];
2790        let den: [u128; 3] = [1, 2, u128::MAX >> 1];
2791        let mut q_canon = [0u128; 4];
2792        let mut r_canon = [0u128; 4];
2793        limbs_divmod(&num, &den, &mut q_canon, &mut r_canon);
2794        let mut q_knuth = [0u128; 4];
2795        let mut r_knuth = [0u128; 4];
2796        limbs_divmod_knuth(&num, &den, &mut q_knuth, &mut r_knuth);
2797        assert_eq!(q_canon, q_knuth);
2798        assert_eq!(r_canon, r_knuth);
2799    }
2800
2801    /// `limbs_divmod_bz` with a numerator that has trailing zero limbs
2802    /// strips them off in its top-non-zero scan before deciding whether
2803    /// to recurse.
2804    #[test]
2805    fn bz_strips_numerator_trailing_zeros() {
2806        // 16-limb buffer but only the low half is non-zero; den is 10 limbs.
2807        // BZ should recognise top < 2*n and fall back to Knuth.
2808        let mut num = [0u128; 16];
2809        for slot in &mut num[..8] {
2810            *slot = 0xCAFE_F00D;
2811        }
2812        let mut den = [0u128; 10];
2813        den[0] = 7;
2814        let mut q_canon = [0u128; 16];
2815        let mut r_canon = [0u128; 16];
2816        limbs_divmod(&num, &den, &mut q_canon, &mut r_canon);
2817        let mut q_bz = [0u128; 16];
2818        let mut r_bz = [0u128; 16];
2819        limbs_divmod_bz(&num, &den, &mut q_bz, &mut r_bz);
2820        assert_eq!(q_canon, q_bz);
2821        assert_eq!(r_canon, r_bz);
2822    }
2823}