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/// Fixed-width specialisation of [`limbs_is_zero_u64`]. `L` const at
1120/// callsite, lets LLVM unroll for small `L`.
1121#[inline]
1122pub(crate) const fn limbs_is_zero_u64_fixed<const L: usize>(a: &[u64; L]) -> bool {
1123    let mut i = 0;
1124    while i < L {
1125        if a[i] != 0 {
1126            return false;
1127        }
1128        i += 1;
1129    }
1130    true
1131}
1132
1133/// `a == b` for two limb slices of possibly different lengths.
1134#[inline]
1135pub(crate) const fn limbs_eq_u64(a: &[u64], b: &[u64]) -> bool {
1136    let n = if a.len() > b.len() { a.len() } else { b.len() };
1137    let mut i = 0;
1138    while i < n {
1139        let av = if i < a.len() { a[i] } else { 0 };
1140        let bv = if i < b.len() { b[i] } else { 0 };
1141        if av != bv {
1142            return false;
1143        }
1144        i += 1;
1145    }
1146    true
1147}
1148
1149/// Three-way comparison `-1`/`0`/`1`.
1150#[inline]
1151pub(crate) const fn limbs_cmp_u64(a: &[u64], b: &[u64]) -> i32 {
1152    let n = if a.len() > b.len() { a.len() } else { b.len() };
1153    let mut i = n;
1154    while i > 0 {
1155        i -= 1;
1156        let av = if i < a.len() { a[i] } else { 0 };
1157        let bv = if i < b.len() { b[i] } else { 0 };
1158        if av < bv {
1159            return -1;
1160        }
1161        if av > bv {
1162            return 1;
1163        }
1164    }
1165    0
1166}
1167
1168/// Fixed-width specialisation of [`limbs_cmp_u64`] — both operands
1169/// the same `L`; no length-difference handling needed.
1170#[inline]
1171pub(crate) const fn limbs_cmp_u64_fixed<const L: usize>(a: &[u64; L], b: &[u64; L]) -> i32 {
1172    let mut i = L;
1173    while i > 0 {
1174        i -= 1;
1175        if a[i] < b[i] {
1176            return -1;
1177        }
1178        if a[i] > b[i] {
1179            return 1;
1180        }
1181    }
1182    0
1183}
1184
1185/// Bit length (`0` for zero, else `floor(log2)+1`).
1186#[inline]
1187pub(crate) const fn limbs_bit_len_u64(a: &[u64]) -> u32 {
1188    let mut i = a.len();
1189    while i > 0 {
1190        i -= 1;
1191        if a[i] != 0 {
1192            return (i as u32) * 64 + (64 - a[i].leading_zeros());
1193        }
1194    }
1195    0
1196}
1197
1198/// Fixed-width specialisation of [`limbs_bit_len_u64`].
1199#[inline]
1200pub(crate) const fn limbs_bit_len_u64_fixed<const L: usize>(a: &[u64; L]) -> u32 {
1201    let mut i = L;
1202    while i > 0 {
1203        i -= 1;
1204        if a[i] != 0 {
1205            return (i as u32) * 64 + (64 - a[i].leading_zeros());
1206        }
1207    }
1208    0
1209}
1210
1211/// `a += b`, returns carry out. `a.len() >= b.len()`.
1212#[inline]
1213pub(crate) const fn limbs_add_assign_u64(a: &mut [u64], b: &[u64]) -> bool {
1214    let mut carry: u64 = 0;
1215    let mut i = 0;
1216    while i < a.len() {
1217        let bv = if i < b.len() { b[i] } else { 0 };
1218        let (s1, c1) = a[i].overflowing_add(bv);
1219        let (s2, c2) = s1.overflowing_add(carry);
1220        a[i] = s2;
1221        carry = (c1 as u64) + (c2 as u64);
1222        i += 1;
1223    }
1224    carry != 0
1225}
1226
1227/// Fixed-width specialisation of [`limbs_add_assign_u64`] — both
1228/// operands the same `L`.
1229#[inline]
1230pub(crate) const fn limbs_add_assign_u64_fixed<const L: usize>(
1231    a: &mut [u64; L],
1232    b: &[u64; L],
1233) -> bool {
1234    let mut carry: u64 = 0;
1235    let mut i = 0;
1236    while i < L {
1237        let (s1, c1) = a[i].overflowing_add(b[i]);
1238        let (s2, c2) = s1.overflowing_add(carry);
1239        a[i] = s2;
1240        carry = (c1 as u64) + (c2 as u64);
1241        i += 1;
1242    }
1243    carry != 0
1244}
1245
1246/// `a -= b`, returns borrow out. `a.len() >= b.len()`.
1247#[inline]
1248pub(crate) const fn limbs_sub_assign_u64(a: &mut [u64], b: &[u64]) -> bool {
1249    let mut borrow: u64 = 0;
1250    let mut i = 0;
1251    while i < a.len() {
1252        let bv = if i < b.len() { b[i] } else { 0 };
1253        let (d1, b1) = a[i].overflowing_sub(bv);
1254        let (d2, b2) = d1.overflowing_sub(borrow);
1255        a[i] = d2;
1256        borrow = (b1 as u64) + (b2 as u64);
1257        i += 1;
1258    }
1259    borrow != 0
1260}
1261
1262/// Fixed-width specialisation of [`limbs_sub_assign_u64`].
1263#[inline]
1264pub(crate) const fn limbs_sub_assign_u64_fixed<const L: usize>(
1265    a: &mut [u64; L],
1266    b: &[u64; L],
1267) -> bool {
1268    let mut borrow: u64 = 0;
1269    let mut i = 0;
1270    while i < L {
1271        let (d1, b1) = a[i].overflowing_sub(b[i]);
1272        let (d2, b2) = d1.overflowing_sub(borrow);
1273        a[i] = d2;
1274        borrow = (b1 as u64) + (b2 as u64);
1275        i += 1;
1276    }
1277    borrow != 0
1278}
1279
1280/// Fixed-width specialisation of [`limbs_shl_u64`]. `L` const, but
1281/// `shift` is still runtime — bounds checks vanish, the inner loop
1282/// trip count is known.
1283#[inline]
1284pub(crate) const fn limbs_shl_u64_fixed<const L: usize>(
1285    a: &[u64; L],
1286    shift: u32,
1287    out: &mut [u64; L],
1288) {
1289    let mut z = 0;
1290    while z < L {
1291        out[z] = 0;
1292        z += 1;
1293    }
1294    let limb_shift = (shift / 64) as usize;
1295    let bit = shift % 64;
1296    let mut i = 0;
1297    while i < L {
1298        let dst = i + limb_shift;
1299        if dst < L {
1300            if bit == 0 {
1301                out[dst] |= a[i];
1302            } else {
1303                out[dst] |= a[i] << bit;
1304                if dst + 1 < L {
1305                    out[dst + 1] |= a[i] >> (64 - bit);
1306                }
1307            }
1308        }
1309        i += 1;
1310    }
1311}
1312
1313/// Fixed-width specialisation of [`limbs_shr_u64`].
1314#[inline]
1315pub(crate) const fn limbs_shr_u64_fixed<const L: usize>(
1316    a: &[u64; L],
1317    shift: u32,
1318    out: &mut [u64; L],
1319) {
1320    let mut z = 0;
1321    while z < L {
1322        out[z] = 0;
1323        z += 1;
1324    }
1325    let limb_shift = (shift / 64) as usize;
1326    let bit = shift % 64;
1327    let mut i = limb_shift;
1328    while i < L {
1329        let dst = i - limb_shift;
1330        if dst < L {
1331            if bit == 0 {
1332                out[dst] |= a[i];
1333            } else {
1334                out[dst] |= a[i] >> bit;
1335                if dst >= 1 {
1336                    out[dst - 1] |= a[i] << (64 - bit);
1337                }
1338            }
1339        }
1340        i += 1;
1341    }
1342}
1343
1344/// `out = a << shift`. `out` is zeroed then filled.
1345pub(crate) const fn limbs_shl_u64(a: &[u64], shift: u32, out: &mut [u64]) {
1346    let mut z = 0;
1347    while z < out.len() {
1348        out[z] = 0;
1349        z += 1;
1350    }
1351    let limb_shift = (shift / 64) as usize;
1352    let bit = shift % 64;
1353    let mut i = 0;
1354    while i < a.len() {
1355        let dst = i + limb_shift;
1356        if dst < out.len() {
1357            if bit == 0 {
1358                out[dst] |= a[i];
1359            } else {
1360                out[dst] |= a[i] << bit;
1361                if dst + 1 < out.len() {
1362                    out[dst + 1] |= a[i] >> (64 - bit);
1363                }
1364            }
1365        }
1366        i += 1;
1367    }
1368}
1369
1370/// `out = a >> shift`. `out` is zeroed then filled.
1371pub(crate) const fn limbs_shr_u64(a: &[u64], shift: u32, out: &mut [u64]) {
1372    let mut z = 0;
1373    while z < out.len() {
1374        out[z] = 0;
1375        z += 1;
1376    }
1377    let limb_shift = (shift / 64) as usize;
1378    let bit = shift % 64;
1379    let mut i = limb_shift;
1380    while i < a.len() {
1381        let dst = i - limb_shift;
1382        if dst < out.len() {
1383            if bit == 0 {
1384                out[dst] |= a[i];
1385            } else {
1386                out[dst] |= a[i] >> bit;
1387                if dst >= 1 {
1388                    out[dst - 1] |= a[i] << (64 - bit);
1389                }
1390            }
1391        }
1392        i += 1;
1393    }
1394}
1395
1396/// Single-bit left shift in place; returns the bit shifted out.
1397#[inline]
1398const fn limbs_shl1_u64(a: &mut [u64]) -> u64 {
1399    let mut carry: u64 = 0;
1400    let mut i = 0;
1401    while i < a.len() {
1402        let new_carry = a[i] >> 63;
1403        a[i] = (a[i] << 1) | carry;
1404        carry = new_carry;
1405        i += 1;
1406    }
1407    carry
1408}
1409
1410/// `true` if every limb above index 0 is zero — fits a single u64.
1411#[inline]
1412const fn limbs_fit_one_u64(a: &[u64]) -> bool {
1413    let mut i = 1;
1414    while i < a.len() {
1415        if a[i] != 0 {
1416            return false;
1417        }
1418        i += 1;
1419    }
1420    true
1421}
1422
1423/// `out = a · b` schoolbook. `out.len() >= a.len() + b.len()` and
1424/// `out` must be zeroed by the caller.
1425///
1426/// Inner step uses the native `u64 × u64 → u128` widening mul
1427/// (`MUL` + `UMULH` on x86-64 / aarch64), avoiding the 4-way
1428/// `mul_128` decomposition every u128 schoolbook step pays.
1429pub(crate) const fn limbs_mul_u64(a: &[u64], b: &[u64], out: &mut [u64]) {
1430    let mut i = 0;
1431    while i < a.len() {
1432        if a[i] != 0 {
1433            let mut carry: u64 = 0;
1434            let mut j = 0;
1435            while j < b.len() {
1436                if b[j] != 0 || carry != 0 {
1437                    let prod = (a[i] as u128) * (b[j] as u128);
1438                    let prod_lo = prod as u64;
1439                    let prod_hi = (prod >> 64) as u64;
1440                    let idx = i + j;
1441                    let (s1, c1) = out[idx].overflowing_add(prod_lo);
1442                    let (s2, c2) = s1.overflowing_add(carry);
1443                    out[idx] = s2;
1444                    carry = prod_hi + (c1 as u64) + (c2 as u64);
1445                }
1446                j += 1;
1447            }
1448            let mut idx = i + b.len();
1449            while carry != 0 && idx < out.len() {
1450                let (s, c) = out[idx].overflowing_add(carry);
1451                out[idx] = s;
1452                carry = c as u64;
1453                idx += 1;
1454            }
1455        }
1456        i += 1;
1457    }
1458}
1459
1460/// Fixed-width specialisation of [`limbs_mul_u64`]: the operand
1461/// limb-count `L` and output limb-count `D = 2·L` are both
1462/// compile-time constants, so the slice indirection and loop-bound
1463/// checks vanish and LLVM can unroll the inner loop (and, for small
1464/// `L`, the outer one too).
1465///
1466/// Same algorithm and same output as [`limbs_mul_u64`]; faster only
1467/// when both operands have known-equal length (the common case for
1468/// wide-tier `widen_mul` where both operands are an `Int{N}` of the
1469/// tier's storage width).
1470#[inline]
1471pub(crate) const fn limbs_mul_u64_fixed<const L: usize, const D: usize>(
1472    a: &[u64; L],
1473    b: &[u64; L],
1474    out: &mut [u64; D],
1475) {
1476    debug_assert!(D >= 2 * L, "limbs_mul_u64_fixed: D must be ≥ 2·L");
1477    let mut i = 0;
1478    while i < L {
1479        let ai = a[i];
1480        if ai != 0 {
1481            let mut carry: u64 = 0;
1482            let mut j = 0;
1483            while j < L {
1484                let v = (ai as u128) * (b[j] as u128)
1485                    + (out[i + j] as u128)
1486                    + (carry as u128);
1487                out[i + j] = v as u64;
1488                carry = (v >> 64) as u64;
1489                j += 1;
1490            }
1491            // Final row carry, propagated until exhausted or end of
1492            // `out`. Worst-case unbounded chain when out[i + L ..]
1493            // is all-ones; ordinarily exits after 1 iteration.
1494            let mut idx = i + L;
1495            let mut c = carry;
1496            while c != 0 && idx < D {
1497                let v = (out[idx] as u128) + (c as u128);
1498                out[idx] = v as u64;
1499                c = (v >> 64) as u64;
1500                idx += 1;
1501            }
1502        }
1503        i += 1;
1504    }
1505}
1506
1507/// `quot = num / den`, `rem = num % den`, u64 limbs.
1508///
1509/// Hardware fast paths:
1510/// - both fit a single u64 → one native `u64 / u64`
1511/// - divisor fits a single u64 → native `u128 / u64` per dividend limb
1512/// - otherwise → bit shift-subtract (only reached when divisor is
1513///   multi-limb; the dispatcher routes those to Knuth instead)
1514pub(crate) const fn limbs_divmod_u64(
1515    num: &[u64],
1516    den: &[u64],
1517    quot: &mut [u64],
1518    rem: &mut [u64],
1519) {
1520    let mut z = 0;
1521    while z < quot.len() {
1522        quot[z] = 0;
1523        z += 1;
1524    }
1525    z = 0;
1526    while z < rem.len() {
1527        rem[z] = 0;
1528        z += 1;
1529    }
1530
1531    let den_one_limb = limbs_fit_one_u64(den);
1532
1533    // Fast path A: both fit a single u64 → hardware divide.
1534    if den_one_limb && limbs_fit_one_u64(num) {
1535        if !quot.is_empty() {
1536            quot[0] = num[0] / den[0];
1537        }
1538        if !rem.is_empty() {
1539            rem[0] = num[0] % den[0];
1540        }
1541        return;
1542    }
1543
1544    // Fast path B: divisor fits a single u64 — schoolbook base-2^64
1545    // long divide using the native u128/u64 hardware divide. Note this
1546    // is the SAME shape as the u128 path's Fast B (which manually
1547    // splits u128 into 64-bit halves), but here it's one hardware
1548    // divide per limb instead of two.
1549    if den_one_limb {
1550        let d = den[0];
1551        let mut r: u64 = 0;
1552        let mut top = num.len();
1553        while top > 0 && num[top - 1] == 0 {
1554            top -= 1;
1555        }
1556        let mut i = top;
1557        while i > 0 {
1558            i -= 1;
1559            let acc = ((r as u128) << 64) | (num[i] as u128);
1560            let q = (acc / (d as u128)) as u64;
1561            r = (acc % (d as u128)) as u64;
1562            if i < quot.len() {
1563                quot[i] = q;
1564            }
1565        }
1566        if !rem.is_empty() {
1567            rem[0] = r;
1568        }
1569        return;
1570    }
1571
1572    // General path: binary shift-subtract. Only reached for multi-limb
1573    // divisors when the dispatcher isn't routing to Knuth (i.e. in
1574    // const contexts where Knuth isn't available).
1575    let bits = limbs_bit_len_u64(num);
1576    let mut i = bits;
1577    while i > 0 {
1578        i -= 1;
1579        limbs_shl1_u64(rem);
1580        let bit = (num[(i / 64) as usize] >> (i % 64)) & 1;
1581        rem[0] |= bit;
1582        limbs_shl1_u64(quot);
1583        if limbs_cmp_u64(rem, den) >= 0 {
1584            limbs_sub_assign_u64(rem, den);
1585            quot[0] |= 1;
1586        }
1587    }
1588}
1589
1590/// Scratch capacity for the runtime u64-limb kernels — 144 u64 limbs
1591/// (9216 bits), matching the u128 path's 72-limb scratch.
1592// 288 u64 limbs = 18432 bits — covers the widest work integer in
1593// the crate (Int16384 used by D1231 cbrt, 256 u64 limbs) with isqrt
1594// scratch slack.
1595const SCRATCH_LIMBS_U64: usize = 288;
1596
1597/// Karatsuba threshold for the u64-base multiplier. Set above any
1598/// width the crate ships so the dispatcher never routes through
1599/// Karatsuba in practice. The implementation is retained for
1600/// possible future use (a `simd` feature, an extra-wide tier past
1601/// D1231, etc.) but the M2 gate at L=16-96 showed schoolbook wins
1602/// 1.07-1.92× at every shipped width — LLVM-unrolled schoolbook
1603/// + the heap allocations the recursive split needs put the
1604/// crossover well past our widest tier.
1605pub(crate) const KARATSUBA_THRESHOLD_U64: usize = 256;
1606
1607/// Recursive Karatsuba multiplication at u64 base.
1608///
1609/// Reference: Karatsuba & Ofman 1962, "Multiplication of Multidigit
1610/// Numbers on Automata" (Doklady Akad. Nauk SSSR 145, 293-294).
1611/// Splits both equal-length operands at half: `a = a₁·B + a₀`,
1612/// `b = b₁·B + b₀`, computes three half-width sub-products
1613/// `z₀ = a₀·b₀`, `z₂ = a₁·b₁`, `z₁ = (a₀+a₁)·(b₀+b₁) − z₀ − z₂`,
1614/// then recombines as `z₂·B² + z₁·B + z₀`.
1615///
1616/// Operands must be equal length. `out.len() >= 2 * a.len()` and
1617/// `out` must be zeroed by the caller.
1618#[cfg(feature = "alloc")]
1619pub(crate) fn limbs_mul_karatsuba_u64(a: &[u64], b: &[u64], out: &mut [u64]) {
1620    debug_assert_eq!(a.len(), b.len());
1621    debug_assert!(out.len() >= 2 * a.len());
1622    let n = a.len();
1623    if n < KARATSUBA_THRESHOLD_U64 {
1624        limbs_mul_u64(a, b, out);
1625        return;
1626    }
1627    let h = n / 2;
1628    let hi_len = n - h;
1629    let (a_lo, a_hi) = a.split_at(h);
1630    let (b_lo, b_hi) = b.split_at(h);
1631
1632    // z0 = a_lo · b_lo
1633    let mut z0 = alloc::vec![0u64; 2 * h];
1634    limbs_mul_karatsuba_padded_u64(a_lo, b_lo, &mut z0);
1635
1636    // z2 = a_hi · b_hi
1637    let mut z2 = alloc::vec![0u64; 2 * hi_len];
1638    limbs_mul_karatsuba_padded_u64(a_hi, b_hi, &mut z2);
1639
1640    // sum_a = a_lo + a_hi, sum_b = b_lo + b_hi. The sums fit in
1641    // max(h, hi_len) + 1 limbs (1 limb of carry).
1642    let sum_len = core::cmp::max(h, hi_len) + 1;
1643    let mut sum_a = alloc::vec![0u64; sum_len];
1644    let mut sum_b = alloc::vec![0u64; sum_len];
1645    sum_a[..h].copy_from_slice(a_lo);
1646    sum_b[..h].copy_from_slice(b_lo);
1647    let _ = limbs_add_assign_u64(&mut sum_a[..], a_hi);
1648    let _ = limbs_add_assign_u64(&mut sum_b[..], b_hi);
1649
1650    // z1m = sum_a · sum_b, then z1 = z1m - z0 - z2.
1651    let mut z1 = alloc::vec![0u64; 2 * sum_len];
1652    limbs_mul_karatsuba_padded_u64(&sum_a, &sum_b, &mut z1);
1653    let _ = limbs_sub_assign_u64(&mut z1[..], &z0);
1654    let _ = limbs_sub_assign_u64(&mut z1[..], &z2);
1655
1656    // Combine: out = z0 + z2·B² + z1·B  (B = 2^(h·64)).
1657    for o in out.iter_mut().take(2 * n) {
1658        *o = 0;
1659    }
1660    let z0_take = core::cmp::min(z0.len(), out.len());
1661    out[..z0_take].copy_from_slice(&z0[..z0_take]);
1662    let z2_take = core::cmp::min(z2.len(), out.len().saturating_sub(2 * h));
1663    if z2_take > 0 {
1664        out[2 * h..2 * h + z2_take].copy_from_slice(&z2[..z2_take]);
1665    }
1666    let z1_take = core::cmp::min(z1.len(), out.len().saturating_sub(h));
1667    if z1_take > 0 {
1668        let _ = limbs_add_assign_u64(&mut out[h..h + z1_take], &z1[..z1_take]);
1669    }
1670}
1671
1672/// Karatsuba helper that handles uneven operand lengths at the
1673/// recursion boundary (`n` odd → `n_hi = n − h > h`).
1674#[cfg(feature = "alloc")]
1675fn limbs_mul_karatsuba_padded_u64(a: &[u64], b: &[u64], out: &mut [u64]) {
1676    if a.len() == b.len() && a.len() >= KARATSUBA_THRESHOLD_U64 {
1677        limbs_mul_karatsuba_u64(a, b, out);
1678    } else {
1679        for o in out.iter_mut() {
1680            *o = 0;
1681        }
1682        limbs_mul_u64(a, b, out);
1683    }
1684}
1685
1686/// Equal-length u64 multiplier dispatcher. Picks Karatsuba above
1687/// the threshold; otherwise schoolbook. Both operands are assumed
1688/// to be the same length (the common `widen_mul` case).
1689pub(crate) fn limbs_mul_fast_u64(a: &[u64], b: &[u64], out: &mut [u64]) {
1690    #[cfg(feature = "alloc")]
1691    {
1692        if a.len() == b.len() && a.len() >= KARATSUBA_THRESHOLD_U64 {
1693            for o in out.iter_mut() {
1694                *o = 0;
1695            }
1696            limbs_mul_karatsuba_u64(a, b, out);
1697            return;
1698        }
1699    }
1700    limbs_mul_u64(a, b, out);
1701}
1702
1703/// Möller–Granlund 2-by-1 invariant divisor at u64 base.
1704///
1705/// Reference: same as [`MG2by1`] (Möller & Granlund 2011, Algorithm 4).
1706///
1707/// The u64 base implementation is materially simpler than its u128
1708/// sibling because the doubled type (u128) is *native* — every step
1709/// that the u128 path does via `mul_128` + carry-merge is just one
1710/// `u128` op here.
1711#[derive(Clone, Copy)]
1712pub(crate) struct MG2by1U64 {
1713    d: u64,
1714    v: u64,
1715}
1716
1717impl MG2by1U64 {
1718    /// `d` must be normalised: `d >> 63 == 1`.
1719    #[inline]
1720    pub(crate) const fn new(d: u64) -> Self {
1721        debug_assert!(d >> 63 == 1, "MG2by1U64::new: divisor must be normalised");
1722        // v = floor((B² - 1 - d·B) / d) where B = 2^64.
1723        // Numerator high = !d (= B-1-d), low = u64::MAX (= B-1).
1724        // High < d for normalised d, so native u128/u128 with the
1725        // divisor cast to u128 returns a quotient fitting u64.
1726        let num = ((!d as u128) << 64) | (u64::MAX as u128);
1727        let v = (num / (d as u128)) as u64;
1728        Self { d, v }
1729    }
1730
1731    /// Divide `(u1·B + u0)` by `d`. Requires `u1 < d`.
1732    #[inline]
1733    pub(crate) const fn div_rem(&self, u1: u64, u0: u64) -> (u64, u64) {
1734        debug_assert!(u1 < self.d, "MG2by1U64::div_rem: high word must be < divisor");
1735        // (q1, q0) = v·u1 + ⟨u1, u0⟩ as u128
1736        let q128 = (self.v as u128).wrapping_mul(u1 as u128)
1737            .wrapping_add(((u1 as u128) << 64) | (u0 as u128));
1738        let mut q1 = (q128 >> 64) as u64;
1739        let q0 = q128 as u64;
1740        q1 = q1.wrapping_add(1);
1741        let mut r = u0.wrapping_sub(q1.wrapping_mul(self.d));
1742        if r > q0 {
1743            q1 = q1.wrapping_sub(1);
1744            r = r.wrapping_add(self.d);
1745        }
1746        if r >= self.d {
1747            q1 = q1.wrapping_add(1);
1748            r = r.wrapping_sub(self.d);
1749        }
1750        (q1, r)
1751    }
1752}
1753
1754/// Möller–Granlund 3-by-2 invariant divisor at u64 base.
1755///
1756/// Divides `(n2·B² + n1·B + n0)` by `(d1·B + d0)` for a normalised
1757/// 2-limb divisor (`d1`'s top bit set) using *two* limbs of divisor
1758/// information, returning a quotient that is exactly correct in one
1759/// pass — no refinement loop is needed in the Knuth Algorithm D
1760/// caller. Compared to [`MG2by1U64`] + the historic Knuth refinement
1761/// loop, the 3-by-2 form trades:
1762///
1763/// - +1 hardware multiply per call (the d0·q step), against
1764/// - up to 2 refinement-loop iterations per quotient limb saved.
1765///
1766/// Net win at every Knuth call with `n ≥ 2` divisor limbs.
1767///
1768/// Reference: Möller & Granlund 2011, Algorithm 5 (the divide) and
1769/// Algorithm 6 (the reciprocal precompute). `MG2by1U64` is the 2-by-1
1770/// cousin used by `limbs_divmod_knuth_u64`'s q̂ estimator.
1771#[derive(Clone, Copy)]
1772pub(crate) struct MG3by2U64 {
1773    d1: u64,
1774    d0: u64,
1775    /// Reciprocal of the top divisor limb (same formula as MG2by1U64::v).
1776    dinv: u64,
1777}
1778
1779impl MG3by2U64 {
1780    /// Setup. `d1` must be normalised (`d1 >> 63 == 1`).
1781    ///
1782    /// Computes the *3-by-2* invariant reciprocal, which differs from
1783    /// the [`MG2by1U64`] 2-by-1 reciprocal by an extra refinement step
1784    /// that accounts for `d0`. Without that refinement the algorithm
1785    /// fails on inputs where the divisor's low limb is large enough
1786    /// to push the q estimate over by more than the corrections can
1787    /// recover (test case: `n=(B-2, B-1, B-1)`, `d=(B-1, B-1)`, where
1788    /// the naive 2-by-1 reciprocal hands back q=0 instead of B-1).
1789    ///
1790    /// Reference: Möller & Granlund 2011, Algorithm 6 (the
1791    /// reciprocal refinement that accounts for `d0`).
1792    #[inline]
1793    pub(crate) const fn new(d1: u64, d0: u64) -> Self {
1794        debug_assert!(d1 >> 63 == 1, "MG3by2U64::new: top divisor limb must be normalised");
1795        // Step 1: 2-by-1 reciprocal of d1 alone.
1796        let num = ((!d1 as u128) << 64) | (u64::MAX as u128);
1797        let mut v = (num / (d1 as u128)) as u64;
1798
1799        // Step 2: refine for d0. `p = d1·v + d0` (mod B). If the sum
1800        // overflows, v was over-estimated → decrement.
1801        let mut p = d1.wrapping_mul(v).wrapping_add(d0);
1802        if p < d0 {
1803            v = v.wrapping_sub(1);
1804            let mask = if p >= d1 { u64::MAX } else { 0 };
1805            p = p.wrapping_sub(d1);
1806            v = v.wrapping_add(mask);
1807            p = p.wrapping_sub(mask & d1);
1808        }
1809
1810        // Step 3: account for d0·v. `(t1, t0) = d0·v`; check if
1811        // `p + t1` overflows; one or two more decrements may be
1812        // required.
1813        let prod = (d0 as u128) * (v as u128);
1814        let t1 = (prod >> 64) as u64;
1815        let t0 = prod as u64;
1816        let (new_p, carry) = p.overflowing_add(t1);
1817        let _p_final = new_p;
1818        if carry {
1819            v = v.wrapping_sub(1);
1820            if new_p >= d1 && (new_p > d1 || t0 >= d0) {
1821                v = v.wrapping_sub(1);
1822            }
1823        }
1824
1825        Self { d1, d0, dinv: v }
1826    }
1827
1828    /// Divide `(n2·B² + n1·B + n0)` by `(d1·B + d0)`. Requires
1829    /// `(n2, n1) < (d1, d0)` so the quotient fits a single u64.
1830    /// Returns `(q, r1, r0)` where the remainder is `r1·B + r0`.
1831    ///
1832    /// Algorithm decomposition (Möller & Granlund 2011, Algorithm 5):
1833    /// 1. Initial `q` from a 2-by-1 divide of `(n2, n1)` by `d1` via
1834    ///    the precomputed reciprocal `dinv`.
1835    /// 2. Subtract `(q·d1, q·d0)` from `(n1, n0)`; this stages the
1836    ///    candidate remainder `(r1, r0)`.
1837    /// 3. Two add-back corrections that fire 0–1 times each: the
1838    ///    first catches `q` over by 1, the second catches the rare
1839    ///    `q` over by 2 (only possible if the initial 2-by-1 reciprocal
1840    ///    over-shot).
1841    #[inline]
1842    pub(crate) const fn div_rem(&self, n2: u64, n1: u64, n0: u64) -> (u64, u64, u64) {
1843        debug_assert!(
1844            n2 < self.d1 || (n2 == self.d1 && n1 < self.d0),
1845            "MG3by2U64::div_rem: numerator high pair must be < divisor"
1846        );
1847
1848        // Step 1: q estimate from (n2, n1) / d1 via dinv.
1849        // (q_hi, q_lo) = n2 * dinv + (n2, n1) — overflow into a 257th
1850        // bit is fine, the mask-based correction (step 4a) recovers
1851        // from it without needing to materialise the lost bit.
1852        let prod = (n2 as u128).wrapping_mul(self.dinv as u128)
1853            .wrapping_add(((n2 as u128) << 64) | (n1 as u128));
1854        let mut q = (prod >> 64) as u64;
1855        let q_lo = prod as u64;
1856
1857        // Step 2a: r1 = n1 - q·d1 (mod B).
1858        let mut r1 = n1.wrapping_sub(q.wrapping_mul(self.d1));
1859
1860        // Step 2b: (r1, r0) = (r1, n0) - (d1, d0).
1861        let r256 = (((r1 as u128) << 64) | (n0 as u128))
1862            .wrapping_sub(((self.d1 as u128) << 64) | (self.d0 as u128));
1863        r1 = (r256 >> 64) as u64;
1864        let mut r0 = r256 as u64;
1865
1866        // Step 2c: (r1, r0) -= d0·q (mod B²).
1867        let t = (self.d0 as u128).wrapping_mul(q as u128);
1868        let r256 = (((r1 as u128) << 64) | (r0 as u128)).wrapping_sub(t);
1869        r1 = (r256 >> 64) as u64;
1870        r0 = r256 as u64;
1871
1872        // Step 3: q += 1; provisional.
1873        q = q.wrapping_add(1);
1874
1875        // Step 4a: first conditional correction.
1876        // If r1 >= q_lo (in u64 numeric), the provisional q was over
1877        // by 1; decrement q and add (d1, d0) back to the remainder.
1878        // Branchless via mask.
1879        let mask = if r1 >= q_lo { u64::MAX } else { 0 };
1880        q = q.wrapping_add(mask); // adds u64::MAX = -1.
1881        let add = ((mask & self.d1) as u128) << 64 | ((mask & self.d0) as u128);
1882        let r256 = (((r1 as u128) << 64) | (r0 as u128)).wrapping_add(add);
1883        r1 = (r256 >> 64) as u64;
1884        r0 = r256 as u64;
1885
1886        // Step 4b: final correction (rare).
1887        // If (r1, r0) >= (d1, d0), q was *still* off by 1; bump q and
1888        // subtract the divisor once more.
1889        if r1 > self.d1 || (r1 == self.d1 && r0 >= self.d0) {
1890            q = q.wrapping_add(1);
1891            let r256 = (((r1 as u128) << 64) | (r0 as u128))
1892                .wrapping_sub(((self.d1 as u128) << 64) | (self.d0 as u128));
1893            r1 = (r256 >> 64) as u64;
1894            r0 = r256 as u64;
1895        }
1896
1897        (q, r1, r0)
1898    }
1899}
1900
1901/// Runtime divide dispatcher at u64 base.
1902pub(crate) fn limbs_divmod_dispatch_u64(
1903    num: &[u64],
1904    den: &[u64],
1905    quot: &mut [u64],
1906    rem: &mut [u64],
1907) {
1908    const BZ_THRESHOLD_U64: usize = 16; // doubled from u128 path's 8.
1909
1910    let mut n = den.len();
1911    while n > 0 && den[n - 1] == 0 {
1912        n -= 1;
1913    }
1914    assert!(n > 0, "limbs_divmod_dispatch_u64: divide by zero");
1915
1916    let mut top = num.len();
1917    while top > 0 && num[top - 1] == 0 {
1918        top -= 1;
1919    }
1920
1921    // Single-limb divisor: defer to const limbs_divmod_u64 (its Fast B
1922    // is one hardware u128/u64 per dividend limb — already optimal).
1923    if n == 1 {
1924        limbs_divmod_u64(num, den, quot, rem);
1925        return;
1926    }
1927
1928    if n >= BZ_THRESHOLD_U64 && top >= 2 * n {
1929        limbs_divmod_bz_u64(num, den, quot, rem);
1930    } else {
1931        limbs_divmod_knuth_u64(num, den, quot, rem);
1932    }
1933}
1934
1935/// Knuth Algorithm D at base 2^64.
1936///
1937/// Same structure as [`limbs_divmod_knuth`] but every limb is a u64
1938/// and the q̂ estimator uses [`MG2by1U64`]. The multiply-subtract pass
1939/// uses native `u64 × u64 → u128`, which collapses one carry-merge
1940/// layer compared to the u128 version's `mul_128`.
1941pub(crate) fn limbs_divmod_knuth_u64(
1942    num: &[u64],
1943    den: &[u64],
1944    quot: &mut [u64],
1945    rem: &mut [u64],
1946) {
1947    for q in quot.iter_mut() {
1948        *q = 0;
1949    }
1950    for r in rem.iter_mut() {
1951        *r = 0;
1952    }
1953
1954    let mut n = den.len();
1955    while n > 0 && den[n - 1] == 0 {
1956        n -= 1;
1957    }
1958    assert!(n > 0, "limbs_divmod_knuth_u64: divide by zero");
1959
1960    let mut top = num.len();
1961    while top > 0 && num[top - 1] == 0 {
1962        top -= 1;
1963    }
1964    if top < n {
1965        let copy_n = num.len().min(rem.len());
1966        let mut i = 0;
1967        while i < copy_n {
1968            rem[i] = num[i];
1969            i += 1;
1970        }
1971        return;
1972    }
1973
1974    let shift = den[n - 1].leading_zeros();
1975    let mut u = [0u64; SCRATCH_LIMBS_U64];
1976    let mut v = [0u64; SCRATCH_LIMBS_U64];
1977    debug_assert!(top < SCRATCH_LIMBS_U64 && n <= SCRATCH_LIMBS_U64);
1978
1979    if shift == 0 {
1980        u[..top].copy_from_slice(&num[..top]);
1981        u[top] = 0;
1982        v[..n].copy_from_slice(&den[..n]);
1983    } else {
1984        let mut carry: u64 = 0;
1985        for i in 0..top {
1986            let val = num[i];
1987            u[i] = (val << shift) | carry;
1988            carry = val >> (64 - shift);
1989        }
1990        u[top] = carry;
1991        carry = 0;
1992        for i in 0..n {
1993            let val = den[i];
1994            v[i] = (val << shift) | carry;
1995            carry = val >> (64 - shift);
1996        }
1997    }
1998
1999    let m_plus_n = if u[top] != 0 { top + 1 } else { top };
2000    debug_assert!(m_plus_n >= n);
2001    let m = m_plus_n - n;
2002
2003    // Knuth Algorithm D requires a multi-limb divisor. Single-limb
2004    // divisors have a much faster hardware divide path; route them
2005    // out here so the hot loop below can assume n >= 2 and lose the
2006    // per-iteration n=1 dispatch.
2007    if n == 1 {
2008        limbs_divmod_u64(num, den, quot, rem);
2009        return;
2010    }
2011
2012    // MG 2-by-1 q̂ estimator (Möller-Granlund 2011 Algorithm 4) +
2013    // inner refinement against v[n-2]. The 3-by-2 estimator was
2014    // re-benched post u64 migration: its per-q̂ setup cost
2015    // (extra multiplies vs the 2-by-1's one) outweighs the
2016    // refinement loop's near-zero iteration count on decimal
2017    // divisors, so 2-by-1 + while-loop still wins at the widest
2018    // tiers.
2019    let v_top = v[n - 1];
2020    let v_below = v[n - 2];
2021    let mg_top = MG2by1U64::new(v_top);
2022
2023    let mut j_plus_one = m + 1;
2024    while j_plus_one > 0 {
2025        j_plus_one -= 1;
2026        let j = j_plus_one;
2027
2028        let jn = j + n;
2029        let u_top = u[jn];
2030        let u_next = u[jn - 1];
2031
2032        // MG 2-by-1 q̂ + (r_hat). Cheap-check `u_top > v_top` first
2033        // — strict greater → q̂ = MAX, no MG call, no refinement
2034        // possible — then handle the `u_top == v_top` edge inline,
2035        // then the common u_top < v_top case via the 2-by-1
2036        // estimator.
2037        let (mut q_hat, mut r_hat) = if u_top > v_top {
2038            (u64::MAX, u64::MAX)
2039        } else if u_top == v_top {
2040            let (r, of) = u_next.overflowing_add(v_top);
2041            (u64::MAX, if of { u64::MAX } else { r })
2042        } else {
2043            mg_top.div_rem(u_top, u_next)
2044        };
2045
2046        // Refinement against v[n-2]. Tightens q̂ from off-by-2 to
2047        // off-by-1; the post-subtract `final_borrow` check below
2048        // catches the remaining off-by-1 case. Almost never fires
2049        // on decimal divisors but cheap when it doesn't.
2050        loop {
2051            let prod = (q_hat as u128) * (v_below as u128);
2052            let hi = (prod >> 64) as u64;
2053            let lo = prod as u64;
2054            let rhs_lo = u[jn - 2];
2055            let rhs_hi = r_hat;
2056            if hi < rhs_hi || (hi == rhs_hi && lo <= rhs_lo) {
2057                break;
2058            }
2059            q_hat = q_hat.wrapping_sub(1);
2060            let (new_r, of) = r_hat.overflowing_add(v_top);
2061            if of {
2062                break;
2063            }
2064            r_hat = new_r;
2065        }
2066
2067        // D4. u[j..=j+n] -= q̂ · v[0..n]
2068        let mut mul_carry: u64 = 0;
2069        let mut borrow: u64 = 0;
2070        for i in 0..n {
2071            let prod = (q_hat as u128) * (v[i] as u128);
2072            let prod_lo = prod as u64;
2073            let prod_hi = (prod >> 64) as u64;
2074            let (s_prod, c1) = prod_lo.overflowing_add(mul_carry);
2075            let new_mul_carry = prod_hi + (c1 as u64);
2076            let (s1, b1) = u[j + i].overflowing_sub(s_prod);
2077            let (s2, b2) = s1.overflowing_sub(borrow);
2078            u[j + i] = s2;
2079            borrow = (b1 as u64) + (b2 as u64);
2080            mul_carry = new_mul_carry;
2081        }
2082        let (s1, b1) = u[j + n].overflowing_sub(mul_carry);
2083        let (s2, b2) = s1.overflowing_sub(borrow);
2084        u[j + n] = s2;
2085        let final_borrow = (b1 as u64) + (b2 as u64);
2086
2087        if final_borrow != 0 {
2088            q_hat = q_hat.wrapping_sub(1);
2089            let mut carry: u64 = 0;
2090            for i in 0..n {
2091                let (s1, c1) = u[j + i].overflowing_add(v[i]);
2092                let (s2, c2) = s1.overflowing_add(carry);
2093                u[j + i] = s2;
2094                carry = (c1 as u64) + (c2 as u64);
2095            }
2096            u[j + n] = u[j + n].wrapping_add(carry);
2097        }
2098
2099        if j < quot.len() {
2100            quot[j] = q_hat;
2101        }
2102    }
2103
2104    if shift == 0 {
2105        let copy_n = n.min(rem.len());
2106        rem[..copy_n].copy_from_slice(&u[..copy_n]);
2107    } else {
2108        for i in 0..n {
2109            if i < rem.len() {
2110                let lo = u[i] >> shift;
2111                let hi_into_lo = if i + 1 < n {
2112                    u[i + 1] << (64 - shift)
2113                } else {
2114                    0
2115                };
2116                rem[i] = lo | hi_into_lo;
2117            }
2118        }
2119    }
2120}
2121
2122/// Burnikel–Ziegler outer chunking, u64 base.
2123pub(crate) fn limbs_divmod_bz_u64(
2124    num: &[u64],
2125    den: &[u64],
2126    quot: &mut [u64],
2127    rem: &mut [u64],
2128) {
2129    const BZ_THRESHOLD_U64: usize = 16;
2130
2131    let mut n = den.len();
2132    while n > 0 && den[n - 1] == 0 {
2133        n -= 1;
2134    }
2135    assert!(n > 0, "limbs_divmod_bz_u64: divide by zero");
2136
2137    let mut top = num.len();
2138    while top > 0 && num[top - 1] == 0 {
2139        top -= 1;
2140    }
2141
2142    if n < BZ_THRESHOLD_U64 || top < 2 * n {
2143        limbs_divmod_knuth_u64(num, den, quot, rem);
2144        return;
2145    }
2146
2147    for q in quot.iter_mut() {
2148        *q = 0;
2149    }
2150    for r in rem.iter_mut() {
2151        *r = 0;
2152    }
2153
2154    let chunks = top.div_ceil(n);
2155    let mut carry = [0u64; SCRATCH_LIMBS_U64];
2156    let mut buf = [0u64; SCRATCH_LIMBS_U64];
2157    let mut q_chunk = [0u64; SCRATCH_LIMBS_U64];
2158    let mut r_chunk = [0u64; SCRATCH_LIMBS_U64];
2159
2160    let mut idx = chunks;
2161    while idx > 0 {
2162        idx -= 1;
2163        let lo = idx * n;
2164        let hi = ((idx + 1) * n).min(top);
2165        buf.fill(0);
2166        let chunk_len = hi - lo;
2167        buf[..chunk_len].copy_from_slice(&num[lo..lo + chunk_len]);
2168        buf[chunk_len..chunk_len + n].copy_from_slice(&carry[..n]);
2169        let buf_len = chunk_len + n;
2170        limbs_divmod_knuth_u64(
2171            &buf[..buf_len],
2172            &den[..n],
2173            &mut q_chunk[..buf_len],
2174            &mut r_chunk[..n],
2175        );
2176        let store_end = (lo + n).min(quot.len());
2177        let store_len = store_end.saturating_sub(lo);
2178        quot[lo..lo + store_len].copy_from_slice(&q_chunk[..store_len]);
2179        carry[..n].copy_from_slice(&r_chunk[..n]);
2180    }
2181    let rem_n = n.min(rem.len());
2182    rem[..rem_n].copy_from_slice(&carry[..rem_n]);
2183}
2184
2185/// `out = floor(sqrt(n))`. Newton iteration on top of the runtime
2186/// divide dispatcher.
2187///
2188/// History: this routine previously called the *const* [`limbs_divmod_u64`]
2189/// per iteration, which routes multi-limb divisors through the
2190/// O(bits²) shift-subtract path. At Int4096 (n=64 u64 limbs) that
2191/// dominates wall time — Newton converges in ~log₂(b) ≈ 12 iterations,
2192/// each one a `~65k`-limb-op divmod. Switching to
2193/// [`limbs_divmod_dispatch_u64`] gets Knuth-base-2⁶⁴ per iteration
2194/// (~`~32²` = 1024 limb-ops), worth ~40× on D307 sqrt.
2195pub(crate) fn limbs_isqrt_u64(n: &[u64], out: &mut [u64]) {
2196    for o in out.iter_mut() {
2197        *o = 0;
2198    }
2199    let bits = limbs_bit_len_u64(n);
2200    if bits == 0 {
2201        return;
2202    }
2203    if bits <= 1 {
2204        out[0] = 1;
2205        return;
2206    }
2207    let work = n.len() + 1;
2208    debug_assert!(work <= SCRATCH_LIMBS_U64, "isqrt scratch overflow");
2209    let mut x = [0u64; SCRATCH_LIMBS_U64];
2210    let e = bits.div_ceil(2);
2211    x[(e / 64) as usize] |= 1u64 << (e % 64);
2212    loop {
2213        let mut q = [0u64; SCRATCH_LIMBS_U64];
2214        let mut r = [0u64; SCRATCH_LIMBS_U64];
2215        limbs_divmod_dispatch_u64(n, &x[..work], &mut q[..work], &mut r[..work]);
2216        limbs_add_assign_u64(&mut q[..work], &x[..work]);
2217        let mut y = [0u64; SCRATCH_LIMBS_U64];
2218        limbs_shr_u64(&q[..work], 1, &mut y[..work]);
2219        if limbs_cmp_u64(&y[..work], &x[..work]) >= 0 {
2220            break;
2221        }
2222        x = y;
2223    }
2224    let copy_len = if out.len() < work { out.len() } else { work };
2225    out[..copy_len].copy_from_slice(&x[..copy_len]);
2226}
2227
2228/// `limbs /= radix` in place, returning the remainder. `radix` must
2229/// be a u64 (so the per-limb divide stays inside `u128 / u64`).
2230fn limbs_div_small_u64(limbs: &mut [u64], radix: u64) -> u64 {
2231    let mut rem: u64 = 0;
2232    for limb in limbs.iter_mut().rev() {
2233        let acc = ((rem as u128) << 64) | (*limb as u128);
2234        *limb = (acc / (radix as u128)) as u64;
2235        rem = (acc % (radix as u128)) as u64;
2236    }
2237    rem
2238}
2239
2240/// Format a u64 limb slice into `buf` in the given radix (`2..=16`).
2241pub(crate) fn limbs_fmt_into_u64<'a>(
2242    limbs: &[u64],
2243    radix: u64,
2244    lower: bool,
2245    buf: &'a mut [u8],
2246) -> &'a str {
2247    let digits: &[u8] = if lower {
2248        b"0123456789abcdef"
2249    } else {
2250        b"0123456789ABCDEF"
2251    };
2252    if limbs_is_zero_u64(limbs) {
2253        let last = buf.len() - 1;
2254        buf[last] = b'0';
2255        return core::str::from_utf8(&buf[last..]).unwrap();
2256    }
2257    let mut work = [0u64; SCRATCH_LIMBS_U64];
2258    work[..limbs.len()].copy_from_slice(limbs);
2259    let wl = limbs.len();
2260    let mut pos = buf.len();
2261    while !limbs_is_zero_u64(&work[..wl]) {
2262        let r = limbs_div_small_u64(&mut work[..wl], radix);
2263        pos -= 1;
2264        buf[pos] = digits[r as usize];
2265    }
2266    core::str::from_utf8(&buf[pos..]).unwrap()
2267}
2268
2269/// Signed three-way compare for u64-limb magnitudes with signs.
2270#[inline]
2271pub(crate) const fn scmp_u64(a_neg: bool, a: &[u64], b_neg: bool, b: &[u64]) -> i32 {
2272    match (a_neg, b_neg) {
2273        (true, false) => -1,
2274        (false, true) => 1,
2275        _ => limbs_cmp_u64(a, b),
2276    }
2277}
2278
2279// ─────────────────────────────────────────────────────────────────────
2280// End of u64 primitives.
2281// ─────────────────────────────────────────────────────────────────────
2282
2283mod macros;
2284use macros::decl_wide_int;
2285
2286
2287/// Signed three-way comparison of two magnitude-limb slices given their
2288/// signs. Returns `-1` / `0` / `1`.
2289#[inline]
2290pub(crate) const fn scmp(a_neg: bool, a: &[u128], b_neg: bool, b: &[u128]) -> i32 {
2291    match (a_neg, b_neg) {
2292        (true, false) => -1,
2293        (false, true) => 1,
2294        _ => limbs_cmp(a, b),
2295    }
2296}
2297
2298/// A signed integer that can be decomposed into a magnitude + sign and
2299/// rebuilt from one — the basis of `wide_cast` (widen / narrow between
2300/// any two widths, or between a wide integer and a primitive
2301/// `i128` / `i64` / `u128`). u64-limb representation throughout, so
2302/// every wide-int's magnitude buffer is directly compatible without
2303/// boundary conversion.
2304pub(crate) trait WideInt: Copy {
2305    /// Magnitude limbs (little-endian u64, zero-padded to 128) and sign.
2306    /// 128 u64 limbs = 8192 bits, comfortably above the widest type
2307    /// the crate ships (Int4096, which is 64 u64 limbs).
2308    fn to_mag_sign(self) -> ([u64; 288], bool);
2309    /// Rebuilds from a magnitude limb slice and a sign, truncating
2310    /// the magnitude to this type's width.
2311    fn from_mag_sign(mag: &[u64], negative: bool) -> Self;
2312}
2313
2314/// Implements `WideInt` for a signed primitive integer. The
2315/// magnitude is split into two u64 limbs (low, high) regardless of
2316/// the source primitive's width — for `i64` the high limb is always
2317/// zero; for `i128` the split carries the upper 64 bits.
2318macro_rules! impl_wideint_signed_prim {
2319    ($($t:ty),*) => {$(
2320        impl WideInt for $t {
2321            #[inline]
2322            fn to_mag_sign(self) -> ([u64; 288], bool) {
2323                let mut out = [0u64; 288];
2324                let mag = self.unsigned_abs() as u128;
2325                out[0] = mag as u64;
2326                out[1] = (mag >> 64) as u64;
2327                (out, self < 0)
2328            }
2329            #[inline]
2330            fn from_mag_sign(mag: &[u64], negative: bool) -> $t {
2331                let lo = mag.first().copied().unwrap_or(0) as u128;
2332                let hi = mag.get(1).copied().unwrap_or(0) as u128;
2333                let combined = lo | (hi << 64);
2334                let m = combined as $t;
2335                if negative { m.wrapping_neg() } else { m }
2336            }
2337        }
2338    )*};
2339}
2340impl_wideint_signed_prim!(i8, i16, i32, i64, i128);
2341
2342impl WideInt for u128 {
2343    #[inline]
2344    fn to_mag_sign(self) -> ([u64; 288], bool) {
2345        let mut out = [0u64; 288];
2346        out[0] = self as u64;
2347        out[1] = (self >> 64) as u64;
2348        (out, false)
2349    }
2350    #[inline]
2351    fn from_mag_sign(mag: &[u64], _negative: bool) -> u128 {
2352        let lo = mag.first().copied().unwrap_or(0) as u128;
2353        let hi = mag.get(1).copied().unwrap_or(0) as u128;
2354        lo | (hi << 64)
2355    }
2356}
2357
2358/// Widening / narrowing cast between any two `WideInt` types via a
2359/// shared magnitude + sign representation.
2360#[inline]
2361pub(crate) fn wide_cast<S: WideInt, T: WideInt>(src: S) -> T {
2362    let (mag, negative) = src.to_mag_sign();
2363    T::from_mag_sign(&mag, negative)
2364}
2365
2366// The concrete wide integer type pairs. The 256/512/1024-bit widths
2367// back the wide decimal tiers; 2048/4096-bit widths are the
2368// strict-transcendental work integers.
2369// $L = u64 limb count; $D = doubled (= 2 · $L) for widening
2370// products. Each Int*'s name encodes the bit width = $L · 64.
2371decl_wide_int!(Uint192, Int192, 3, 6);
2372decl_wide_int!(Uint256, Int256, 4, 8);
2373decl_wide_int!(Uint384, Int384, 6, 12);
2374decl_wide_int!(Uint512, Int512, 8, 16);
2375decl_wide_int!(Uint768, Int768, 12, 24);
2376decl_wide_int!(Uint1024, Int1024, 16, 32);
2377decl_wide_int!(Uint1536, Int1536, 24, 48);
2378decl_wide_int!(Uint2048, Int2048, 32, 64);
2379decl_wide_int!(Uint3072, Int3072, 48, 96);
2380decl_wide_int!(Uint4096, Int4096, 64, 128);
2381decl_wide_int!(Uint6144, Int6144, 96, 192);
2382decl_wide_int!(Uint8192, Int8192, 128, 256);
2383decl_wide_int!(Uint12288, Int12288, 192, 384);
2384decl_wide_int!(Uint16384, Int16384, 256, 512);
2385
2386// Short aliases used by the decimal-tier macros (replacing the former
2387// `crate::wide` re-export shim). The signed alias is exposed at each
2388// width where it backs storage *or* serves as the next-width mul/div
2389// widening step; the unsigned alias only where `Display`'s magnitude
2390// path needs it. The feature gates mirror the call-site features.
2391// Tier aliases — each width gets an `I*` (signed) alias when it
2392// backs storage or serves as a mul/div widening step for some tier,
2393// and a matching `U*` (unsigned) when `Display`'s magnitude path
2394// needs it.
2395#[cfg(any(feature = "d56", feature = "wide"))]
2396pub(crate) use self::{Int192 as I192, Uint192 as U192};
2397#[cfg(any(feature = "d56", feature = "d76", feature = "wide"))]
2398pub(crate) use self::Int384 as I384;
2399#[cfg(any(feature = "d114", feature = "wide"))]
2400pub(crate) use self::Uint384 as U384;
2401#[cfg(any(feature = "d76", feature = "wide"))]
2402pub(crate) use self::{Int256 as I256, Uint256 as U256};
2403#[cfg(any(feature = "d76", feature = "d114", feature = "d153", feature = "wide"))]
2404pub(crate) use self::Int512 as I512;
2405#[cfg(any(feature = "d153", feature = "wide"))]
2406pub(crate) use self::Uint512 as U512;
2407#[cfg(any(feature = "d114", feature = "d153", feature = "d230", feature = "wide"))]
2408pub(crate) use self::Int768 as I768;
2409#[cfg(any(feature = "d230", feature = "wide"))]
2410pub(crate) use self::Uint768 as U768;
2411#[cfg(any(feature = "d153", feature = "d230", feature = "d307", feature = "wide", feature = "x-wide"))]
2412pub(crate) use self::Int1024 as I1024;
2413#[cfg(any(feature = "d230", feature = "d307", feature = "d461", feature = "wide", feature = "x-wide"))]
2414pub(crate) use self::Int1536 as I1536;
2415#[cfg(any(feature = "d461", feature = "x-wide"))]
2416pub(crate) use self::Uint1536 as U1536;
2417#[cfg(any(feature = "d307", feature = "d461", feature = "d615", feature = "wide", feature = "x-wide"))]
2418pub(crate) use self::{Int2048 as I2048, Uint1024 as U1024};
2419#[cfg(any(feature = "d615", feature = "x-wide"))]
2420pub(crate) use self::Uint2048 as U2048;
2421#[cfg(any(feature = "d461", feature = "d615", feature = "d923", feature = "x-wide", feature = "xx-wide"))]
2422pub(crate) use self::Int3072 as I3072;
2423#[cfg(any(feature = "d923", feature = "xx-wide"))]
2424pub(crate) use self::Uint3072 as U3072;
2425#[cfg(any(feature = "d615", feature = "d923", feature = "d1231", feature = "x-wide", feature = "xx-wide"))]
2426pub(crate) use self::Int4096 as I4096;
2427#[cfg(any(feature = "d1231", feature = "xx-wide"))]
2428pub(crate) use self::Uint4096 as U4096;
2429#[cfg(any(feature = "d923", feature = "d1231", feature = "xx-wide"))]
2430pub(crate) use self::Int6144 as I6144;
2431#[cfg(any(feature = "d1231", feature = "xx-wide"))]
2432pub(crate) use self::Int8192 as I8192;
2433#[cfg(any(feature = "d923", feature = "xx-wide"))]
2434#[allow(unused_imports)]
2435pub(crate) use self::Int12288 as I12288;
2436#[cfg(any(feature = "d1231", feature = "xx-wide"))]
2437#[allow(unused_imports)]
2438pub(crate) use self::Int16384 as I16384;
2439
2440#[cfg(test)]
2441mod karatsuba_tests {
2442    use super::*;
2443
2444    /// Karatsuba and schoolbook must agree bit-for-bit on every
2445    /// equal-length input that meets the threshold.
2446    #[test]
2447    fn karatsuba_matches_schoolbook_at_n16() {
2448        let a: [u128; 16] = core::array::from_fn(|i| (i as u128) * 0xdead_beef + 1);
2449        let b: [u128; 16] = core::array::from_fn(|i| 0xcafe_babe ^ ((i as u128) << 5));
2450        let mut s = [0u128; 32];
2451        let mut k = [0u128; 32];
2452        limbs_mul(&a, &b, &mut s);
2453        limbs_mul_karatsuba(&a, &b, &mut k);
2454        assert_eq!(s, k);
2455    }
2456
2457    #[test]
2458    fn karatsuba_matches_schoolbook_at_n32() {
2459        let a: [u128; 32] = core::array::from_fn(|i| (i as u128).wrapping_mul(0x1234_5678_9abc));
2460        let b: [u128; 32] = core::array::from_fn(|i| (i as u128 + 1).wrapping_mul(0xfedc_ba98));
2461        let mut s = [0u128; 64];
2462        let mut k = [0u128; 64];
2463        limbs_mul(&a, &b, &mut s);
2464        limbs_mul_karatsuba(&a, &b, &mut k);
2465        assert_eq!(s, k);
2466    }
2467
2468    #[test]
2469    fn karatsuba_handles_zero_inputs() {
2470        let a = [0u128; 16];
2471        let b: [u128; 16] = core::array::from_fn(|i| (i as u128) + 1);
2472        let mut k = [0u128; 32];
2473        limbs_mul_karatsuba(&a, &b, &mut k);
2474        for o in &k {
2475            assert_eq!(*o, 0);
2476        }
2477    }
2478}
2479
2480#[cfg(test)]
2481mod hint_tests {
2482    use super::*;
2483
2484    #[test]
2485    fn signed_add_sub_neg() {
2486        let a = Int256::from_i128(5);
2487        let b = Int256::from_i128(3);
2488        assert_eq!(a.wrapping_add(b), Int256::from_i128(8));
2489        assert_eq!(a.wrapping_sub(b), Int256::from_i128(2));
2490        assert_eq!(b.wrapping_sub(a), Int256::from_i128(-2));
2491        assert_eq!(a.negate(), Int256::from_i128(-5));
2492        assert_eq!(Int256::ZERO.negate(), Int256::ZERO);
2493    }
2494
2495    #[test]
2496    fn signed_mul_div_rem() {
2497        let six = Int512::from_i128(6);
2498        let two = Int512::from_i128(2);
2499        let three = Int512::from_i128(3);
2500        assert_eq!(six.wrapping_mul(three), Int512::from_i128(18));
2501        assert_eq!(six.wrapping_div(two), three);
2502        assert_eq!(Int512::from_i128(7).wrapping_rem(three), Int512::from_i128(1));
2503        assert_eq!(Int512::from_i128(-7).wrapping_rem(three), Int512::from_i128(-1));
2504        assert_eq!(six.negate().wrapping_mul(three), Int512::from_i128(-18));
2505    }
2506
2507    #[test]
2508    fn checked_overflow() {
2509        assert_eq!(Int256::MAX.checked_add(Int256::ONE), None);
2510        assert_eq!(Int256::MIN.checked_sub(Int256::ONE), None);
2511        assert_eq!(Int256::MIN.checked_neg(), None);
2512        assert_eq!(
2513            Int256::from_i128(2).checked_add(Int256::from_i128(3)),
2514            Some(Int256::from_i128(5))
2515        );
2516    }
2517
2518    #[test]
2519    fn from_str_and_pow() {
2520        let ten = Int1024::from_str_radix("10", 10).unwrap();
2521        assert_eq!(ten, Int1024::from_i128(10));
2522        assert_eq!(ten.pow(3), Int1024::from_i128(1000));
2523        let big = Int1024::from_str_radix("10", 10).unwrap().pow(40);
2524        let from_str = Int1024::from_str_radix(
2525            "10000000000000000000000000000000000000000",
2526            10,
2527        )
2528        .unwrap();
2529        assert_eq!(big, from_str);
2530        assert_eq!(Int256::from_str_radix("-42", 10).unwrap(), Int256::from_i128(-42));
2531    }
2532
2533    #[test]
2534    fn ordering_and_resize() {
2535        assert!(Int256::from_i128(-1) < Int256::ZERO);
2536        assert!(Int256::MIN < Int256::MAX);
2537        let v = Int256::from_i128(-123_456_789);
2538        let wide: Int1024 = v.resize();
2539        let back: Int256 = wide.resize();
2540        assert_eq!(back, v);
2541        assert_eq!(wide, Int1024::from_i128(-123_456_789));
2542    }
2543
2544    #[test]
2545    fn isqrt_and_f64() {
2546        assert_eq!(Int512::from_i128(144).isqrt(), Int512::from_i128(12));
2547        assert_eq!(Int256::from_i128(1_000_000).as_f64(), 1_000_000.0);
2548        assert_eq!(Int256::from_f64(-2_500.0), Int256::from_i128(-2500));
2549    }
2550
2551    /// `Uint256` (the unsigned macro emission) supports the same
2552    /// bit/sign-manipulation surface as the signed sibling. Methods
2553    /// here are reachable through the wide decimal types but not always
2554    /// exercised by name; verify the contracts directly.
2555    #[test]
2556    fn uint256_is_zero_and_bit_helpers() {
2557        let zero = Uint256::ZERO;
2558        let one = Uint256::from_str_radix("1", 10).unwrap();
2559        let two = Uint256::from_str_radix("2", 10).unwrap();
2560        assert!(zero.is_zero());
2561        assert!(!one.is_zero());
2562        assert!(one.is_power_of_two());
2563        assert!(two.is_power_of_two());
2564        let three = Uint256::from_str_radix("3", 10).unwrap();
2565        assert!(!three.is_power_of_two());
2566        // next_power_of_two(0) == 1
2567        assert_eq!(zero.next_power_of_two(), one);
2568        // next_power_of_two(1) == 1 (already power of two)
2569        assert_eq!(one.next_power_of_two(), one);
2570        // next_power_of_two(3) == 4
2571        let four = Uint256::from_str_radix("4", 10).unwrap();
2572        assert_eq!(three.next_power_of_two(), four);
2573        // count_ones / leading_zeros
2574        assert_eq!(zero.count_ones(), 0);
2575        assert_eq!(one.count_ones(), 1);
2576        assert_eq!(zero.leading_zeros(), Uint256::BITS);
2577        assert_eq!(one.leading_zeros(), Uint256::BITS - 1);
2578    }
2579
2580    #[test]
2581    fn uint256_parse_arithmetic_and_pow() {
2582        // from_str_radix only accepts radix 10.
2583        assert!(Uint256::from_str_radix("10", 2).is_err());
2584        // Non-digit byte rejected.
2585        assert!(Uint256::from_str_radix("1a", 10).is_err());
2586        // Arithmetic: 3 - 2 = 1, 6 / 2 = 3, 7 % 3 = 1, 3·3 = 9.
2587        let two = Uint256::from_str_radix("2", 10).unwrap();
2588        let three = Uint256::from_str_radix("3", 10).unwrap();
2589        let six = Uint256::from_str_radix("6", 10).unwrap();
2590        let seven = Uint256::from_str_radix("7", 10).unwrap();
2591        assert_eq!(three - two, Uint256::from_str_radix("1", 10).unwrap());
2592        assert_eq!(six / two, three);
2593        assert_eq!(seven % three, Uint256::from_str_radix("1", 10).unwrap());
2594        // BitAnd / BitOr / BitXor
2595        let five = Uint256::from_str_radix("5", 10).unwrap();  // 101
2596        let four = Uint256::from_str_radix("4", 10).unwrap();  // 100
2597        let one = Uint256::from_str_radix("1", 10).unwrap();   // 001
2598        assert_eq!(five & four, four);                       // 100
2599        assert_eq!(five | one, five);                        // 101
2600        assert_eq!(five ^ four, one);                        // 001
2601        // pow: 2^10 = 1024
2602        let p10 = two.pow(10);
2603        assert_eq!(p10, Uint256::from_str_radix("1024", 10).unwrap());
2604        // cast_signed round-trip
2605        let signed = three.cast_signed();
2606        assert_eq!(signed, Int256::from_i128(3));
2607    }
2608
2609    /// `Int256::bit` reports the two's-complement bit at any index;
2610    /// indices past the storage width return the sign bit.
2611    #[test]
2612    fn signed_bit_and_trailing_zeros() {
2613        let v = Int256::from_i128(0b1100);
2614        assert!(v.bit(2));
2615        assert!(v.bit(3));
2616        assert!(!v.bit(0));
2617        assert!(!v.bit(1));
2618        // Out-of-range bit returns the sign — non-negative for v.
2619        assert!(!v.bit(1000));
2620        // Negative input: sign bit returns true past the storage.
2621        let n = Int256::from_i128(-1);
2622        assert!(n.bit(1000));
2623        // trailing_zeros
2624        assert_eq!(Int256::from_i128(8).trailing_zeros(), 3);
2625        assert_eq!(Int256::ZERO.trailing_zeros(), Int256::BITS);
2626    }
2627}
2628
2629#[cfg(test)]
2630mod slice_tests {
2631    use super::*;
2632
2633    #[test]
2634    fn mul_and_divmod_round_trip() {
2635        let a = [123u128, 7, 0, 0];
2636        let b = [456u128, 0, 0, 0];
2637        let mut prod = [0u128; 8];
2638        limbs_mul(&a, &b, &mut prod);
2639        let mut q = [0u128; 8];
2640        let mut r = [0u128; 8];
2641        limbs_divmod(&prod, &b, &mut q, &mut r);
2642        assert_eq!(&q[..4], &a, "quotient");
2643        assert!(limbs_is_zero(&r), "remainder");
2644    }
2645
2646    #[test]
2647    fn shifts() {
2648        let a = [1u128, 0];
2649        let mut out = [0u128; 2];
2650        limbs_shl(&a, 130, &mut out);
2651        assert_eq!(out, [0, 4]);
2652        let mut back = [0u128; 2];
2653        limbs_shr(&out, 130, &mut back);
2654        assert_eq!(back, [1, 0]);
2655    }
2656
2657    #[test]
2658    fn isqrt_basic() {
2659        let n = [0u128, 0, 1, 0];
2660        let mut out = [0u128; 4];
2661        limbs_isqrt(&n, &mut out);
2662        assert_eq!(out, [0, 1, 0, 0]);
2663        let n = [144u128, 0];
2664        let mut out = [0u128; 2];
2665        limbs_isqrt(&n, &mut out);
2666        assert_eq!(out, [12, 0]);
2667        let n = [2u128, 0];
2668        let mut out = [0u128; 2];
2669        limbs_isqrt(&n, &mut out);
2670        assert_eq!(out, [1, 0]);
2671    }
2672
2673    #[test]
2674    fn add_sub_carry() {
2675        let mut a = [u128::MAX, 0];
2676        let carry = limbs_add_assign(&mut a, &[1, 0]);
2677        assert!(!carry);
2678        assert_eq!(a, [0, 1]);
2679        let borrow = limbs_sub_assign(&mut a, &[1, 0]);
2680        assert!(!borrow);
2681        assert_eq!(a, [u128::MAX, 0]);
2682    }
2683
2684    /// `div_2_by_1` matches the obvious `(high·2^128 + low) / d`
2685    /// formula on representative inputs.
2686    #[test]
2687    fn div_2_by_1_basics() {
2688        // 1 / 1 = 1 r 0.
2689        assert_eq!(div_2_by_1(0, 1, 1), (1, 0));
2690        // 5 / 2 = 2 r 1.
2691        assert_eq!(div_2_by_1(0, 5, 2), (2, 1));
2692        // (3·2^128) / 4 = 3·2^126 r 0.
2693        assert_eq!(div_2_by_1(3, 0, 4), (3 << 126, 0));
2694        // High limb just under divisor — exercises the r_top overflow
2695        // recovery in the inner loop.
2696        let d = u128::MAX - 7;
2697        let (q, r) = div_2_by_1(d - 1, u128::MAX, d);
2698        // q · d + r == (d−1)·2^128 + (2^128 − 1)
2699        let (mul_hi, mul_lo) = mul_128(q, d);
2700        let (sum_lo, c) = mul_lo.overflowing_add(r);
2701        let sum_hi = mul_hi + c as u128;
2702        assert_eq!(sum_hi, d - 1);
2703        assert_eq!(sum_lo, u128::MAX);
2704        assert!(r < d);
2705    }
2706
2707    // ── u64-primitive equivalence: u64 versions vs u128 oracle ──────
2708
2709    /// Pack a `[u128; N]` little-endian limb array into `[u64; 2*N]`.
2710    fn pack(limbs: &[u128]) -> alloc::vec::Vec<u64> {
2711        let mut out = alloc::vec![0u64; 2 * limbs.len()];
2712        for (i, &l) in limbs.iter().enumerate() {
2713            out[2 * i] = l as u64;
2714            out[2 * i + 1] = (l >> 64) as u64;
2715        }
2716        out
2717    }
2718
2719    /// Unpack a `[u64; 2*N]` slice into a `[u128; N]` vec.
2720    fn unpack(words: &[u64]) -> alloc::vec::Vec<u128> {
2721        assert!(words.len() % 2 == 0);
2722        let mut out = alloc::vec![0u128; words.len() / 2];
2723        for i in 0..out.len() {
2724            out[i] = (words[2 * i] as u128) | ((words[2 * i + 1] as u128) << 64);
2725        }
2726        out
2727    }
2728
2729    fn corpus() -> alloc::vec::Vec<alloc::vec::Vec<u128>> {
2730        alloc::vec![
2731            alloc::vec![0u128, 0, 0, 0],
2732            alloc::vec![1u128, 0, 0, 0],
2733            alloc::vec![u128::MAX, 0, 0, 0],
2734            alloc::vec![u128::MAX, u128::MAX, 0, 0],
2735            alloc::vec![u128::MAX, u128::MAX, u128::MAX, u128::MAX],
2736            alloc::vec![123u128, 456, 0, 0],
2737            alloc::vec![
2738                0x1234_5678_9abc_def0_fedc_ba98_7654_3210_u128,
2739                0xa5a5_a5a5_5a5a_5a5a_3c3c_3c3c_c3c3_c3c3,
2740                0,
2741                0,
2742            ],
2743        ]
2744    }
2745
2746    /// `limbs_mul_u64` matches `limbs_mul` after pack/unpack on the
2747    /// shared corpus.
2748    #[test]
2749    fn limbs_mul_u64_matches_u128() {
2750        for a in corpus() {
2751            for b in corpus() {
2752                let mut out128 = alloc::vec![0u128; a.len() + b.len()];
2753                limbs_mul(&a, &b, &mut out128);
2754
2755                let a64 = pack(&a);
2756                let b64 = pack(&b);
2757                let mut out64 = alloc::vec![0u64; a64.len() + b64.len()];
2758                limbs_mul_u64(&a64, &b64, &mut out64);
2759
2760                assert_eq!(unpack(&out64), out128, "limbs_mul mismatch");
2761            }
2762        }
2763    }
2764
2765    /// `limbs_mul_karatsuba_u64` matches `limbs_mul_u64` on equal-length
2766    /// operands across the carry-stressing corpus. Proves the recursive
2767    /// split + recombine algebra holds for the worst-case inputs.
2768    #[test]
2769    fn limbs_mul_karatsuba_u64_matches_schoolbook() {
2770        for a in corpus() {
2771            for b in corpus() {
2772                let a64 = pack(&a);
2773                let b64 = pack(&b);
2774                let n = a64.len().min(b64.len());
2775                if n < super::KARATSUBA_THRESHOLD_U64 {
2776                    continue;
2777                }
2778                let mut a_buf = alloc::vec![0u64; n];
2779                let mut b_buf = alloc::vec![0u64; n];
2780                a_buf.copy_from_slice(&a64[..n]);
2781                b_buf.copy_from_slice(&b64[..n]);
2782                let mut out_school = alloc::vec![0u64; 2 * n];
2783                let mut out_kara = alloc::vec![0u64; 2 * n];
2784                limbs_mul_u64(&a_buf, &b_buf, &mut out_school);
2785                limbs_mul_karatsuba_u64(&a_buf, &b_buf, &mut out_kara);
2786                assert_eq!(out_kara, out_school, "Karatsuba mismatch at n={n}");
2787            }
2788        }
2789    }
2790
2791    /// `limbs_mul_u64_fixed::<L, D>` matches `limbs_mul_u64` at
2792    /// a representative set of compile-time `L` values covering
2793    /// every wide tier (D38..D1231). Each L gets its own
2794    /// monomorphisation; the test confirms the unrolled-by-LLVM
2795    /// fixed-array path produces the same output as the slice
2796    /// path for every shape in the carry-stressing corpus.
2797    #[test]
2798    fn limbs_mul_u64_fixed_matches_slice() {
2799        macro_rules! check {
2800            ($L:expr, $D:expr) => {{
2801                for a in corpus() {
2802                    for b in corpus() {
2803                        let a64 = pack(&a);
2804                        let b64 = pack(&b);
2805                        if a64.len() < $L || b64.len() < $L {
2806                            continue;
2807                        }
2808                        let mut a_arr = [0u64; $L];
2809                        let mut b_arr = [0u64; $L];
2810                        a_arr.copy_from_slice(&a64[..$L]);
2811                        b_arr.copy_from_slice(&b64[..$L]);
2812                        let mut out_slice = alloc::vec![0u64; $D];
2813                        let mut out_fixed = [0u64; $D];
2814                        limbs_mul_u64(&a_arr, &b_arr, &mut out_slice);
2815                        limbs_mul_u64_fixed::<$L, $D>(&a_arr, &b_arr, &mut out_fixed);
2816                        assert_eq!(
2817                            &out_slice[..],
2818                            &out_fixed[..],
2819                            "limbs_mul_u64_fixed::<{}, {}> mismatch",
2820                            $L, $D
2821                        );
2822                    }
2823                }
2824            }};
2825        }
2826        check!(2, 4);
2827        check!(4, 8);
2828        check!(8, 16);
2829        check!(16, 32);
2830        check!(24, 48);
2831        check!(32, 64);
2832        check!(48, 96);
2833        check!(64, 128);
2834    }
2835
2836    /// `limbs_divmod_u64` matches `limbs_divmod`.
2837    #[test]
2838    fn limbs_divmod_u64_matches_u128() {
2839        for num in corpus() {
2840            for den in corpus() {
2841                if den.iter().all(|&x| x == 0) {
2842                    continue;
2843                }
2844                let mut q128 = alloc::vec![0u128; num.len()];
2845                let mut r128 = alloc::vec![0u128; num.len()];
2846                limbs_divmod(&num, &den, &mut q128, &mut r128);
2847
2848                let n64 = pack(&num);
2849                let d64 = pack(&den);
2850                let mut q64 = alloc::vec![0u64; n64.len()];
2851                let mut r64 = alloc::vec![0u64; n64.len()];
2852                limbs_divmod_u64(&n64, &d64, &mut q64, &mut r64);
2853
2854                assert_eq!(unpack(&q64), q128, "divmod q mismatch");
2855                assert_eq!(unpack(&r64), r128, "divmod r mismatch");
2856            }
2857        }
2858    }
2859
2860    /// `limbs_divmod_knuth_u64` matches `limbs_divmod_knuth`.
2861    #[test]
2862    fn limbs_divmod_knuth_u64_matches_u128() {
2863        for num in corpus() {
2864            for den in corpus() {
2865                if den.iter().all(|&x| x == 0) {
2866                    continue;
2867                }
2868                let mut q128 = alloc::vec![0u128; num.len()];
2869                let mut r128 = alloc::vec![0u128; num.len()];
2870                limbs_divmod_knuth(&num, &den, &mut q128, &mut r128);
2871
2872                let n64 = pack(&num);
2873                let d64 = pack(&den);
2874                let mut q64 = alloc::vec![0u64; n64.len()];
2875                let mut r64 = alloc::vec![0u64; n64.len()];
2876                limbs_divmod_knuth_u64(&n64, &d64, &mut q64, &mut r64);
2877
2878                assert_eq!(unpack(&q64), q128, "knuth q mismatch");
2879                assert_eq!(unpack(&r64), r128, "knuth r mismatch");
2880            }
2881        }
2882    }
2883
2884    /// `MG3by2U64` matches the `limbs_divmod_u64` oracle on a
2885    /// representative corpus. Tests the corner cases that historically
2886    /// broke MG 3-by-2 implementations: numerator near divisor (so the
2887    /// initial q estimate may overshoot by 2), minimal normalised d1
2888    /// (= B/2), maximal d1, and the paper's worst-case corner where r1
2889    /// must compare against q_lo without underflow.
2890    #[test]
2891    fn mg3by2_u64_matches_reference() {
2892        let cases: &[(u64, u64, u64, u64, u64)] = &[
2893            // (n2, n1, n0, d1, d0) — d1 normalised, (n2, n1) < (d1, d0).
2894            // Minimal normalised d1 = B/2.
2895            (0, 0, 1, 1u64 << 63, 0),
2896            (0, 1, 0, 1u64 << 63, 0),
2897            ((1u64 << 63) - 1, u64::MAX, u64::MAX, 1u64 << 63, 1),
2898            // Maximal d1 = B-1.
2899            (u64::MAX - 1, u64::MAX, u64::MAX, u64::MAX, u64::MAX),
2900            (0, 0, 1, u64::MAX, 1),
2901            // Mid-range divisor; numerator just under (d1, d0).
2902            (0xc0ffee, 0xdead_beef, 0xface_b00c, (1u64 << 63) | 0xc0ffee_u64, 0xdead_beef_face_b00c),
2903            // Small numerator vs large divisor (quotient = 0).
2904            (0, 1, 2, (1u64 << 63) | 1, 2),
2905            // Numerator = divisor (quotient = 1, remainder = 0). Need to
2906            // express (d1, d0, 0) carefully: n2 = 0, then we'd violate
2907            // the precondition. Skip; this is a degenerate corner the
2908            // Knuth caller never hits.
2909        ];
2910        for &(n2, n1, n0, d1, d0) in cases {
2911            assert!(d1 >> 63 == 1, "d1 not normalised: {d1:#x}");
2912            assert!(
2913                n2 < d1 || (n2 == d1 && n1 < d0),
2914                "test precondition (n2, n1) < (d1, d0) violated"
2915            );
2916            let mg = MG3by2U64::new(d1, d0);
2917            let (q, r1, r0) = mg.div_rem(n2, n1, n0);
2918
2919            // Reference: 3-limb numerator / 2-limb divisor via
2920            // limbs_divmod_u64. The function requires
2921            // `rem.len() >= num.len()` so size both at 3.
2922            let num = alloc::vec![n0, n1, n2];
2923            let den = alloc::vec![d0, d1];
2924            let mut q_ref = alloc::vec![0u64; 3];
2925            let mut r_ref = alloc::vec![0u64; 3];
2926            limbs_divmod_u64(&num, &den, &mut q_ref, &mut r_ref);
2927
2928            assert_eq!(q_ref[0], q, "MG3by2 q mismatch for n=({n2:#x},{n1:#x},{n0:#x}) d=({d1:#x},{d0:#x})");
2929            assert_eq!(q_ref[1], 0, "MG3by2 q higher limb non-zero — precondition violated");
2930            assert_eq!(q_ref[2], 0, "MG3by2 q higher limb non-zero — precondition violated");
2931            assert_eq!(r_ref[0], r0, "MG3by2 r0 mismatch");
2932            assert_eq!(r_ref[1], r1, "MG3by2 r1 mismatch");
2933        }
2934    }
2935
2936    /// `MG2by1U64` matches a reference 2-by-1 divide.
2937    #[test]
2938    fn mg2by1_u64_matches_reference() {
2939        let cases: &[(u64, u64, u64)] = &[
2940            (0, 1, 1u64 << 63),
2941            (0, u64::MAX, 1u64 << 63),
2942            ((1u64 << 63) - 1, u64::MAX, 1u64 << 63),
2943            (0, 1, u64::MAX),
2944            (u64::MAX - 1, u64::MAX, u64::MAX),
2945            (12345, 67890, (1u64 << 63) | 0xdead_beef_u64),
2946            (u64::MAX - 1, 0, u64::MAX),
2947        ];
2948        for &(u1, u0, d) in cases {
2949            assert!(d >> 63 == 1);
2950            assert!(u1 < d);
2951            let mg = MG2by1U64::new(d);
2952            let (q, r) = mg.div_rem(u1, u0);
2953            // Reference: ((u1 as u128) << 64 | u0 as u128) / (d as u128)
2954            let num = ((u1 as u128) << 64) | (u0 as u128);
2955            let exp_q = (num / (d as u128)) as u64;
2956            let exp_r = (num % (d as u128)) as u64;
2957            assert_eq!((q, r), (exp_q, exp_r), "MG u64 mismatch for {u1:#x}, {u0:#x}, d={d:#x}");
2958        }
2959    }
2960
2961    /// `MG2by1::div_rem` bit-exact matches `div_2_by_1` on a
2962    /// battery of corner cases that historically broke 2-by-1 MG
2963    /// implementations: maximal numerator with minimal-normalised
2964    /// divisor (forces the +1 step's u128 overflow), boundary
2965    /// q̂ = u128::MAX, exact divides, and the smallest divisor that
2966    /// satisfies the normalisation requirement (`d` with top bit
2967    /// set and otherwise zero, i.e. `B/2`).
2968    #[test]
2969    fn mg2by1_matches_div_2_by_1() {
2970        // For each (u1, u0, d), the precondition is `u1 < d` and
2971        // `d >> 127 == 1` (normalised).
2972        let cases: &[(u128, u128, u128)] = &[
2973            // Minimal normalised divisor (d = B/2).
2974            (0, 1, 1u128 << 127),
2975            (0, u128::MAX, 1u128 << 127),
2976            ((1u128 << 127) - 1, u128::MAX, 1u128 << 127),
2977            // Maximal divisor (d = u128::MAX = B-1).
2978            (0, 1, u128::MAX),
2979            (u128::MAX - 1, u128::MAX, u128::MAX),
2980            // The exact corner case worked through in the docs:
2981            // u1 = B-2, u0 = B-1, d = B-1 → (q, r) = (B-1, B-2).
2982            (u128::MAX - 1, u128::MAX, u128::MAX),
2983            // Mid-range with mid-range divisor.
2984            (12345, 67890, (1u128 << 127) | 0xdead_beefu128),
2985            // Numerator equals divisor minus one in the high limb —
2986            // exercises the "q̂ = u128::MAX" path.
2987            (u128::MAX - 1, 0, u128::MAX),
2988            // Random spread.
2989            (0x1234_5678_9abc_def0_u128 ^ 0xa5a5, 0xfedc_ba98_7654_3210_u128, (1u128 << 127) | 0xc0ffee_u128),
2990        ];
2991        for &(u1, u0, d) in cases {
2992            assert!(d >> 127 == 1, "test divisor not normalised: {d:#x}");
2993            assert!(u1 < d, "test precondition u1 < d violated: {u1:#x} >= {d:#x}");
2994            let (q_ref, r_ref) = div_2_by_1(u1, u0, d);
2995            let mg = MG2by1::new(d);
2996            let (q_mg, r_mg) = mg.div_rem(u1, u0);
2997            assert_eq!(
2998                (q_mg, r_mg),
2999                (q_ref, r_ref),
3000                "MG2by1 disagrees with div_2_by_1 for (u1={u1:#x}, u0={u0:#x}, d={d:#x})"
3001            );
3002        }
3003    }
3004
3005    /// `limbs_divmod_knuth` agrees with the canonical `limbs_divmod`
3006    /// on a battery of representative shapes — single-limb divisors,
3007    /// multi-limb divisors, zero remainders, partial overflows in the
3008    /// q̂ refinement step.
3009    #[test]
3010    fn knuth_matches_canonical_divmod() {
3011        let cases: &[(&[u128], &[u128])] = &[
3012            // Simple
3013            (&[42], &[7]),
3014            (&[u128::MAX, 0], &[2]),
3015            // Multi-limb numerator, single-limb denominator.
3016            (&[1, 1, 0, 0], &[3]),
3017            // Multi-limb both — three-limb numerator by two-limb den.
3018            (&[u128::MAX, u128::MAX, 1, 0], &[5, 9]),
3019            // Three-limb both.
3020            (&[u128::MAX, u128::MAX, u128::MAX, 0], &[1, 2, 3]),
3021            // Numerator < denominator — quotient zero, remainder = num.
3022            (&[100, 0, 0], &[200, 0, 1]),
3023            // Equal high limbs (forces the u_top ≥ v_top branch).
3024            (
3025                &[0, 0, u128::MAX, u128::MAX],
3026                &[1, 2, u128::MAX],
3027            ),
3028        ];
3029        for (num, den) in cases {
3030            let mut q_canon = [0u128; 8];
3031            let mut r_canon = [0u128; 8];
3032            limbs_divmod(num, den, &mut q_canon, &mut r_canon);
3033            let mut q_knuth = [0u128; 8];
3034            let mut r_knuth = [0u128; 8];
3035            limbs_divmod_knuth(num, den, &mut q_knuth, &mut r_knuth);
3036            assert_eq!(q_canon, q_knuth, "quotient mismatch on {:?} / {:?}", num, den);
3037            assert_eq!(r_canon, r_knuth, "remainder mismatch on {:?} / {:?}", num, den);
3038        }
3039    }
3040
3041    /// `limbs_divmod_bz` agrees with the canonical path on
3042    /// medium-and-large operands. Recursion engages only above the
3043    /// `BZ_THRESHOLD = 8` limb cutoff.
3044    #[test]
3045    fn bz_matches_canonical_divmod() {
3046        // Builds a 16-limb dividend with a 10-limb divisor — well
3047        // above BZ_THRESHOLD so the recursive path is exercised.
3048        let mut num = [0u128; 16];
3049        for (i, slot) in num.iter_mut().enumerate() {
3050            *slot = (i as u128)
3051                .wrapping_mul(0x9E37_79B9_7F4A_7C15)
3052                .wrapping_add(i as u128);
3053        }
3054        let mut den = [0u128; 10];
3055        for (i, slot) in den.iter_mut().enumerate() {
3056            *slot = ((i + 1) as u128).wrapping_mul(0xBF58_476D_1CE4_E5B9);
3057        }
3058        let mut q_canon = [0u128; 16];
3059        let mut r_canon = [0u128; 16];
3060        limbs_divmod(&num, &den, &mut q_canon, &mut r_canon);
3061        let mut q_bz = [0u128; 16];
3062        let mut r_bz = [0u128; 16];
3063        limbs_divmod_bz(&num, &den, &mut q_bz, &mut r_bz);
3064        assert_eq!(q_canon, q_bz, "BZ quotient mismatch");
3065        assert_eq!(r_canon, r_bz, "BZ remainder mismatch");
3066    }
3067
3068    /// `limbs_mul_fast` dispatches to Karatsuba when both operands are
3069    /// equal-length ≥ `KARATSUBA_MIN`. Verify by comparing the result
3070    /// against schoolbook (`limbs_mul`) on a 16-limb pair.
3071    #[cfg(feature = "alloc")]
3072    #[test]
3073    fn fast_mul_dispatches_to_karatsuba_at_threshold() {
3074        let a: [u128; 16] = core::array::from_fn(|i| (i as u128).wrapping_mul(0xABCD) + 1);
3075        let b: [u128; 16] = core::array::from_fn(|i| (i as u128).wrapping_mul(0xBEEF) + 7);
3076        let mut fast = [0u128; 32];
3077        let mut school = [0u128; 32];
3078        limbs_mul_fast(&a, &b, &mut fast);
3079        limbs_mul(&a, &b, &mut school);
3080        assert_eq!(fast, school, "fast (Karatsuba) and schoolbook disagree");
3081    }
3082
3083    /// `limbs_mul_fast` falls through to schoolbook for unequal lengths
3084    /// or below the threshold. The 8-limb pair below skips Karatsuba.
3085    #[cfg(feature = "alloc")]
3086    #[test]
3087    fn fast_mul_falls_through_to_schoolbook_below_threshold() {
3088        let a: [u128; 8] = core::array::from_fn(|i| (i as u128).wrapping_mul(0x1234) + 1);
3089        let b: [u128; 8] = core::array::from_fn(|i| (i as u128).wrapping_mul(0x5678) + 3);
3090        let mut fast = [0u128; 16];
3091        let mut school = [0u128; 16];
3092        limbs_mul_fast(&a, &b, &mut fast);
3093        limbs_mul(&a, &b, &mut school);
3094        assert_eq!(fast, school);
3095    }
3096
3097    /// Karatsuba called directly below the threshold should still
3098    /// produce the correct product via its internal schoolbook
3099    /// fall-through. This exercises the safety branch in
3100    /// `limbs_mul_karatsuba` that zeros out and delegates back to
3101    /// schoolbook when `n < KARATSUBA_MIN`.
3102    #[cfg(feature = "alloc")]
3103    #[test]
3104    fn karatsuba_safety_fallback_below_threshold() {
3105        let a: [u128; 4] = [123, 456, 789, 0];
3106        let b: [u128; 4] = [987, 654, 321, 0];
3107        let mut karatsuba_out = [0u128; 8];
3108        let mut school_out = [0u128; 8];
3109        limbs_mul_karatsuba(&a, &b, &mut karatsuba_out);
3110        limbs_mul(&a, &b, &mut school_out);
3111        assert_eq!(karatsuba_out, school_out);
3112    }
3113
3114    /// `limbs_isqrt` of `1` returns `1` via the `bits <= 1` short-
3115    /// circuit.
3116    #[test]
3117    fn isqrt_one_short_circuit() {
3118        let n = [1u128, 0];
3119        let mut out = [0u128; 2];
3120        limbs_isqrt(&n, &mut out);
3121        assert_eq!(out, [1, 0]);
3122    }
3123
3124    /// `limbs_isqrt` of `0` returns `0` via the `bits == 0` short-
3125    /// circuit.
3126    #[test]
3127    fn isqrt_zero_short_circuit() {
3128        let n = [0u128, 0];
3129        let mut out = [0u128; 2];
3130        limbs_isqrt(&n, &mut out);
3131        assert_eq!(out, [0, 0]);
3132    }
3133
3134    /// `WideInt::from_mag_sign` for `u128` reads the first limb and
3135    /// ignores the sign flag. Exercised through a chained `wide_cast`
3136    /// `Int256 → u128`.
3137    #[test]
3138    fn wide_cast_into_u128_returns_first_limb() {
3139        let src = Int256::from_i128(123_456_789);
3140        let dst: u128 = wide_cast(src);
3141        assert_eq!(dst, 123_456_789);
3142        // Casting ZERO yields 0.
3143        let dst: u128 = wide_cast(Int256::ZERO);
3144        assert_eq!(dst, 0);
3145    }
3146
3147    /// Knuth's q̂-cap path fires when `u_top >= v_top` in the
3148    /// per-quotient-limb loop. We engineer a dividend whose normalised
3149    /// top limb equals the normalised divisor top so the cap (`q̂ =
3150    /// u128::MAX`, plus the subsequent multiply-subtract correction)
3151    /// runs, then verify the resulting quotient matches the canonical
3152    /// `limbs_divmod`.
3153    #[test]
3154    fn knuth_q_hat_cap_branch_matches_canonical() {
3155        // num top limb == den top limb; div quotient's first chunk hits
3156        // the cap. Picking the divisor's top close to u128::MAX
3157        // tightens the normalisation shift.
3158        let num: [u128; 4] = [0, 0, u128::MAX, u128::MAX >> 1];
3159        let den: [u128; 3] = [1, 2, u128::MAX >> 1];
3160        let mut q_canon = [0u128; 4];
3161        let mut r_canon = [0u128; 4];
3162        limbs_divmod(&num, &den, &mut q_canon, &mut r_canon);
3163        let mut q_knuth = [0u128; 4];
3164        let mut r_knuth = [0u128; 4];
3165        limbs_divmod_knuth(&num, &den, &mut q_knuth, &mut r_knuth);
3166        assert_eq!(q_canon, q_knuth);
3167        assert_eq!(r_canon, r_knuth);
3168    }
3169
3170    /// `limbs_divmod_bz` with a numerator that has trailing zero limbs
3171    /// strips them off in its top-non-zero scan before deciding whether
3172    /// to recurse.
3173    #[test]
3174    fn bz_strips_numerator_trailing_zeros() {
3175        // 16-limb buffer but only the low half is non-zero; den is 10 limbs.
3176        // BZ should recognise top < 2*n and fall back to Knuth.
3177        let mut num = [0u128; 16];
3178        for slot in &mut num[..8] {
3179            *slot = 0xCAFE_F00D;
3180        }
3181        let mut den = [0u128; 10];
3182        den[0] = 7;
3183        let mut q_canon = [0u128; 16];
3184        let mut r_canon = [0u128; 16];
3185        limbs_divmod(&num, &den, &mut q_canon, &mut r_canon);
3186        let mut q_bz = [0u128; 16];
3187        let mut r_bz = [0u128; 16];
3188        limbs_divmod_bz(&num, &den, &mut q_bz, &mut r_bz);
3189        assert_eq!(q_canon, q_bz);
3190        assert_eq!(r_canon, r_bz);
3191    }
3192}