Skip to main content

logicaffeine_base/
numeric.rs

1//! The numeric tower's foundation: a hand-rolled arbitrary-precision integer.
2//!
3//! Logos carries the *type* of a number across every boundary (interpreter, VM,
4//! wire), so an integer never silently becomes an IEEE-754 double the way a JSON
5//! number does — there is no 2^53 cliff here. [`BigInt`] is the exact, unbounded
6//! integer all of that rests on; [`Rational`]/[`Decimal`]/[`Complex`] build on it.
7//!
8//! Representation is sign + little-endian base-2^64 magnitude (limbs, no
9//! trailing zeros; zero is the empty magnitude). A single-limb magnitude is
10//! stored inline — no heap allocation for anything that fits 64 bits, and the
11//! add/mul/div_rem fast paths compute those cases in machine registers.
12//! Arithmetic here is *correct first* — schoolbook add/sub/mul and
13//! bit-at-a-time long division — which is the exact-determinism floor;
14//! Karatsuba multiplication and Knuth-D division are the FAST follow-up that
15//! must reproduce these results bit-for-bit.
16
17use std::cmp::Ordering;
18use std::fmt;
19
20/// The sign of a [`BigInt`]. Zero has its own sign so the magnitude invariant
21/// (no trailing zero limbs; the zero magnitude is empty) stays canonical.
22#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
23enum Sign {
24    Neg,
25    Zero,
26    Pos,
27}
28
29/// An exact, arbitrary-precision integer.
30#[derive(Clone, PartialEq, Eq, Hash)]
31pub struct BigInt {
32    sign: Sign,
33    mag: Mag,
34}
35
36/// The magnitude of a [`BigInt`]: a single inline limb (the overwhelmingly
37/// common case — no heap allocation) or heap limbs for multi-limb values.
38///
39/// INVARIANT: `Heap` holds ≥ 2 normalized limbs (no trailing zeros); every
40/// 0- or 1-limb magnitude is `Inline` (zero is `Inline(0)`). The variant is
41/// therefore canonical per value, so the derived `PartialEq`/`Hash` agree
42/// with numeric equality.
43#[derive(Clone, PartialEq, Eq, Hash)]
44enum Mag {
45    Inline(u64),
46    Heap(Vec<u64>),
47}
48
49impl Mag {
50    /// Canonicalize a limb vector (trim trailing zeros, inline when it fits).
51    fn from_vec(mut v: Vec<u64>) -> Mag {
52        while v.last() == Some(&0) {
53            v.pop();
54        }
55        match v.len() {
56            0 => Mag::Inline(0),
57            1 => Mag::Inline(v[0]),
58            _ => Mag::Heap(v),
59        }
60    }
61
62    /// The normalized little-endian limbs (empty ⇔ zero).
63    fn limbs(&self) -> &[u64] {
64        match self {
65            Mag::Inline(0) => &[],
66            Mag::Inline(x) => std::slice::from_ref(x),
67            Mag::Heap(v) => v,
68        }
69    }
70
71    /// The single limb when the magnitude fits one (`Some(0)` for zero),
72    /// `None` for multi-limb values.
73    fn as_single(&self) -> Option<u64> {
74        match self {
75            Mag::Inline(x) => Some(*x),
76            Mag::Heap(_) => None,
77        }
78    }
79}
80
81// ---- magnitude primitives (operate on normalized little-endian `&[u64]`) ----
82
83/// Drop trailing zero limbs so a magnitude has a unique representation.
84fn normalize(mut mag: Vec<u64>) -> Vec<u64> {
85    while mag.last() == Some(&0) {
86        mag.pop();
87    }
88    mag
89}
90
91/// Compare two normalized magnitudes.
92fn mag_cmp(a: &[u64], b: &[u64]) -> Ordering {
93    match a.len().cmp(&b.len()) {
94        Ordering::Equal => {
95            for i in (0..a.len()).rev() {
96                match a[i].cmp(&b[i]) {
97                    Ordering::Equal => {}
98                    other => return other,
99                }
100            }
101            Ordering::Equal
102        }
103        other => other,
104    }
105}
106
107/// `a + b` on magnitudes (full carry).
108fn mag_add(a: &[u64], b: &[u64]) -> Vec<u64> {
109    let mut out = Vec::with_capacity(a.len().max(b.len()) + 1);
110    let mut carry = 0u128;
111    for i in 0..a.len().max(b.len()) {
112        let av = *a.get(i).unwrap_or(&0) as u128;
113        let bv = *b.get(i).unwrap_or(&0) as u128;
114        let sum = av + bv + carry;
115        out.push(sum as u64);
116        carry = sum >> 64;
117    }
118    if carry != 0 {
119        out.push(carry as u64);
120    }
121    normalize(out)
122}
123
124/// `a - b` on magnitudes; requires `a >= b` (full borrow).
125fn mag_sub(a: &[u64], b: &[u64]) -> Vec<u64> {
126    debug_assert!(mag_cmp(a, b) != Ordering::Less, "mag_sub underflow");
127    let mut out = Vec::with_capacity(a.len());
128    let mut borrow = 0i128;
129    for i in 0..a.len() {
130        let av = a[i] as i128;
131        let bv = *b.get(i).unwrap_or(&0) as i128;
132        let mut diff = av - bv - borrow;
133        if diff < 0 {
134            diff += 1i128 << 64;
135            borrow = 1;
136        } else {
137            borrow = 0;
138        }
139        out.push(diff as u64);
140    }
141    debug_assert_eq!(borrow, 0, "mag_sub left a borrow");
142    normalize(out)
143}
144
145/// The magnitude length (in 64-bit limbs) at/above which Karatsuba beats schoolbook:
146/// its three half-size products plus the add/sub glue only pay off once the smaller
147/// operand is large enough. Below it, schoolbook's tight inner loop wins.
148const KARATSUBA_THRESHOLD: usize = 32;
149
150/// `a * b` on magnitudes: schoolbook for small operands, Karatsuba for large.
151fn mag_mul(a: &[u64], b: &[u64]) -> Vec<u64> {
152    if a.is_empty() || b.is_empty() {
153        return Vec::new();
154    }
155    if a.len().min(b.len()) < KARATSUBA_THRESHOLD {
156        return mag_mul_schoolbook(a, b);
157    }
158    mag_mul_karatsuba(a, b)
159}
160
161/// Schoolbook `a * b` — O(n·m). The exact correctness oracle Karatsuba is fuzzed against.
162fn mag_mul_schoolbook(a: &[u64], b: &[u64]) -> Vec<u64> {
163    let mut out = vec![0u64; a.len() + b.len()];
164    for (i, &av) in a.iter().enumerate() {
165        let mut carry = 0u128;
166        for (j, &bv) in b.iter().enumerate() {
167            let cur = out[i + j] as u128 + (av as u128) * (bv as u128) + carry;
168            out[i + j] = cur as u64;
169            carry = cur >> 64;
170        }
171        out[i + b.len()] += carry as u64;
172    }
173    normalize(out)
174}
175
176/// Prepend `n` zero limbs — multiply by `2^(64·n)`, i.e. shift the magnitude up by `n` limbs.
177fn mag_shl_limbs(a: &[u64], n: usize) -> Vec<u64> {
178    if a.is_empty() {
179        return Vec::new();
180    }
181    let mut out = Vec::with_capacity(a.len() + n);
182    out.resize(n, 0);
183    out.extend_from_slice(a);
184    out
185}
186
187/// Karatsuba `a * b`: split each operand at `m` limbs (`x = x_hi·B^m + x_lo`, `B = 2^64`)
188/// and combine three half-size products —
189///   `z0 = a_lo·b_lo`, `z2 = a_hi·b_hi`, `z1 = (a_lo+a_hi)·(b_lo+b_hi) − z0 − z2` —
190/// into `a·b = z2·B^{2m} + z1·B^m + z0`. `z1` is the (non-negative) sum of the cross
191/// products, so the subtractions never underflow. Recurses through `mag_mul`, so every
192/// sub-product below `KARATSUBA_THRESHOLD` falls back to schoolbook.
193fn mag_mul_karatsuba(a: &[u64], b: &[u64]) -> Vec<u64> {
194    let m = a.len().min(b.len()) / 2; // ≥ KARATSUBA_THRESHOLD/2 ≥ 1, and ≤ both lengths
195    let (a_lo, a_hi) = a.split_at(m);
196    let (b_lo, b_hi) = b.split_at(m);
197
198    let z0 = mag_mul(a_lo, b_lo);
199    let z2 = mag_mul(a_hi, b_hi);
200    let a_sum = mag_add(a_lo, a_hi);
201    let b_sum = mag_add(b_lo, b_hi);
202    let z1 = mag_sub(&mag_sub(&mag_mul(&a_sum, &b_sum), &z0), &z2);
203
204    let mut out = z0;
205    out = mag_add(&out, &mag_shl_limbs(&z1, m));
206    out = mag_add(&out, &mag_shl_limbs(&z2, 2 * m));
207    normalize(out)
208}
209
210/// `r << 1 | bit` on a magnitude (shift the whole number up by one bit).
211#[cfg(test)]
212fn mag_shl1(a: &[u64], bit: u64) -> Vec<u64> {
213    let mut out = Vec::with_capacity(a.len() + 1);
214    let mut carry = bit & 1;
215    for &limb in a {
216        out.push((limb << 1) | carry);
217        carry = limb >> 63;
218    }
219    if carry != 0 {
220        out.push(carry);
221    }
222    normalize(out)
223}
224
225/// Bit-at-a-time long division — the exact oracle Algorithm D is fuzzed against.
226#[cfg(test)]
227fn mag_divrem_bitwise(a: &[u64], b: &[u64]) -> (Vec<u64>, Vec<u64>) {
228    if mag_cmp(a, b) == Ordering::Less {
229        return (Vec::new(), a.to_vec());
230    }
231    let nbits = a.len() * 64;
232    let mut q = vec![0u64; a.len()];
233    let mut r: Vec<u64> = Vec::new();
234    for i in (0..nbits).rev() {
235        let bit = (a[i / 64] >> (i % 64)) & 1;
236        r = mag_shl1(&r, bit);
237        if mag_cmp(&r, b) != Ordering::Less {
238            r = mag_sub(&r, b);
239            q[i / 64] |= 1u64 << (i % 64);
240        }
241    }
242    (normalize(q), normalize(r))
243}
244
245/// `a << bits` on a magnitude.
246fn mag_shl_bits(a: &[u64], bits: u64) -> Vec<u64> {
247    if a.is_empty() {
248        return Vec::new();
249    }
250    let (words, sh) = ((bits / 64) as usize, (bits % 64) as u32);
251    let mut out = Vec::with_capacity(a.len() + words + 1);
252    out.resize(words, 0);
253    if sh == 0 {
254        out.extend_from_slice(a);
255    } else {
256        let mut carry = 0u64;
257        for &limb in a {
258            out.push((limb << sh) | carry);
259            carry = limb >> (64 - sh);
260        }
261        if carry != 0 {
262            out.push(carry);
263        }
264    }
265    out
266}
267
268/// `x · 2^k` for a finite `x`: exact while the result is finite, infinite once it is not. Multiplying
269/// by a power of two changes only the exponent, so there is nothing to round until the exponent
270/// overflows; the scale is applied in steps of 2^1000 because a single `f64` holds at most 2^1023.
271fn scale_by_power_of_two(mut x: f64, mut k: u64) -> f64 {
272    const STEP: u64 = 1000;
273    let power = |e: u64| f64::from_bits((1023 + e) << 52);
274    while k > STEP && x.is_finite() {
275        x *= power(STEP);
276        k -= STEP;
277    }
278    if x.is_finite() {
279        x * power(k)
280    } else {
281        x
282    }
283}
284
285/// `a >> bits` on a magnitude (floor).
286fn mag_shr_bits(a: &[u64], bits: u64) -> Vec<u64> {
287    let words = bits / 64;
288    if words >= a.len() as u64 {
289        return Vec::new();
290    }
291    let a = &a[words as usize..];
292    let sh = (bits % 64) as u32;
293    if sh == 0 {
294        return a.to_vec();
295    }
296    let mut out = Vec::with_capacity(a.len());
297    for i in 0..a.len() {
298        let hi = a.get(i + 1).map_or(0, |h| h << (64 - sh));
299        out.push((a[i] >> sh) | hi);
300    }
301    normalize(out)
302}
303
304/// Long division on magnitudes: returns `(quotient, remainder)` with `a = q*b + r` and
305/// `0 <= r < b`, by Knuth's Algorithm D (TAOCP vol. 2, §4.3.1): normalise so the divisor's top
306/// limb has its high bit set, estimate each quotient limb from the top two limbs of the running
307/// remainder, correct the estimate at most twice, and add back on the rare overshoot.
308fn mag_divrem(a: &[u64], b: &[u64]) -> (Vec<u64>, Vec<u64>) {
309    debug_assert!(!b.is_empty(), "division by zero magnitude");
310    if mag_cmp(a, b) == Ordering::Less {
311        return (Vec::new(), a.to_vec());
312    }
313    if b.len() == 1 {
314        let d = b[0] as u128;
315        let mut q = vec![0u64; a.len()];
316        let mut rem: u128 = 0;
317        for i in (0..a.len()).rev() {
318            let cur = (rem << 64) | a[i] as u128;
319            q[i] = (cur / d) as u64;
320            rem = cur % d;
321        }
322        return (normalize(q), normalize(vec![rem as u64]));
323    }
324    let shift = b[b.len() - 1].leading_zeros() as u64;
325    let v = mag_shl_bits(b, shift);
326    let mut u = mag_shl_bits(a, shift);
327    u.resize(a.len() + 1, 0);
328    let n = v.len();
329    let m = u.len() - n - 1;
330    let mut q = vec![0u64; m + 1];
331    let (vtop, vnext) = (v[n - 1] as u128, v[n - 2] as u128);
332    const B: u128 = 1 << 64;
333    for j in (0..=m).rev() {
334        let num = ((u[j + n] as u128) << 64) | u[j + n - 1] as u128;
335        let mut qhat = num / vtop;
336        let mut rhat = num % vtop;
337        while qhat >= B || qhat * vnext > ((rhat << 64) | u[j + n - 2] as u128) {
338            qhat -= 1;
339            rhat += vtop;
340            if rhat >= B {
341                break;
342            }
343        }
344        let mut borrow: i128 = 0;
345        let mut carry: u128 = 0;
346        for i in 0..n {
347            let p = qhat * v[i] as u128 + carry;
348            carry = p >> 64;
349            let t = u[i + j] as i128 - (p as u64) as i128 + borrow;
350            u[i + j] = t as u64;
351            borrow = t >> 64;
352        }
353        let t = u[j + n] as i128 - carry as i128 + borrow;
354        u[j + n] = t as u64;
355        if t < 0 {
356            qhat -= 1;
357            let mut c: u128 = 0;
358            for i in 0..n {
359                let s = u[i + j] as u128 + v[i] as u128 + c;
360                u[i + j] = s as u64;
361                c = s >> 64;
362            }
363            u[j + n] = u[j + n].wrapping_add(c as u64);
364        }
365        q[j] = qhat as u64;
366    }
367    u.truncate(n);
368    (normalize(q), mag_shr_bits(&normalize(u), shift))
369}
370
371impl BigInt {
372    /// The additive identity.
373    pub fn zero() -> Self {
374        BigInt {
375            sign: Sign::Zero,
376            mag: Mag::Inline(0),
377        }
378    }
379
380    /// Build from a sign flag and a (not-necessarily-normalized) magnitude,
381    /// re-establishing the canonical form (trim zeros; empty magnitude ⇒ Zero).
382    fn from_sign_mag(neg: bool, mag: Vec<u64>) -> Self {
383        let mag = Mag::from_vec(mag);
384        let sign = if mag.limbs().is_empty() {
385            Sign::Zero
386        } else if neg {
387            Sign::Neg
388        } else {
389            Sign::Pos
390        };
391        BigInt { sign, mag }
392    }
393
394    /// Build from a sign flag and a ≤128-bit magnitude — the allocation-free
395    /// constructor the single-limb fast paths return through.
396    fn from_sign_mag_u128(neg: bool, m: u128) -> Self {
397        if m == 0 {
398            return Self::zero();
399        }
400        let lo = m as u64;
401        let hi = (m >> 64) as u64;
402        let mag = if hi == 0 {
403            Mag::Inline(lo)
404        } else {
405            Mag::Heap(vec![lo, hi])
406        };
407        BigInt {
408            sign: if neg { Sign::Neg } else { Sign::Pos },
409            mag,
410        }
411    }
412
413    /// Exact widening from a machine integer.
414    pub fn from_i64(x: i64) -> Self {
415        Self::from_sign_mag_u128(x < 0, (x as i128).unsigned_abs())
416    }
417
418    /// Exact widening from an unsigned machine integer.
419    pub fn from_u64(x: u64) -> Self {
420        Self::from_sign_mag_u128(false, x as u128)
421    }
422
423    /// Heap payload bytes duplicated when this integer is cloned.
424    ///
425    /// Inline fields and the vector header belong to the containing value.
426    /// This borrowed query neither copies limbs nor formats the integer.
427    pub fn clone_payload_bytes(&self) -> usize {
428        match &self.mag {
429            Mag::Inline(_) => 0,
430            Mag::Heap(limbs) => limbs.len() * std::mem::size_of::<u64>(),
431        }
432    }
433
434    /// Narrow back to an `i64` iff the value fits — the basis of the "downsize when
435    /// it provably fits" path the runtime uses to stay on the fast i64 repr.
436    pub fn to_i64(&self) -> Option<i64> {
437        let m = self.mag.as_single()? as i128;
438        let v = if self.sign == Sign::Neg { -m } else { m };
439        if (i64::MIN as i128..=i64::MAX as i128).contains(&v) {
440            Some(v as i64)
441        } else {
442            None
443        }
444    }
445
446    /// The value as a `u64` when it is non-negative and fits.
447    pub fn to_u64(&self) -> Option<u64> {
448        match self.sign {
449            Sign::Neg => None,
450            _ => self.mag.as_single(),
451        }
452    }
453
454    /// The low 64 bits, defined for every integer.
455    pub fn wrapping_u64(&self) -> u64 {
456        let low = self.mag.limbs().first().copied().unwrap_or(0);
457        if self.sign == Sign::Neg {
458            low.wrapping_neg()
459        } else {
460            low
461        }
462    }
463
464    /// Number of significant bits of the magnitude (`0` for zero).
465    pub fn bit_len(&self) -> u64 {
466        let l = self.mag.limbs();
467        match l.last() {
468            None => 0,
469            Some(top) => (l.len() as u64 - 1) * 64 + (64 - top.leading_zeros() as u64),
470        }
471    }
472
473    /// `gcd(|self|, |other|)`, with `gcd(a, 0) = |a|`.
474    pub fn gcd(&self, other: &Self) -> Self {
475        if let (Some(a), Some(b)) = (self.mag.as_single(), other.mag.as_single()) {
476            let (mut a, mut b) = (a, b);
477            while b != 0 {
478                let t = a % b;
479                a = b;
480                b = t;
481            }
482            return BigInt::from_u64(a);
483        }
484        bigint_gcd(self, other)
485    }
486
487    /// `self · 2^bits` (exact for either sign).
488    pub fn shl_bits(&self, bits: u64) -> Self {
489        Self::from_sign_mag(self.sign == Sign::Neg, mag_shl_bits(self.mag.limbs(), bits))
490    }
491
492    /// `⌊self / 2^bits⌋` for a non-negative value; `None` for a negative one.
493    pub fn shr_bits(&self, bits: u64) -> Option<Self> {
494        if self.sign == Sign::Neg {
495            return None;
496        }
497        Some(Self::from_sign_mag(
498            false,
499            mag_shr_bits(self.mag.limbs(), bits),
500        ))
501    }
502
503    fn natural_bitwise(&self, other: &Self, op: impl Fn(u64, u64) -> u64) -> Option<Self> {
504        if self.sign == Sign::Neg || other.sign == Sign::Neg {
505            return None;
506        }
507        let (a, b) = (self.mag.limbs(), other.mag.limbs());
508        let out = (0..a.len().max(b.len()))
509            .map(|i| op(*a.get(i).unwrap_or(&0), *b.get(i).unwrap_or(&0)))
510            .collect();
511        Some(Self::from_sign_mag(false, out))
512    }
513
514    /// Bitwise AND of two non-negative values; `None` if either is negative.
515    pub fn bitand_natural(&self, other: &Self) -> Option<Self> {
516        self.natural_bitwise(other, |x, y| x & y)
517    }
518
519    /// Bitwise OR of two non-negative values; `None` if either is negative.
520    pub fn bitor_natural(&self, other: &Self) -> Option<Self> {
521        self.natural_bitwise(other, |x, y| x | y)
522    }
523
524    /// Bitwise XOR of two non-negative values; `None` if either is negative.
525    pub fn bitxor_natural(&self, other: &Self) -> Option<Self> {
526        self.natural_bitwise(other, |x, y| x ^ y)
527    }
528
529    pub fn is_zero(&self) -> bool {
530        self.sign == Sign::Zero
531    }
532
533    /// Parity (the low bit of the magnitude — sign does not change it). Zero is even.
534    pub fn is_odd(&self) -> bool {
535        self.mag.limbs().first().is_some_and(|limb| limb & 1 == 1)
536    }
537
538    /// The binary64 nearest to this integer, ties to even, ±∞ once the rounding reaches 2^1024: the
539    /// one conversion every tier uses for an Int flowing into a Real (a widened argument, `n + 0.5`).
540    ///
541    /// One rounding, never one per limb: the top 64 significant bits are taken exactly, every bit
542    /// below them is folded into bit 0 as a sticky bit (eleven places under the 53-bit rounding
543    /// position, so it can break a tie but never create one), and that `u64` is converted with the
544    /// hardware's round-to-nearest-even. Scaling back by a power of two is exact until it overflows,
545    /// which is exactly where the exact value rounds to infinity too.
546    pub fn to_f64(&self) -> f64 {
547        let limbs = self.mag.limbs();
548        let bits = self.bit_len();
549        let magnitude = if bits <= 64 {
550            limbs.first().copied().unwrap_or(0) as f64
551        } else {
552            let dropped = bits - 64;
553            let (word, shift) = ((dropped / 64) as usize, (dropped % 64) as u32);
554            let top = if shift == 0 {
555                limbs[word]
556            } else {
557                (limbs[word] >> shift) | (limbs[word + 1] << (64 - shift))
558            };
559            let sticky = limbs[..word].iter().any(|&l| l != 0)
560                || (shift != 0 && limbs[word] << (64 - shift) != 0);
561            scale_by_power_of_two((top | sticky as u64) as f64, dropped)
562        };
563        if self.sign == Sign::Neg {
564            -magnitude
565        } else {
566            magnitude
567        }
568    }
569
570    pub fn is_negative(&self) -> bool {
571        self.sign == Sign::Neg
572    }
573
574    pub fn is_positive(&self) -> bool {
575        self.sign == Sign::Pos
576    }
577
578    /// The absolute value.
579    pub fn abs(&self) -> Self {
580        BigInt {
581            sign: if self.sign == Sign::Zero {
582                Sign::Zero
583            } else {
584                Sign::Pos
585            },
586            mag: self.mag.clone(),
587        }
588    }
589
590    /// Additive inverse.
591    pub fn negated(&self) -> Self {
592        let sign = match self.sign {
593            Sign::Neg => Sign::Pos,
594            Sign::Zero => Sign::Zero,
595            Sign::Pos => Sign::Neg,
596        };
597        BigInt {
598            sign,
599            mag: self.mag.clone(),
600        }
601    }
602
603    /// `self + other`.
604    pub fn add(&self, other: &Self) -> Self {
605        // Single-limb fast path: both magnitudes fit a limb, so the signed sum
606        // fits an i128 — no limb vectors, no allocation.
607        if let (Some(a), Some(b)) = (self.mag.as_single(), other.mag.as_single()) {
608            let av = if self.sign == Sign::Neg {
609                -(a as i128)
610            } else {
611                a as i128
612            };
613            let bv = if other.sign == Sign::Neg {
614                -(b as i128)
615            } else {
616                b as i128
617            };
618            let sum = av + bv;
619            return Self::from_sign_mag_u128(sum < 0, sum.unsigned_abs());
620        }
621        match (self.sign, other.sign) {
622            (Sign::Zero, _) => other.clone(),
623            (_, Sign::Zero) => self.clone(),
624            // Same sign: add magnitudes, keep the sign.
625            (a, b) if a == b => {
626                Self::from_sign_mag(a == Sign::Neg, mag_add(self.mag.limbs(), other.mag.limbs()))
627            }
628            // Opposite signs: subtract the smaller magnitude from the larger; the
629            // result takes the sign of the larger.
630            _ => match mag_cmp(self.mag.limbs(), other.mag.limbs()) {
631                Ordering::Equal => Self::zero(),
632                Ordering::Greater => Self::from_sign_mag(
633                    self.sign == Sign::Neg,
634                    mag_sub(self.mag.limbs(), other.mag.limbs()),
635                ),
636                Ordering::Less => Self::from_sign_mag(
637                    other.sign == Sign::Neg,
638                    mag_sub(other.mag.limbs(), self.mag.limbs()),
639                ),
640            },
641        }
642    }
643
644    /// `self - other`.
645    pub fn sub(&self, other: &Self) -> Self {
646        self.add(&other.negated())
647    }
648
649    /// `self * other`.
650    pub fn mul(&self, other: &Self) -> Self {
651        let neg = (self.sign == Sign::Neg) ^ (other.sign == Sign::Neg);
652        // Single-limb fast path: the product fits a u128.
653        if let (Some(a), Some(b)) = (self.mag.as_single(), other.mag.as_single()) {
654            return Self::from_sign_mag_u128(neg, (a as u128) * (b as u128));
655        }
656        if self.is_zero() || other.is_zero() {
657            return Self::zero();
658        }
659        Self::from_sign_mag(neg, mag_mul(self.mag.limbs(), other.mag.limbs()))
660    }
661
662    /// In-place multiply by a machine-integer scalar, REUSING the heap magnitude buffer
663    /// (it grows by at most one limb, never reallocates from scratch). The exact-value
664    /// counterpart of `self.mul(&BigInt::from_i64(rhs))` — same result, but the growing
665    /// accumulator's `Vec` is mutated rather than reallocated each call, which is the hot
666    /// loop `Set p to p * i` (factorial). Canonical form is preserved: multiplying a
667    /// normalized magnitude by a nonzero scalar never introduces a trailing zero limb (a
668    /// zeroed low half always carries out), and a `Heap` value stays ≥ 2 limbs.
669    pub fn mul_assign_i64(&mut self, rhs: i64) {
670        if rhs == 0 || self.is_zero() {
671            *self = Self::zero();
672            return;
673        }
674        if rhs < 0 {
675            self.sign = match self.sign {
676                Sign::Neg => Sign::Pos,
677                Sign::Pos => Sign::Neg,
678                Sign::Zero => Sign::Zero,
679            };
680        }
681        let m = (rhs as i128).unsigned_abs() as u64;
682        match &mut self.mag {
683            Mag::Inline(x) => {
684                let prod = (*x as u128) * (m as u128);
685                self.mag = if (prod >> 64) == 0 {
686                    Mag::Inline(prod as u64)
687                } else {
688                    Mag::Heap(vec![prod as u64, (prod >> 64) as u64])
689                };
690            }
691            Mag::Heap(v) => {
692                let mut carry: u64 = 0;
693                for limb in v.iter_mut() {
694                    let prod = (*limb as u128) * (m as u128) + (carry as u128);
695                    *limb = prod as u64;
696                    carry = (prod >> 64) as u64;
697                }
698                if carry != 0 {
699                    v.push(carry);
700                }
701            }
702        }
703    }
704
705    /// Truncated division toward zero: returns `(quotient, remainder)` with
706    /// `self = q*other + r` and the remainder carrying the dividend's sign — exactly
707    /// matching Rust/`i64` `/` and `%`, so the wide type is a drop-in for the narrow.
708    /// `None` when `other` is zero.
709    pub fn div_rem(&self, other: &Self) -> Option<(Self, Self)> {
710        if other.is_zero() {
711            return None;
712        }
713        let q_neg = (self.sign == Sign::Neg) ^ (other.sign == Sign::Neg);
714        // Single-limb fast path: machine division gives the truncated pair
715        // directly (the remainder takes the dividend's sign).
716        if let (Some(a), Some(b)) = (self.mag.as_single(), other.mag.as_single()) {
717            return Some((
718                Self::from_sign_mag_u128(q_neg, (a / b) as u128),
719                Self::from_sign_mag_u128(self.sign == Sign::Neg, (a % b) as u128),
720            ));
721        }
722        if self.is_zero() {
723            return Some((Self::zero(), Self::zero()));
724        }
725        let (qm, rm) = mag_divrem(self.mag.limbs(), other.mag.limbs());
726        let q = Self::from_sign_mag(q_neg, qm);
727        // The remainder takes the dividend's sign (truncated division).
728        let r = Self::from_sign_mag(self.sign == Sign::Neg, rm);
729        Some((q, r))
730    }
731
732    /// Parse a base-10 integer (optional leading `+`/`-`). `None` on any non-digit.
733    pub fn parse_decimal(s: &str) -> Option<Self> {
734        let bytes = s.as_bytes();
735        let (neg, digits) = match bytes.first() {
736            Some(b'-') => (true, &bytes[1..]),
737            Some(b'+') => (false, &bytes[1..]),
738            _ => (false, bytes),
739        };
740        if digits.is_empty() {
741            return None;
742        }
743        let ten = BigInt::from_u64(10);
744        let mut acc = BigInt::zero();
745        for &d in digits {
746            if !d.is_ascii_digit() {
747                return None;
748            }
749            acc = acc.mul(&ten).add(&BigInt::from_u64((d - b'0') as u64));
750        }
751        Some(if neg { acc.negated() } else { acc })
752    }
753
754    /// `self` raised to a non-negative integer power, by exponentiation-by-squaring
755    /// (`0^0 == 1`). Exact and unbounded — `2.pow(63)` is the value `i64` cannot hold.
756    pub fn pow(&self, mut exp: u32) -> BigInt {
757        let mut result = BigInt::from_u64(1);
758        let mut base = self.clone();
759        while exp > 0 {
760            if exp & 1 == 1 {
761                result = result.mul(&base);
762            }
763            exp >>= 1;
764            if exp > 0 {
765                base = base.mul(&base);
766            }
767        }
768        result
769    }
770
771    /// Sign + little-endian magnitude bytes — a compact, exact serialization (the
772    /// inverse of [`BigInt::from_le_bytes`]). The wire ships these instead of a
773    /// decimal string, so there is no base conversion and no precision question.
774    pub fn to_le_bytes(&self) -> (bool, Vec<u8>) {
775        let limbs = self.mag.limbs();
776        let mut bytes = Vec::with_capacity(limbs.len() * 8);
777        for &limb in limbs {
778            bytes.extend_from_slice(&limb.to_le_bytes());
779        }
780        (self.sign == Sign::Neg, bytes)
781    }
782
783    /// Reconstruct from a sign flag and little-endian magnitude bytes (length need
784    /// not be a multiple of 8; trailing zero limbs are normalized away).
785    pub fn from_le_bytes(negative: bool, bytes: &[u8]) -> Self {
786        let mut mag = Vec::with_capacity(bytes.len().div_ceil(8));
787        for chunk in bytes.chunks(8) {
788            let mut limb = [0u8; 8];
789            limb[..chunk.len()].copy_from_slice(chunk);
790            mag.push(u64::from_le_bytes(limb));
791        }
792        Self::from_sign_mag(negative, mag)
793    }
794}
795
796impl Ord for BigInt {
797    fn cmp(&self, other: &Self) -> Ordering {
798        // Order by sign first, then by magnitude (reversed when both negative).
799        let rank = |s: Sign| match s {
800            Sign::Neg => -1i8,
801            Sign::Zero => 0,
802            Sign::Pos => 1,
803        };
804        match rank(self.sign).cmp(&rank(other.sign)) {
805            Ordering::Equal => match self.sign {
806                Sign::Zero => Ordering::Equal,
807                Sign::Pos => mag_cmp(self.mag.limbs(), other.mag.limbs()),
808                Sign::Neg => mag_cmp(other.mag.limbs(), self.mag.limbs()),
809            },
810            other => other,
811        }
812    }
813}
814
815impl PartialOrd for BigInt {
816    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
817        Some(self.cmp(other))
818    }
819}
820
821impl fmt::Display for BigInt {
822    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
823        if self.is_zero() {
824            return write!(f, "0");
825        }
826        // Emit base-10 by repeatedly dividing by 10^19 (the largest power of ten that
827        // fits in a u64), collecting 19-digit chunks least-significant first.
828        const TEN19: u64 = 10_000_000_000_000_000_000;
829        let ten19 = BigInt::from_u64(TEN19);
830        let mut chunks: Vec<u64> = Vec::new();
831        let mut cur = self.abs();
832        while !cur.is_zero() {
833            let (q, r) = cur.div_rem(&ten19).expect("10^19 is nonzero");
834            // r < 10^19 < 2^64, so it is one limb at most — and may exceed i64::MAX,
835            // hence read the limb directly rather than via `to_i64`.
836            chunks.push(r.mag.limbs().first().copied().unwrap_or(0));
837            cur = q;
838        }
839        if self.is_negative() {
840            write!(f, "-")?;
841        }
842        // Most-significant chunk has no leading zeros; the rest are zero-padded to 19.
843        write!(f, "{}", chunks.last().unwrap())?;
844        for &chunk in chunks.iter().rev().skip(1) {
845            write!(f, "{chunk:019}")?;
846        }
847        Ok(())
848    }
849}
850
851impl fmt::Debug for BigInt {
852    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
853        write!(f, "BigInt({self})")
854    }
855}
856
857impl From<i64> for BigInt {
858    fn from(x: i64) -> Self {
859        BigInt::from_i64(x)
860    }
861}
862
863// =====================================================================
864// Rational — exact fractions on top of BigInt
865// =====================================================================
866
867/// `gcd(|a|, |b|)` by the Euclidean algorithm (`gcd(a, 0) == |a|`).
868fn bigint_gcd(a: &BigInt, b: &BigInt) -> BigInt {
869    let mut a = a.abs();
870    let mut b = b.abs();
871    while !b.is_zero() {
872        let (_q, r) = a.div_rem(&b).expect("b is nonzero inside the loop");
873        a = b;
874        b = r;
875    }
876    a
877}
878
879/// An exact rational number: a fraction kept in lowest terms with a strictly
880/// positive denominator. Built on [`BigInt`], so it never rounds the way a JSON
881/// / `f64` "number" does — `1/3` stays exactly `1/3`, not `0.3333…`, and a
882/// numerator past 2^53 survives instead of collapsing onto a double.
883///
884/// Representation is correct-first: BigInt numerator and denominator, reduced on
885/// every construction. The i64-fast-path (storing small num/den inline to skip
886/// the BigInt allocation) is the documented performance follow-up — exactly as
887/// Karatsuba is for [`BigInt`] — and must reproduce these values bit-for-bit.
888#[derive(Clone, PartialEq, Eq, Hash)]
889pub struct Rational {
890    /// Carries the sign of the whole value.
891    num: BigInt,
892    /// INVARIANT: `den > 0`, `gcd(|num|, den) == 1`, and `den == 1` whenever
893    /// `num == 0` — so equal values share one representation (Eq/Hash/Ord are
894    /// structural).
895    den: BigInt,
896}
897
898impl Rational {
899    /// The canonicalizing constructor: reduce `num/den` to lowest terms with a
900    /// positive denominator. Returns `None` for a zero denominator (the one
901    /// undefined fraction).
902    pub fn new(num: BigInt, den: BigInt) -> Option<Rational> {
903        if den.is_zero() {
904            return None;
905        }
906        let (mut num, mut den) = (num, den);
907        if den.is_negative() {
908            num = num.negated();
909            den = den.negated();
910        }
911        if num.is_zero() {
912            return Some(Rational {
913                num: BigInt::zero(),
914                den: BigInt::from_i64(1),
915            });
916        }
917        let g = bigint_gcd(&num, &den);
918        let (num, _) = num.div_rem(&g).expect("gcd divides the numerator exactly");
919        let (den, _) = den
920            .div_rem(&g)
921            .expect("gcd divides the denominator exactly");
922        Some(Rational { num, den })
923    }
924
925    /// The integer `n` as the fraction `n/1`.
926    pub fn from_bigint(n: BigInt) -> Rational {
927        Rational {
928            num: n,
929            den: BigInt::from_i64(1),
930        }
931    }
932
933    pub fn from_i64(x: i64) -> Rational {
934        Rational::from_bigint(BigInt::from_i64(x))
935    }
936
937    /// `n/d` from machine integers (convenience; `None` if `d == 0`).
938    pub fn from_ratio_i64(n: i64, d: i64) -> Option<Rational> {
939        Rational::new(BigInt::from_i64(n), BigInt::from_i64(d))
940    }
941
942    pub fn zero() -> Rational {
943        Rational {
944            num: BigInt::zero(),
945            den: BigInt::from_i64(1),
946        }
947    }
948
949    pub fn one() -> Rational {
950        Rational::from_i64(1)
951    }
952
953    pub fn numerator(&self) -> &BigInt {
954        &self.num
955    }
956
957    pub fn denominator(&self) -> &BigInt {
958        &self.den
959    }
960
961    /// True when the value is a whole number (`den == 1`).
962    pub fn is_integer(&self) -> bool {
963        self.den == BigInt::from_i64(1)
964    }
965
966    pub fn is_zero(&self) -> bool {
967        self.num.is_zero()
968    }
969
970    pub fn is_negative(&self) -> bool {
971        self.num.is_negative()
972    }
973
974    pub fn is_positive(&self) -> bool {
975        self.num.is_positive()
976    }
977
978    /// The integer value when this is whole, else `None` (the provable narrow
979    /// back to [`BigInt`]).
980    pub fn to_bigint(&self) -> Option<BigInt> {
981        if self.is_integer() {
982            Some(self.num.clone())
983        } else {
984            None
985        }
986    }
987
988    /// The `i64` value when this is a whole number that fits, else `None`.
989    pub fn to_i64(&self) -> Option<i64> {
990        if self.is_integer() {
991            self.num.to_i64()
992        } else {
993            None
994        }
995    }
996
997    /// Nearest `f64` (for display / interop only — lossy for large terms, exact
998    /// for small ones). The *value* stays exact; this is a view.
999    pub fn to_f64(&self) -> f64 {
1000        self.num.to_f64() / self.den.to_f64()
1001    }
1002
1003    /// The greatest integer `≤ self` (round toward −∞). `floor(7/2) == 3`,
1004    /// `floor(-7/2) == -4`. The companion of explicit floor division.
1005    pub fn floor(&self) -> BigInt {
1006        let (q, r) = self.num.div_rem(&self.den).expect("denominator is nonzero");
1007        if self.num.is_negative() && !r.is_zero() {
1008            q.sub(&BigInt::from_i64(1))
1009        } else {
1010            q
1011        }
1012    }
1013
1014    /// The least integer `≥ self` (round toward +∞). `ceil(7/2) == 4`,
1015    /// `ceil(-7/2) == -3`.
1016    pub fn ceil(&self) -> BigInt {
1017        let (q, r) = self.num.div_rem(&self.den).expect("denominator is nonzero");
1018        if !self.num.is_negative() && !r.is_zero() {
1019            q.add(&BigInt::from_i64(1))
1020        } else {
1021            q
1022        }
1023    }
1024
1025    /// The nearest integer, ties rounded AWAY from zero (matching `f64::round`):
1026    /// `round(x) = sign(x) · ⌊|x| + 1/2⌋ = sign(x) · ((2|num| + den) ÷ 2den)`.
1027    pub fn round(&self) -> BigInt {
1028        let two = BigInt::from_i64(2);
1029        let numerator = self.num.abs().mul(&two).add(&self.den);
1030        let denominator = self.den.mul(&two);
1031        let (mag, _) = numerator
1032            .div_rem(&denominator)
1033            .expect("denominator is nonzero");
1034        if self.num.is_negative() {
1035            mag.negated()
1036        } else {
1037            mag
1038        }
1039    }
1040
1041    pub fn negated(&self) -> Rational {
1042        Rational {
1043            num: self.num.negated(),
1044            den: self.den.clone(),
1045        }
1046    }
1047
1048    pub fn abs(&self) -> Rational {
1049        Rational {
1050            num: self.num.abs(),
1051            den: self.den.clone(),
1052        }
1053    }
1054
1055    /// `1/self` — `None` when `self == 0`.
1056    pub fn recip(&self) -> Option<Rational> {
1057        Rational::new(self.den.clone(), self.num.clone())
1058    }
1059
1060    pub fn add(&self, other: &Rational) -> Rational {
1061        // a/b + c/d = (a·d + c·b)/(b·d); b,d > 0 ⇒ b·d > 0 ⇒ `new` succeeds.
1062        let num = self.num.mul(&other.den).add(&other.num.mul(&self.den));
1063        let den = self.den.mul(&other.den);
1064        Rational::new(num, den).expect("product of positive denominators is nonzero")
1065    }
1066
1067    pub fn sub(&self, other: &Rational) -> Rational {
1068        let num = self.num.mul(&other.den).sub(&other.num.mul(&self.den));
1069        let den = self.den.mul(&other.den);
1070        Rational::new(num, den).expect("product of positive denominators is nonzero")
1071    }
1072
1073    pub fn mul(&self, other: &Rational) -> Rational {
1074        let num = self.num.mul(&other.num);
1075        let den = self.den.mul(&other.den);
1076        Rational::new(num, den).expect("product of positive denominators is nonzero")
1077    }
1078
1079    /// `self / other` — `None` when `other == 0`.
1080    pub fn div(&self, other: &Rational) -> Option<Rational> {
1081        // (a/b)/(c/d) = (a·d)/(b·c); `new` rejects a zero denominator (c == 0).
1082        let num = self.num.mul(&other.den);
1083        let den = self.den.mul(&other.num);
1084        Rational::new(num, den)
1085    }
1086
1087    /// `self^exp`, exact for every integer exponent. Negative exponents take the
1088    /// reciprocal first; `None` only for `0` raised to a negative power.
1089    pub fn pow(&self, exp: i32) -> Option<Rational> {
1090        if exp >= 0 {
1091            let k = exp as u32;
1092            Some(
1093                Rational::new(self.num.pow(k), self.den.pow(k))
1094                    .expect("denominator^k stays positive"),
1095            )
1096        } else {
1097            if self.num.is_zero() {
1098                return None;
1099            }
1100            let k = exp.unsigned_abs();
1101            // (a/b)^-k = b^k / a^k; `new` re-fixes the sign and reduces.
1102            Rational::new(self.den.pow(k), self.num.pow(k))
1103        }
1104    }
1105
1106    /// Parse `"3/4"`, `"-3/4"`, or a bare integer `"5"`. Whitespace around the
1107    /// parts is tolerated; `None` on malformed input or a zero denominator.
1108    pub fn parse(s: &str) -> Option<Rational> {
1109        let s = s.trim();
1110        if let Some((n, d)) = s.split_once('/') {
1111            let num = BigInt::parse_decimal(n.trim())?;
1112            let den = BigInt::parse_decimal(d.trim())?;
1113            Rational::new(num, den)
1114        } else {
1115            Some(Rational::from_bigint(BigInt::parse_decimal(s)?))
1116        }
1117    }
1118}
1119
1120impl Ord for Rational {
1121    fn cmp(&self, other: &Self) -> Ordering {
1122        // a/b vs c/d with b, d > 0: compare a·d vs c·b (no rounding).
1123        self.num.mul(&other.den).cmp(&other.num.mul(&self.den))
1124    }
1125}
1126
1127impl PartialOrd for Rational {
1128    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1129        Some(self.cmp(other))
1130    }
1131}
1132
1133impl fmt::Display for Rational {
1134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1135        if self.is_integer() {
1136            write!(f, "{}", self.num)
1137        } else {
1138            write!(f, "{}/{}", self.num, self.den)
1139        }
1140    }
1141}
1142
1143impl fmt::Debug for Rational {
1144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1145        write!(f, "Rational({}/{})", self.num, self.den)
1146    }
1147}
1148
1149impl From<i64> for Rational {
1150    fn from(x: i64) -> Self {
1151        Rational::from_i64(x)
1152    }
1153}
1154
1155impl From<BigInt> for Rational {
1156    fn from(x: BigInt) -> Self {
1157        Rational::from_bigint(x)
1158    }
1159}
1160
1161// =====================================================================
1162// Decimal — exact base-10 fixed-point on top of BigInt
1163// =====================================================================
1164
1165/// How a [`Decimal`] resolves the digits it must drop when rounding to a smaller
1166/// scale. `HalfEven` (banker's rounding) is the money/finance default: the unbiased
1167/// tie-break that does not drift a long column of sums upward.
1168#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1169pub enum RoundingMode {
1170    /// Toward zero (truncate).
1171    Down,
1172    /// Away from zero.
1173    Up,
1174    /// Toward −∞.
1175    Floor,
1176    /// Toward +∞.
1177    Ceiling,
1178    /// Nearest; ties away from zero.
1179    HalfUp,
1180    /// Nearest; ties toward zero.
1181    HalfDown,
1182    /// Nearest; ties to the even neighbour (banker's rounding).
1183    HalfEven,
1184}
1185
1186/// `10^k` as a [`BigInt`].
1187fn ten_pow(k: u32) -> BigInt {
1188    BigInt::from_u64(10).pow(k)
1189}
1190
1191/// Round a rational to the nearest integer under `mode`. The single rounding
1192/// primitive: [`Decimal`] scale changes and division both funnel through here, so
1193/// every mode behaves identically everywhere.
1194fn round_rational_to_bigint(x: &Rational, mode: RoundingMode) -> BigInt {
1195    let num = x.numerator();
1196    let den = x.denominator(); // INVARIANT (Rational): den > 0.
1197    let (q, r) = num.div_rem(den).expect("rational denominator is nonzero");
1198    if r.is_zero() {
1199        return q; // exact — no rounding to do.
1200    }
1201    let neg = num.is_negative();
1202    // Compare 2·|r| against den to place the fraction relative to the half-way point.
1203    let twice = r.abs().mul(&BigInt::from_i64(2));
1204    let half = twice.cmp(den);
1205    let away = match mode {
1206        RoundingMode::Down => false,
1207        RoundingMode::Up => true,
1208        RoundingMode::Floor => neg,
1209        RoundingMode::Ceiling => !neg,
1210        RoundingMode::HalfUp => half != Ordering::Less,
1211        RoundingMode::HalfDown => half == Ordering::Greater,
1212        RoundingMode::HalfEven => {
1213            half == Ordering::Greater || (half == Ordering::Equal && q.is_odd())
1214        }
1215    };
1216    if away {
1217        // `q` is truncated toward zero, so rounding away adds the value's sign.
1218        if neg {
1219            q.sub(&BigInt::from_i64(1))
1220        } else {
1221            q.add(&BigInt::from_i64(1))
1222        }
1223    } else {
1224        q
1225    }
1226}
1227
1228/// An exact base-10 fixed-point number: an integer `coefficient` divided by a power
1229/// of ten. The value is `coefficient · 10^(−scale)`, so `19.99` is `coefficient =
1230/// 1999`, `scale = 2`. Money lives here — `0.1 + 0.2` is exactly `0.3`, never the
1231/// `0.30000000000000004` of a binary float, and a long ledger of sums never drifts.
1232///
1233/// `+`, `−`, `×` are exact (multiplication adds the scales); `÷` and [`Decimal::rescale`]
1234/// round under an explicit [`RoundingMode`] because base-10 division need not
1235/// terminate. Equality and ordering are by **value** (`1.0 == 1.00 == 1`); `scale`
1236/// is only a display hint. The coefficient is a [`BigInt`], so the value is unbounded
1237/// and exact — the i128 fast path is the documented performance follow-up.
1238#[derive(Clone)]
1239pub struct Decimal {
1240    coeff: BigInt,
1241    /// Number of base-10 fractional digits (value = `coeff / 10^scale`).
1242    scale: u32,
1243}
1244
1245impl Decimal {
1246    /// The integer `coeff` at scale 0.
1247    pub fn from_bigint(coeff: BigInt) -> Decimal {
1248        Decimal { coeff, scale: 0 }
1249    }
1250
1251    pub fn from_i64(x: i64) -> Decimal {
1252        Decimal::from_bigint(BigInt::from_i64(x))
1253    }
1254
1255    /// Construct directly from a coefficient and scale (value = `coeff / 10^scale`).
1256    pub fn from_coeff_scale(coeff: BigInt, scale: u32) -> Decimal {
1257        Decimal { coeff, scale }
1258    }
1259
1260    pub fn zero() -> Decimal {
1261        Decimal::from_i64(0)
1262    }
1263
1264    pub fn one() -> Decimal {
1265        Decimal::from_i64(1)
1266    }
1267
1268    pub fn scale(&self) -> u32 {
1269        self.scale
1270    }
1271
1272    pub fn coefficient(&self) -> &BigInt {
1273        &self.coeff
1274    }
1275
1276    pub fn is_zero(&self) -> bool {
1277        self.coeff.is_zero()
1278    }
1279
1280    pub fn is_negative(&self) -> bool {
1281        self.coeff.is_negative()
1282    }
1283
1284    pub fn negated(&self) -> Decimal {
1285        Decimal {
1286            coeff: self.coeff.negated(),
1287            scale: self.scale,
1288        }
1289    }
1290
1291    pub fn abs(&self) -> Decimal {
1292        Decimal {
1293            coeff: self.coeff.abs(),
1294            scale: self.scale,
1295        }
1296    }
1297
1298    /// Exact view as a [`Rational`] (`coeff / 10^scale`) — lossless, the bridge that
1299    /// keeps `Decimal` inside the exact tower.
1300    pub fn to_rational(&self) -> Rational {
1301        Rational::new(self.coeff.clone(), ten_pow(self.scale)).expect("10^scale is nonzero")
1302    }
1303
1304    /// The fixed-point value nearest `value` at the given `scale`, rounded under `mode`.
1305    pub fn from_rational(value: &Rational, scale: u32, mode: RoundingMode) -> Decimal {
1306        let scaled = value.mul(&Rational::from_bigint(ten_pow(scale)));
1307        Decimal {
1308            coeff: round_rational_to_bigint(&scaled, mode),
1309            scale,
1310        }
1311    }
1312
1313    /// Restate at a different scale. Widening appends zeros (exact); narrowing drops
1314    /// digits and rounds under `mode`.
1315    pub fn rescale(&self, scale: u32, mode: RoundingMode) -> Decimal {
1316        if scale >= self.scale {
1317            Decimal {
1318                coeff: self.coeff.mul(&ten_pow(scale - self.scale)),
1319                scale,
1320            }
1321        } else {
1322            Decimal::from_rational(&self.to_rational(), scale, mode)
1323        }
1324    }
1325
1326    /// Bring two values to a common scale (the larger) so coefficients line up.
1327    fn aligned(&self, other: &Decimal) -> (BigInt, BigInt, u32) {
1328        let s = self.scale.max(other.scale);
1329        let a = self.coeff.mul(&ten_pow(s - self.scale));
1330        let b = other.coeff.mul(&ten_pow(s - other.scale));
1331        (a, b, s)
1332    }
1333
1334    pub fn add(&self, other: &Decimal) -> Decimal {
1335        let (a, b, s) = self.aligned(other);
1336        Decimal {
1337            coeff: a.add(&b),
1338            scale: s,
1339        }
1340    }
1341
1342    pub fn sub(&self, other: &Decimal) -> Decimal {
1343        let (a, b, s) = self.aligned(other);
1344        Decimal {
1345            coeff: a.sub(&b),
1346            scale: s,
1347        }
1348    }
1349
1350    /// Exact product: coefficients multiply, scales add.
1351    pub fn mul(&self, other: &Decimal) -> Decimal {
1352        Decimal {
1353            coeff: self.coeff.mul(&other.coeff),
1354            scale: self.scale + other.scale,
1355        }
1356    }
1357
1358    /// Quotient rounded to `scale` under `mode`. `None` when `other == 0` — base-10
1359    /// division need not terminate, so the caller names the precision it wants.
1360    pub fn div(&self, other: &Decimal, scale: u32, mode: RoundingMode) -> Option<Decimal> {
1361        let q = self.to_rational().div(&other.to_rational())?;
1362        Some(Decimal::from_rational(&q, scale, mode))
1363    }
1364
1365    /// Minimal-scale form (trailing zeros stripped) — the canonical value used for
1366    /// `Eq`/`Hash` so `1.0`, `1.00`, and `1` are one key.
1367    fn normalized(&self) -> (BigInt, u32) {
1368        if self.coeff.is_zero() {
1369            return (BigInt::zero(), 0);
1370        }
1371        let ten = BigInt::from_u64(10);
1372        let mut c = self.coeff.clone();
1373        let mut s = self.scale;
1374        while s > 0 {
1375            let (q, r) = c.div_rem(&ten).expect("ten is nonzero");
1376            if !r.is_zero() {
1377                break;
1378            }
1379            c = q;
1380            s -= 1;
1381        }
1382        (c, s)
1383    }
1384
1385    /// Sign + little-endian coefficient bytes + scale — the wire form (the inverse of
1386    /// [`Decimal::from_le_bytes`]). Reuses [`BigInt`]'s exact byte serialization.
1387    pub fn to_le_bytes(&self) -> (bool, Vec<u8>, u32) {
1388        let (neg, bytes) = self.coeff.to_le_bytes();
1389        (neg, bytes, self.scale)
1390    }
1391
1392    pub fn from_le_bytes(negative: bool, bytes: &[u8], scale: u32) -> Decimal {
1393        Decimal {
1394            coeff: BigInt::from_le_bytes(negative, bytes),
1395            scale,
1396        }
1397    }
1398
1399    /// Parse plain decimal notation: optional sign, optional integer part, optional
1400    /// `.fraction`. `"19.99"`, `"-0.005"`, `".5"`, `"5."`, `"42"` all parse; the scale
1401    /// is the count of fractional digits. `None` on a non-digit or an empty value.
1402    pub fn parse(s: &str) -> Option<Decimal> {
1403        let s = s.trim();
1404        let (neg, body) = match s.as_bytes().first() {
1405            Some(b'-') => (true, &s[1..]),
1406            Some(b'+') => (false, &s[1..]),
1407            _ => (false, s),
1408        };
1409        if body.is_empty() {
1410            return None;
1411        }
1412        let (int_part, frac_part) = match body.split_once('.') {
1413            Some((i, f)) => (i, f),
1414            None => (body, ""),
1415        };
1416        if int_part.is_empty() && frac_part.is_empty() {
1417            return None; // a lone "." is not a number.
1418        }
1419        if !int_part.bytes().all(|c| c.is_ascii_digit())
1420            || !frac_part.bytes().all(|c| c.is_ascii_digit())
1421        {
1422            return None;
1423        }
1424        let digits = format!("{int_part}{frac_part}");
1425        let mag = if digits.is_empty() {
1426            BigInt::zero()
1427        } else {
1428            BigInt::parse_decimal(&digits)?
1429        };
1430        let coeff = if neg { mag.negated() } else { mag };
1431        Some(Decimal {
1432            coeff,
1433            scale: frac_part.len() as u32,
1434        })
1435    }
1436}
1437
1438impl PartialEq for Decimal {
1439    fn eq(&self, other: &Self) -> bool {
1440        self.normalized() == other.normalized()
1441    }
1442}
1443
1444impl Eq for Decimal {}
1445
1446impl std::hash::Hash for Decimal {
1447    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1448        self.normalized().hash(state);
1449    }
1450}
1451
1452impl Ord for Decimal {
1453    fn cmp(&self, other: &Self) -> Ordering {
1454        // Compare by value (cross-scale, no rounding) via the exact rational view.
1455        self.to_rational().cmp(&other.to_rational())
1456    }
1457}
1458
1459impl PartialOrd for Decimal {
1460    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1461        Some(self.cmp(other))
1462    }
1463}
1464
1465impl fmt::Display for Decimal {
1466    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1467        if self.scale == 0 {
1468            return write!(f, "{}", self.coeff);
1469        }
1470        let neg = self.coeff.is_negative();
1471        let mut digits = self.coeff.abs().to_string();
1472        let scale = self.scale as usize;
1473        if digits.len() <= scale {
1474            // Pad so there is at least one integer digit (e.g. "5" at scale 3 → "0005").
1475            digits = format!("{}{}", "0".repeat(scale + 1 - digits.len()), digits);
1476        }
1477        let point = digits.len() - scale;
1478        if neg {
1479            write!(f, "-")?;
1480        }
1481        write!(f, "{}.{}", &digits[..point], &digits[point..])
1482    }
1483}
1484
1485impl fmt::Debug for Decimal {
1486    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1487        write!(f, "Decimal({self})")
1488    }
1489}
1490
1491impl From<i64> for Decimal {
1492    fn from(x: i64) -> Self {
1493        Decimal::from_i64(x)
1494    }
1495}
1496
1497impl From<BigInt> for Decimal {
1498    fn from(x: BigInt) -> Self {
1499        Decimal::from_bigint(x)
1500    }
1501}
1502
1503// =====================================================================
1504// Complex — exact Gaussian rationals on top of Rational
1505// =====================================================================
1506
1507/// An exact complex number `re + im·i`, each part a [`Rational`]. Because the parts
1508/// are exact, `i·i == −1` and `(1+i)(1−i) == 2` hold with no floating error, and the
1509/// Gaussian rationals are closed under `+ − × ÷` (every nonzero value has an exact
1510/// inverse). The magnitude `√(re²+im²)` is irrational in general — request it as an
1511/// `f64` view via [`Complex::abs_f64`] rather than forcing the exact value inexact.
1512///
1513/// Complex numbers are NOT ordered, so there is deliberately no `Ord`/`PartialOrd`.
1514#[derive(Clone, PartialEq, Eq, Hash)]
1515pub struct Complex {
1516    re: Rational,
1517    im: Rational,
1518}
1519
1520impl Complex {
1521    pub fn new(re: Rational, im: Rational) -> Complex {
1522        Complex { re, im }
1523    }
1524
1525    /// A real number as `re + 0i`.
1526    pub fn from_rational(re: Rational) -> Complex {
1527        Complex {
1528            re,
1529            im: Rational::zero(),
1530        }
1531    }
1532
1533    pub fn from_i64(x: i64) -> Complex {
1534        Complex::from_rational(Rational::from_i64(x))
1535    }
1536
1537    pub fn zero() -> Complex {
1538        Complex {
1539            re: Rational::zero(),
1540            im: Rational::zero(),
1541        }
1542    }
1543
1544    pub fn one() -> Complex {
1545        Complex::from_i64(1)
1546    }
1547
1548    /// The imaginary unit `i` (`0 + 1i`).
1549    pub fn i() -> Complex {
1550        Complex {
1551            re: Rational::zero(),
1552            im: Rational::one(),
1553        }
1554    }
1555
1556    pub fn re(&self) -> &Rational {
1557        &self.re
1558    }
1559
1560    pub fn im(&self) -> &Rational {
1561        &self.im
1562    }
1563
1564    pub fn is_zero(&self) -> bool {
1565        self.re.is_zero() && self.im.is_zero()
1566    }
1567
1568    /// True when the imaginary part is zero (the value is a plain real).
1569    pub fn is_real(&self) -> bool {
1570        self.im.is_zero()
1571    }
1572
1573    /// `re − im·i`.
1574    pub fn conjugate(&self) -> Complex {
1575        Complex {
1576            re: self.re.clone(),
1577            im: self.im.negated(),
1578        }
1579    }
1580
1581    /// `re² + im²` — the squared magnitude, exact (a nonnegative [`Rational`]).
1582    pub fn norm_sqr(&self) -> Rational {
1583        self.re.mul(&self.re).add(&self.im.mul(&self.im))
1584    }
1585
1586    /// The magnitude `√(re²+im²)` as an `f64` (lossy by nature — the exact value is
1587    /// generally irrational). The components stay exact; this is a view.
1588    pub fn abs_f64(&self) -> f64 {
1589        self.norm_sqr().to_f64().sqrt()
1590    }
1591
1592    pub fn negated(&self) -> Complex {
1593        Complex {
1594            re: self.re.negated(),
1595            im: self.im.negated(),
1596        }
1597    }
1598
1599    pub fn add(&self, other: &Complex) -> Complex {
1600        Complex {
1601            re: self.re.add(&other.re),
1602            im: self.im.add(&other.im),
1603        }
1604    }
1605
1606    pub fn sub(&self, other: &Complex) -> Complex {
1607        Complex {
1608            re: self.re.sub(&other.re),
1609            im: self.im.sub(&other.im),
1610        }
1611    }
1612
1613    /// `(a+bi)(c+di) = (ac − bd) + (ad + bc)i`.
1614    pub fn mul(&self, other: &Complex) -> Complex {
1615        let (a, b, c, d) = (&self.re, &self.im, &other.re, &other.im);
1616        Complex {
1617            re: a.mul(c).sub(&b.mul(d)),
1618            im: a.mul(d).add(&b.mul(c)),
1619        }
1620    }
1621
1622    /// `1/self` via the conjugate over the squared magnitude — `None` only for zero.
1623    pub fn recip(&self) -> Option<Complex> {
1624        let n = self.norm_sqr();
1625        if n.is_zero() {
1626            return None;
1627        }
1628        let inv = n.recip().expect("norm is nonzero here");
1629        Some(Complex {
1630            re: self.re.mul(&inv),
1631            im: self.im.negated().mul(&inv),
1632        })
1633    }
1634
1635    /// `self / other` — `None` when `other == 0`.
1636    pub fn div(&self, other: &Complex) -> Option<Complex> {
1637        Some(self.mul(&other.recip()?))
1638    }
1639
1640    /// `self` raised to an integer power. Negative exponents take the reciprocal
1641    /// first; `None` only for zero raised to a negative power. `0^0 == 1`.
1642    pub fn pow(&self, exp: i32) -> Option<Complex> {
1643        if exp < 0 {
1644            return self.recip()?.pow(-exp);
1645        }
1646        let mut result = Complex::one();
1647        let mut base = self.clone();
1648        let mut e = exp as u32;
1649        while e > 0 {
1650            if e & 1 == 1 {
1651                result = result.mul(&base);
1652            }
1653            e >>= 1;
1654            if e > 0 {
1655                base = base.mul(&base);
1656            }
1657        }
1658        Some(result)
1659    }
1660
1661    /// Parse `"3+4i"`, `"3-4i"`, `"4i"`, `"-i"`, `"i"`, or a bare real `"3"` /`"1/2"`.
1662    /// Round-trips the [`Display`](fmt::Display) form. `None` on malformed input.
1663    pub fn parse(s: &str) -> Option<Complex> {
1664        let s = s.trim();
1665        if s.is_empty() {
1666            return None;
1667        }
1668        let bytes = s.as_bytes();
1669        if bytes[bytes.len() - 1] != b'i' {
1670            // No imaginary part: a plain real.
1671            return Some(Complex::from_rational(Rational::parse(s)?));
1672        }
1673        let body = &s[..s.len() - 1]; // strip trailing 'i'
1674                                      // Split into real and imaginary at the last sign that is not the leading one.
1675        let split = body
1676            .bytes()
1677            .enumerate()
1678            .rev()
1679            .find(|&(i, c)| i > 0 && (c == b'+' || c == b'-'))
1680            .map(|(i, _)| i);
1681        let (real_str, imag_str) = match split {
1682            Some(i) => (&body[..i], &body[i..]),
1683            None => ("", body),
1684        };
1685        let re = if real_str.is_empty() {
1686            Rational::zero()
1687        } else {
1688            Rational::parse(real_str)?
1689        };
1690        let im = match imag_str {
1691            "" | "+" => Rational::one(),
1692            "-" => Rational::from_i64(-1),
1693            other => Rational::parse(other)?,
1694        };
1695        Some(Complex { re, im })
1696    }
1697}
1698
1699impl fmt::Display for Complex {
1700    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1701        if self.im.is_zero() {
1702            return write!(f, "{}", self.re);
1703        }
1704        let mag = self.im.abs();
1705        let unit = mag == Rational::one(); // omit the coefficient when it is 1
1706        if self.re.is_zero() {
1707            // Pure imaginary.
1708            return if self.im.is_negative() {
1709                if unit {
1710                    write!(f, "-i")
1711                } else {
1712                    write!(f, "-{mag}i")
1713                }
1714            } else if unit {
1715                write!(f, "i")
1716            } else {
1717                write!(f, "{mag}i")
1718            };
1719        }
1720        let sign = if self.im.is_negative() { "-" } else { "+" };
1721        if unit {
1722            write!(f, "{}{}i", self.re, sign)
1723        } else {
1724            write!(f, "{}{}{}i", self.re, sign, mag)
1725        }
1726    }
1727}
1728
1729// =====================================================================
1730// ComplexF — floating-point complex (LAPACK's `Z`), the NUMERICAL dual
1731// of the exact `Complex`. Its parts are `f64`, so — unlike the exact
1732// Gaussian rationals — it has a `sqrt` (`√(a+bi)` from the real `sqrt`),
1733// which is what the sqrt-based complex decompositions (Cholesky, QR, eig,
1734// SVD) need. Inexact by nature (it rounds); use the exact `Complex` when
1735// you want zero error. Boxed as `Rc<ComplexF>` in `RuntimeValue` so the
1736// enum stays 16 bytes (the nanbox budget), exactly like `Complex`.
1737// =====================================================================
1738
1739/// A floating-point complex number `re + im·i`, each part an `f64`. NOT ordered
1740/// and NOT `Eq`/`Hash` (it carries `f64`s); equality is exact bit-for-value.
1741#[derive(Clone, Copy, PartialEq, Debug)]
1742pub struct ComplexF {
1743    re: f64,
1744    im: f64,
1745}
1746
1747impl ComplexF {
1748    pub fn new(re: f64, im: f64) -> ComplexF {
1749        ComplexF { re, im }
1750    }
1751    /// A real number as `re + 0i`.
1752    pub fn from_f64(re: f64) -> ComplexF {
1753        ComplexF { re, im: 0.0 }
1754    }
1755    pub fn re(&self) -> f64 {
1756        self.re
1757    }
1758    pub fn im(&self) -> f64 {
1759        self.im
1760    }
1761    pub fn is_zero(&self) -> bool {
1762        self.re == 0.0 && self.im == 0.0
1763    }
1764    /// True when the imaginary part is zero (a plain real).
1765    pub fn is_real(&self) -> bool {
1766        self.im == 0.0
1767    }
1768    /// `re − im·i`.
1769    pub fn conjugate(&self) -> ComplexF {
1770        ComplexF {
1771            re: self.re,
1772            im: -self.im,
1773        }
1774    }
1775    /// `re² + im²` — the squared magnitude.
1776    pub fn norm_sqr(&self) -> f64 {
1777        self.re * self.re + self.im * self.im
1778    }
1779    /// The magnitude `√(re²+im²)`.
1780    pub fn abs(&self) -> f64 {
1781        self.norm_sqr().sqrt()
1782    }
1783    pub fn negated(&self) -> ComplexF {
1784        ComplexF {
1785            re: -self.re,
1786            im: -self.im,
1787        }
1788    }
1789    pub fn add(&self, other: &ComplexF) -> ComplexF {
1790        ComplexF {
1791            re: self.re + other.re,
1792            im: self.im + other.im,
1793        }
1794    }
1795    pub fn sub(&self, other: &ComplexF) -> ComplexF {
1796        ComplexF {
1797            re: self.re - other.re,
1798            im: self.im - other.im,
1799        }
1800    }
1801    /// `(a+bi)(c+di) = (ac − bd) + (ad + bc)i`.
1802    pub fn mul(&self, other: &ComplexF) -> ComplexF {
1803        let (a, b, c, d) = (self.re, self.im, other.re, other.im);
1804        ComplexF {
1805            re: a * c - b * d,
1806            im: a * d + b * c,
1807        }
1808    }
1809    /// `1/self` via the conjugate over the squared magnitude — `None` only for zero.
1810    pub fn recip(&self) -> Option<ComplexF> {
1811        let n = self.norm_sqr();
1812        if n == 0.0 {
1813            return None;
1814        }
1815        Some(ComplexF {
1816            re: self.re / n,
1817            im: -self.im / n,
1818        })
1819    }
1820    /// `self / other` — `None` when `other == 0`.
1821    pub fn div(&self, other: &ComplexF) -> Option<ComplexF> {
1822        Some(self.mul(&other.recip()?))
1823    }
1824    /// The PRINCIPAL square root `√(a+bi)`, from the real `sqrt` only (no transcendentals):
1825    /// `√z = √((|z|+a)/2) + sign(b)·√((|z|−a)/2)·i`. This is the operation the exact `Complex`
1826    /// cannot do (its magnitude is irrational) — the reason a floating-point complex exists.
1827    pub fn sqrt(&self) -> ComplexF {
1828        let m = self.abs();
1829        if m == 0.0 {
1830            return ComplexF { re: 0.0, im: 0.0 };
1831        }
1832        let re = ((m + self.re) * 0.5).max(0.0).sqrt();
1833        let im0 = ((m - self.re) * 0.5).max(0.0).sqrt();
1834        ComplexF {
1835            re,
1836            im: if self.im < 0.0 { -im0 } else { im0 },
1837        }
1838    }
1839    /// `self` raised to an integer power (binary exponentiation); `None` only for zero to a
1840    /// negative power. `0^0 == 1`.
1841    pub fn pow(&self, exp: i32) -> Option<ComplexF> {
1842        if exp < 0 {
1843            return self.recip()?.pow(-exp);
1844        }
1845        let mut result = ComplexF::from_f64(1.0);
1846        let mut base = *self;
1847        let mut e = exp as u32;
1848        while e > 0 {
1849            if e & 1 == 1 {
1850                result = result.mul(&base);
1851            }
1852            e >>= 1;
1853            if e > 0 {
1854                base = base.mul(&base);
1855            }
1856        }
1857        Some(result)
1858    }
1859}
1860
1861impl fmt::Display for ComplexF {
1862    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1863        // Basic view; the interpreter renders the user-facing form through `fmt_f64` (shortest
1864        // round-trip) so `2.0 + 1.0i` shows as `2+i`, matching the exact `Complex`.
1865        if self.im == 0.0 {
1866            return write!(f, "{}", self.re);
1867        }
1868        let sign = if self.im < 0.0 { "-" } else { "+" };
1869        write!(f, "{}{}{}i", self.re, sign, self.im.abs())
1870    }
1871}
1872
1873impl fmt::Debug for Complex {
1874    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1875        write!(f, "Complex({self})")
1876    }
1877}
1878
1879impl From<i64> for Complex {
1880    fn from(x: i64) -> Self {
1881        Complex::from_i64(x)
1882    }
1883}
1884
1885impl From<Rational> for Complex {
1886    fn from(x: Rational) -> Self {
1887        Complex::from_rational(x)
1888    }
1889}
1890
1891// =====================================================================
1892// Modular — the ring ℤ/nℤ over an arbitrary modulus, on top of BigInt
1893// =====================================================================
1894
1895/// Extended Euclid on `BigInt`: returns `(g, x, y)` with `a·x + b·y = g`, `g = gcd(a, b)`.
1896/// The basis for the modular inverse (`g == 1 ⇒ x` is `a⁻¹ mod b`).
1897fn bigint_egcd(a: &BigInt, b: &BigInt) -> (BigInt, BigInt, BigInt) {
1898    let (mut old_r, mut r) = (a.clone(), b.clone());
1899    let (mut old_s, mut s) = (BigInt::from_i64(1), BigInt::zero());
1900    let (mut old_t, mut t) = (BigInt::zero(), BigInt::from_i64(1));
1901    while !r.is_zero() {
1902        let (q, _) = old_r.div_rem(&r).expect("r is nonzero inside the loop");
1903        let nr = old_r.sub(&q.mul(&r));
1904        old_r = std::mem::replace(&mut r, nr);
1905        let ns = old_s.sub(&q.mul(&s));
1906        old_s = std::mem::replace(&mut s, ns);
1907        let nt = old_t.sub(&q.mul(&t));
1908        old_t = std::mem::replace(&mut t, nt);
1909    }
1910    (old_r, old_s, old_t)
1911}
1912
1913/// An element of the ring ℤ/nℤ — an integer taken modulo a fixed `modulus`. This is the
1914/// arbitrary-modulus generalisation of [`crate::Word8`]/…/[`crate::Word64`] (whose modulus is a power of
1915/// two): arithmetic WRAPS into `[0, modulus)`, the cyclic group where overflow is the point,
1916/// not a bug. The number-theory / crypto substrate — modular exponentiation and the
1917/// extended-Euclid inverse live here, so RSA-style and finite-field code is exact.
1918///
1919/// INVARIANT: `0 ≤ value < modulus` and `modulus ≥ 1` (built via [`Modular::new`], which
1920/// reduces into range), so equal residues share one representation (`Eq`/`Hash` are structural).
1921/// NOT ordered (ℤ/nℤ has no canonical total order).
1922#[derive(Clone, PartialEq, Eq, Hash)]
1923pub struct Modular {
1924    value: BigInt,
1925    modulus: BigInt,
1926}
1927
1928/// Euclidean reduction into `[0, modulus)` (the remainder is made non-negative).
1929fn mod_reduce(value: BigInt, modulus: &BigInt) -> BigInt {
1930    let (_, r) = value.div_rem(modulus).expect("modulus is nonzero");
1931    if r.is_negative() {
1932        r.add(modulus)
1933    } else {
1934        r
1935    }
1936}
1937
1938impl Modular {
1939    /// Reduce `value` into the ring ℤ/`modulus`ℤ. `None` for a non-positive modulus.
1940    pub fn new(value: BigInt, modulus: BigInt) -> Option<Modular> {
1941        if modulus.is_zero() || modulus.is_negative() {
1942            return None;
1943        }
1944        let value = mod_reduce(value, &modulus);
1945        Some(Modular { value, modulus })
1946    }
1947
1948    /// Convenience over machine integers (`None` if `modulus ≤ 0`).
1949    pub fn from_i64(value: i64, modulus: i64) -> Option<Modular> {
1950        Modular::new(BigInt::from_i64(value), BigInt::from_i64(modulus))
1951    }
1952
1953    /// The canonical representative in `[0, modulus)`.
1954    pub fn value(&self) -> &BigInt {
1955        &self.value
1956    }
1957
1958    pub fn modulus(&self) -> &BigInt {
1959        &self.modulus
1960    }
1961
1962    pub fn is_zero(&self) -> bool {
1963        self.value.is_zero()
1964    }
1965
1966    /// `self + other` — `None` when the moduli differ (a ring mismatch, like a Word width mismatch).
1967    pub fn add(&self, other: &Modular) -> Option<Modular> {
1968        if self.modulus != other.modulus {
1969            return None;
1970        }
1971        Modular::new(self.value.add(&other.value), self.modulus.clone())
1972    }
1973
1974    pub fn sub(&self, other: &Modular) -> Option<Modular> {
1975        if self.modulus != other.modulus {
1976            return None;
1977        }
1978        Modular::new(self.value.sub(&other.value), self.modulus.clone())
1979    }
1980
1981    pub fn mul(&self, other: &Modular) -> Option<Modular> {
1982        if self.modulus != other.modulus {
1983            return None;
1984        }
1985        Modular::new(self.value.mul(&other.value), self.modulus.clone())
1986    }
1987
1988    /// The additive inverse `−self` (i.e. `modulus − value`, reduced).
1989    pub fn negated(&self) -> Modular {
1990        Modular::new(self.value.negated(), self.modulus.clone()).expect("modulus stays valid")
1991    }
1992
1993    /// `self^exp` by fast modular exponentiation (square-and-multiply). `0^0 == 1`.
1994    pub fn pow(&self, mut exp: u64) -> Modular {
1995        let one = Modular::new(BigInt::from_i64(1), self.modulus.clone()).expect("modulus valid");
1996        let mut result = one;
1997        let mut base = self.clone();
1998        while exp > 0 {
1999            if exp & 1 == 1 {
2000                result = result.mul(&base).expect("same modulus");
2001            }
2002            exp >>= 1;
2003            if exp > 0 {
2004                base = base.mul(&base).expect("same modulus");
2005            }
2006        }
2007        result
2008    }
2009
2010    /// The multiplicative inverse `self⁻¹` (extended Euclid). `None` unless
2011    /// `gcd(value, modulus) == 1` (the value must be a unit of the ring).
2012    pub fn inverse(&self) -> Option<Modular> {
2013        let (g, x, _) = bigint_egcd(&self.value, &self.modulus);
2014        if g != BigInt::from_i64(1) {
2015            return None;
2016        }
2017        Modular::new(x, self.modulus.clone())
2018    }
2019
2020    /// `self / other = self · other⁻¹` — `None` on a modulus mismatch or a non-invertible divisor.
2021    pub fn div(&self, other: &Modular) -> Option<Modular> {
2022        if self.modulus != other.modulus {
2023            return None;
2024        }
2025        self.mul(&other.inverse()?)
2026    }
2027}
2028
2029impl fmt::Display for Modular {
2030    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2031        write!(f, "{} (mod {})", self.value, self.modulus)
2032    }
2033}
2034
2035impl fmt::Debug for Modular {
2036    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2037        write!(f, "Modular({} mod {})", self.value, self.modulus)
2038    }
2039}
2040
2041// ─── Exact float interop ────────────────────────────────────────────────────
2042//
2043// Cross-type numeric comparison in LOGOS is EXACT — mathematical values, never
2044// a lossy cast (`i as f64` rounds above 2^53, so a cast-based `==` would call
2045// `9007199254740993` equal to the float `9007199254740992.0`). Every finite
2046// f64 is exactly `±m · 2^e`, so the exact answer is always computable through
2047// the BigInt/Rational tower. CPython uses the same model.
2048
2049/// The Mersenne prime 2^61 − 1: the modulus of the UNIFIED numeric hash.
2050/// Every numeric type hashes to its mathematical value mod P, so values that
2051/// compare equal across types (`1 == 1.0 == 1/1`) hash equal — the hash/
2052/// equality coherence law that lets mixed-type map keys unify.
2053pub const NUMERIC_HASH_P: u64 = (1u64 << 61) - 1;
2054
2055/// Decompose a finite f64 into `(negative, mantissa, exponent)` with
2056/// value = ±mantissa · 2^exponent (mantissa integral). `None` for NaN/±inf.
2057fn decompose_f64(f: f64) -> Option<(bool, u64, i32)> {
2058    if !f.is_finite() {
2059        return None;
2060    }
2061    let bits = f.to_bits();
2062    let neg = bits >> 63 == 1;
2063    let biased = ((bits >> 52) & 0x7ff) as i32;
2064    let frac = bits & ((1u64 << 52) - 1);
2065    let (m, e) = if biased == 0 {
2066        (frac, -1074) // subnormal (or zero)
2067    } else {
2068        (frac | (1u64 << 52), biased - 1075)
2069    };
2070    Some((neg, m, e))
2071}
2072
2073/// The EXACT rational value of a finite f64. `None` for NaN/±inf.
2074pub fn rational_from_f64_exact(f: f64) -> Option<Rational> {
2075    let (neg, m, e) = decompose_f64(f)?;
2076    let mag = BigInt::from_u64(m);
2077    let two = BigInt::from_u64(2);
2078    let (num, den) = if e >= 0 {
2079        (mag.mul(&two.pow(e as u32)), BigInt::from_i64(1))
2080    } else {
2081        (mag, two.pow((-e) as u32))
2082    };
2083    let num = if neg { num.negated() } else { num };
2084    Rational::new(num, den)
2085}
2086
2087/// The f64 nearest to `r` (ties to even), rounded once from the exact value: the binary exponent
2088/// comes from the bit lengths, the quotient is scaled to 53 significant bits (or onto the `2^-1074`
2089/// grid below the normal range), and the remainder decides the rounding. Past the largest finite
2090/// float it is the signed infinity. Unlike [`Rational::to_f64`], which divides two rounded doubles,
2091/// this never rounds twice.
2092pub fn rational_to_f64_nearest(r: &Rational) -> f64 {
2093    if r.is_zero() {
2094        return 0.0;
2095    }
2096    let neg = r.is_negative();
2097    let n = r.numerator().abs();
2098    let d = r.denominator().clone();
2099    let e0 = n.bit_len() as i64 - d.bit_len() as i64;
2100    let at_least = if e0 >= 0 {
2101        n >= d.shl_bits(e0 as u64)
2102    } else {
2103        n.shl_bits((-e0) as u64) >= d
2104    };
2105    let e = if at_least { e0 } else { e0 - 1 };
2106    if e > 1023 {
2107        return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
2108    }
2109    let shift = if e >= -1022 { 52 - e } else { 1074 };
2110    let (num, den) = if shift >= 0 {
2111        (n.shl_bits(shift as u64), d)
2112    } else {
2113        (n, d.shl_bits((-shift) as u64))
2114    };
2115    let (mut q, rem) = num.div_rem(&den).expect("the denominator is nonzero");
2116    let round_up = match rem.add(&rem).cmp(&den) {
2117        Ordering::Greater => true,
2118        Ordering::Less => false,
2119        Ordering::Equal => q.is_odd(),
2120    };
2121    if round_up {
2122        q = q.add(&BigInt::from_i64(1));
2123    }
2124    let significand = q.to_u64().expect("at most 2^53 after rounding") as f64;
2125    let magnitude = scale_by_pow2(significand, -shift);
2126    if neg {
2127        -magnitude
2128    } else {
2129        magnitude
2130    }
2131}
2132
2133/// `2^j` for a normal exponent `j ∈ [-1022, 1023]`.
2134fn pow2_normal(j: i64) -> f64 {
2135    f64::from_bits(((j + 1023) as u64) << 52)
2136}
2137
2138/// `x · 2^k`, exact whenever the product is representable: the scale is split into factors that
2139/// are each a normal power of two, so no intermediate overflows or underflows.
2140fn scale_by_pow2(x: f64, k: i64) -> f64 {
2141    if k < -1022 {
2142        x * pow2_normal(-1022) * pow2_normal(k + 1022)
2143    } else if k > 1023 {
2144        x * pow2_normal(1023) * pow2_normal(k - 1023)
2145    } else {
2146        x * pow2_normal(k)
2147    }
2148}
2149
2150/// Exact comparison of an i64 against an f64. `None` iff `f` is NaN.
2151pub fn cmp_i64_f64_exact(i: i64, f: f64) -> Option<Ordering> {
2152    if f.is_nan() {
2153        return None;
2154    }
2155    if f == f64::INFINITY {
2156        return Some(Ordering::Less);
2157    }
2158    if f == f64::NEG_INFINITY {
2159        return Some(Ordering::Greater);
2160    }
2161    // Fast path: |i| ≤ 2^53 is exactly representable, so the f64 compare IS
2162    // exact (the common case — small ints against floats).
2163    if i.unsigned_abs() <= (1u64 << 53) {
2164        return (i as f64).partial_cmp(&f);
2165    }
2166    let fr = rational_from_f64_exact(f).expect("finite f64 is an exact rational");
2167    Some(Rational::from_i64(i).cmp(&fr))
2168}
2169
2170/// Exact comparison of a BigInt against an f64. `None` iff `f` is NaN.
2171pub fn cmp_bigint_f64_exact(b: &BigInt, f: f64) -> Option<Ordering> {
2172    if f.is_nan() {
2173        return None;
2174    }
2175    if f == f64::INFINITY {
2176        return Some(Ordering::Less);
2177    }
2178    if f == f64::NEG_INFINITY {
2179        return Some(Ordering::Greater);
2180    }
2181    let fr = rational_from_f64_exact(f).expect("finite f64 is an exact rational");
2182    Some(Rational::from_bigint(b.clone()).cmp(&fr))
2183}
2184
2185/// Exact comparison of a Rational against an f64. `None` iff `f` is NaN.
2186pub fn cmp_rational_f64_exact(r: &Rational, f: f64) -> Option<Ordering> {
2187    if f.is_nan() {
2188        return None;
2189    }
2190    if f == f64::INFINITY {
2191        return Some(Ordering::Less);
2192    }
2193    if f == f64::NEG_INFINITY {
2194        return Some(Ordering::Greater);
2195    }
2196    let fr = rational_from_f64_exact(f).expect("finite f64 is an exact rational");
2197    Some(r.cmp(&fr))
2198}
2199
2200/// Reduce a u64 mod P (one Mersenne fold suffices: `x >> 61 ≤ 7`).
2201fn mod_p(x: u64) -> u64 {
2202    let r = (x & NUMERIC_HASH_P) + (x >> 61);
2203    if r >= NUMERIC_HASH_P {
2204        r - NUMERIC_HASH_P
2205    } else {
2206        r
2207    }
2208}
2209
2210fn mul_mod_p(a: u64, b: u64) -> u64 {
2211    ((a as u128 * b as u128) % (NUMERIC_HASH_P as u128)) as u64
2212}
2213
2214fn pow_mod_p(mut base: u64, mut exp: u64) -> u64 {
2215    let mut acc = 1u64;
2216    base %= NUMERIC_HASH_P;
2217    while exp > 0 {
2218        if exp & 1 == 1 {
2219            acc = mul_mod_p(acc, base);
2220        }
2221        base = mul_mod_p(base, base);
2222        exp >>= 1;
2223    }
2224    acc
2225}
2226
2227/// Apply the sign to a magnitude hash: negatives map to `P − h` (0 fixed),
2228/// shared by every numeric hasher so equal values agree.
2229fn signed_hash(neg: bool, h: u64) -> u64 {
2230    if neg && h != 0 {
2231        NUMERIC_HASH_P - h
2232    } else {
2233        h
2234    }
2235}
2236
2237/// The unified numeric hash of an i64 (its value mod P, sign-adjusted).
2238pub fn numeric_hash_i64(n: i64) -> u64 {
2239    signed_hash(n < 0, mod_p(n.unsigned_abs()))
2240}
2241
2242/// The unified numeric hash of a BigInt. Limbs fold most-significant first:
2243/// 2^64 ≡ 8 (mod 2^61 − 1).
2244pub fn numeric_hash_bigint(b: &BigInt) -> u64 {
2245    let mut acc: u64 = 0;
2246    for &limb in b.mag.limbs().iter().rev() {
2247        let t = (acc as u128) * 8 + (mod_p(limb) as u128);
2248        acc = (t % (NUMERIC_HASH_P as u128)) as u64;
2249    }
2250    signed_hash(b.is_negative(), acc)
2251}
2252
2253/// The unified numeric hash of an f64: `m · 2^e mod P` via modular
2254/// exponentiation (2^61 ≡ 1, so the exponent reduces mod 61). NaN and the
2255/// infinities take fixed sentinels outside the finite-value pattern.
2256pub fn numeric_hash_f64(f: f64) -> u64 {
2257    if f.is_nan() {
2258        return 0x6e616e; // "nan"
2259    }
2260    if f == f64::INFINITY {
2261        return 314159;
2262    }
2263    if f == f64::NEG_INFINITY {
2264        return NUMERIC_HASH_P - 314159;
2265    }
2266    let (neg, m, e) = decompose_f64(f).expect("finite");
2267    let h = mul_mod_p(mod_p(m), pow_mod_p(2, e.rem_euclid(61) as u64));
2268    signed_hash(neg, h)
2269}
2270
2271/// The unified numeric hash of a Rational: `num · den⁻¹ mod P` (Fermat
2272/// inverse; P is prime, and a reduced denominator is never ≡ 0 mod P for
2273/// representable values).
2274pub fn numeric_hash_rational(r: &Rational) -> u64 {
2275    let num = numeric_hash_bigint(&r.numerator().abs());
2276    let den = numeric_hash_bigint(&r.denominator().abs());
2277    let inv = pow_mod_p(den, NUMERIC_HASH_P - 2);
2278    signed_hash(r.is_negative(), mul_mod_p(num, inv))
2279}
2280
2281/// The language's `min` of two reals: a NaN gives way to the other operand, and of two equal values the
2282/// one with the negative sign, so `min(0, -0.0)` is `-0.0` (IEEE 754-2019 `minimumNumber`). One answer on
2283/// every tier and under every optimizer, where `f64::min` leaves the sign of two equal zeros open.
2284pub fn float_min(a: f64, b: f64) -> f64 {
2285    if a.is_nan() {
2286        b
2287    } else if b.is_nan() || a < b || (a == b && a.is_sign_negative()) {
2288        a
2289    } else {
2290        b
2291    }
2292}
2293
2294/// The language's `max` of two reals: a NaN gives way to the other operand, and of two equal values the
2295/// one with the positive sign, so `max(0, -0.0)` is `0.0` (IEEE 754-2019 `maximumNumber`).
2296pub fn float_max(a: f64, b: f64) -> f64 {
2297    if a.is_nan() {
2298        b
2299    } else if b.is_nan() || a > b || (a == b && a.is_sign_positive()) {
2300        a
2301    } else {
2302        b
2303    }
2304}
2305
2306#[cfg(test)]
2307#[path = "../../logicaffeine_tests/unit/logicaffeine_base/numeric/tests.rs"]
2308mod tests;