Skip to main content

quickjs/
bigint.rs

1//! Arbitrary-precision integers, the engine's `BigInt`.
2//!
3//! A `BigInt` is a sign and a magnitude in base 2^32, little-endian, with no trailing zero
4//! words — so zero is the empty magnitude and every value has exactly one representation.
5//! That last part is what lets `SameValueZero` compare two BigInts with `==` and what lets a
6//! `Map` use one as a key.
7//!
8//! # Two's complement is the hard part
9//!
10//! `&`, `|`, `^` and `~` are defined on the *infinite* two's-complement form of the operand,
11//! which is why `-1n & 3n` is `3n` and `~0n` is `-1n`. The implementation converts to a
12//! fixed width of `max(len(a), len(b)) + 1` words, does the operation there, and converts
13//! back; the extra word carries the sign extension so the result's sign is recoverable.
14//!
15//! `>>` is arithmetic: `-1n >> 1n` is `-1n`, not `0n`. The shift is defined as
16//! `floor(a / 2^n)`, which for a negative value is *not* a right shift of the magnitude —
17//! that rounds toward zero. The implementation does the magnitude shift and then corrects by
18//! subtracting one when any shifted-out bit was set.
19//!
20//! # No dependency
21//!
22//! There is no bignum crate available offline, so this is the arithmetic. It is deliberately
23//! the simplest correct algorithm at each step — schoolbook multiply, binary long division
24//! for the general case, divide-by-10^9 for decimal output — rather than the fastest.
25
26use std::fmt;
27
28/// The largest exponent `**` will compute. An exponent that would need more bits than this
29/// is a `RangeError` rather than an allocation the process cannot survive.
30const MAX_POW_BITS: u64 = 1 << 24;
31
32/// An arbitrary-precision integer.
33#[derive(Clone, PartialEq, Eq, Debug)]
34pub struct BigInt {
35    /// Whether the value is below zero. Zero is never negative: `-0n` is `0n`.
36    negative: bool,
37    /// Base 2^32 magnitude, little-endian, with no trailing zero words.
38    mag: Vec<u32>,
39}
40
41impl BigInt {
42    /// Zero.
43    pub fn zero() -> BigInt {
44        BigInt {
45            negative: false,
46            mag: Vec::new(),
47        }
48    }
49
50    /// One.
51    pub fn one() -> BigInt {
52        BigInt::from_i64(1)
53    }
54
55    /// The value of an `i64`.
56    pub fn from_i64(value: i64) -> BigInt {
57        let negative = value < 0;
58        // `i64::MIN` has no positive counterpart, so the magnitude comes from the unsigned
59        // form rather than from `abs`.
60        let magnitude = value.unsigned_abs();
61        let mut big = BigInt::from_u64_magnitude(magnitude);
62        big.negative = negative && !big.is_zero();
63        big
64    }
65
66    fn from_u64_magnitude(value: u64) -> BigInt {
67        let mut mag = vec![value as u32, (value >> 32) as u32];
68        bigint_trim(&mut mag);
69        BigInt {
70            negative: false,
71            mag,
72        }
73    }
74
75    /// The value of an `f64` truncated toward zero, which the relational comparison needs.
76    ///
77    /// Only called for a finite value whose magnitude is below `1.7e38`, so the exponent is
78    /// bounded and the word count stays small.
79    pub fn from_f64_truncated(value: f64) -> BigInt {
80        let negative = value < 0.0;
81        let magnitude = value.abs();
82        if !magnitude.is_finite() || magnitude == 0.0 {
83            return BigInt::zero();
84        }
85        let mut mag = Vec::new();
86        // Peel 32 bits at a time off the top of the value.
87        let mut remaining = magnitude;
88        while remaining >= 1.0 {
89            let low = remaining % 4294967296.0;
90            mag.push(low as u32);
91            remaining = (remaining - low) / 4294967296.0;
92        }
93        bigint_trim(&mut mag);
94        BigInt {
95            negative: negative && !mag.is_empty(),
96            mag,
97        }
98    }
99
100    /// Whether this is zero.
101    pub fn is_zero(&self) -> bool {
102        self.mag.is_empty()
103    }
104
105    /// Whether this is one.
106    pub fn is_one(&self) -> bool {
107        !self.negative && self.mag.len() == 1 && self.mag[0] == 1
108    }
109
110    /// Whether the value is below zero.
111    pub fn is_negative(&self) -> bool {
112        self.negative
113    }
114
115    /// The number of significant bits in the magnitude: `0` for zero, `1` for `1n`.
116    ///
117    /// `Math.sumPrecise` needs it to know where the leading bit of an exact sum sits, which
118    /// is what decides how many bits survive the final rounding.
119    pub fn bit_length(&self) -> u64 {
120        match self.mag.last() {
121            None => 0,
122            Some(top) => (self.mag.len() as u64 - 1) * 32 + (32 - top.leading_zeros() as u64),
123        }
124    }
125
126    /// The value as an `f64`, for the relational comparisons that accept a Number.
127    ///
128    /// Rounding is the platform's, which is what `BigInt < Number` needs: the comparison is
129    /// on the mathematical values, and an `f64` cannot tell `2^60` from `2^60 + 1` anyway.
130    pub fn to_f64(&self) -> f64 {
131        let mut value = 0.0f64;
132        for word in self.mag.iter().rev() {
133            value = value * 4294967296.0 + *word as f64;
134        }
135        if self.negative { -value } else { value }
136    }
137
138    /// The value as an `i64` when it fits, which `BigInt.asIntN`-free paths use.
139    pub fn to_i64(&self) -> Option<i64> {
140        if self.mag.len() > 2 {
141            return None;
142        }
143        let magnitude = self.mag.first().copied().unwrap_or(0) as u64
144            | ((self.mag.get(1).copied().unwrap_or(0) as u64) << 32);
145        if self.negative {
146            // `-(i64::MIN as u64)` overflows, so the check is on the unsigned magnitude.
147            if magnitude > i64::MIN.unsigned_abs() {
148                return None;
149            }
150            Some((magnitude as i64).wrapping_neg())
151        } else {
152            i64::try_from(magnitude).ok()
153        }
154    }
155
156    /// The value of a `u64`.
157    pub fn from_u64(value: u64) -> BigInt {
158        BigInt::from_u64_magnitude(value)
159    }
160
161    /// The low 64 bits, as the two's-complement bit pattern.
162    ///
163    /// `BigInt::asIntN(64, v)` / `asUintN(64, v)`: a typed array stores the value modulo
164    /// `2^64`, so `new BigUint64Array(1)[0] = -1n` reads back `2^64-1` and a value that
165    /// needs more than 64 bits keeps only its low ones.
166    pub fn to_u64_wrapping(&self) -> u64 {
167        let low = self.mag.first().copied().unwrap_or(0) as u64;
168        let high = self.mag.get(1).copied().unwrap_or(0) as u64;
169        let magnitude = low | (high << 32);
170        if self.negative {
171            magnitude.wrapping_neg()
172        } else {
173            magnitude
174        }
175    }
176
177    /// `to_u64_wrapping` reinterpreted as signed.
178    pub fn to_i64_wrapping(&self) -> i64 {
179        self.to_u64_wrapping() as i64
180    }
181
182    /// Parse `text` in `radix`, which is what a literal and `BigInt("…")` both need.
183    ///
184    /// Surrounding whitespace is not accepted here; the caller trims it, because the literal
185    /// grammar and the string grammar differ in what they allow around the digits.
186    pub fn from_radix(text: &str, radix: u32) -> Option<BigInt> {
187        if !(2..=36).contains(&radix) || text.is_empty() {
188            return None;
189        }
190        let mut result = BigInt::zero();
191        let multiplier = BigInt::from_i64(radix as i64);
192        for character in text.chars() {
193            let digit = character.to_digit(radix)?;
194            result = result.mul(&multiplier).add(&BigInt::from_i64(digit as i64));
195        }
196        Some(result)
197    }
198
199    /// Parse a JS `BigInt` string: optional sign, optional `0x`/`0o`/`0b`, no fraction.
200    ///
201    /// The grammar is `StringIntegerLiteral`, which is stricter than it looks and is why
202    /// `trim` only happens at the very edges:
203    ///
204    /// * whitespace may surround the literal, but not sit between the sign and the digits
205    ///   — `"- 1"` and `" +0x10 "` are both `SyntaxError`s, not `-1` and `16`;
206    /// * a radix prefix has to follow the sign directly, with no whitespace between;
207    /// * an empty literal (or all whitespace) is `0`, but a bare sign is not.
208    pub fn from_string(text: &str) -> Option<BigInt> {
209        let text = text.trim();
210        if text.is_empty() {
211            return Some(BigInt::zero());
212        }
213        let (negative, body) = match text.strip_prefix('-') {
214            Some(rest) => (true, rest),
215            None => (false, text.strip_prefix('+').unwrap_or(text)),
216        };
217        // A radix prefix is part of a *non-decimal* literal, and `StrNonDecimalIntegerLiteral`
218        // has no sign: `BigInt("-0x10")` is a `SyntaxError`, not `-16`. Only the decimal
219        // form accepts `+`/`-`.
220        let has_radix_prefix = body.starts_with("0x")
221            || body.starts_with("0X")
222            || body.starts_with("0o")
223            || body.starts_with("0O")
224            || body.starts_with("0b")
225            || body.starts_with("0B");
226        if has_radix_prefix && negative {
227            return None;
228        }
229        if has_radix_prefix && text.starts_with('+') {
230            return None;
231        }
232        let (radix, digits) =
233            if let Some(rest) = body.strip_prefix("0x").or(body.strip_prefix("0X")) {
234                (16, rest)
235            } else if let Some(rest) = body.strip_prefix("0o").or(body.strip_prefix("0O")) {
236                (8, rest)
237            } else if let Some(rest) = body.strip_prefix("0b").or(body.strip_prefix("0B")) {
238                (2, rest)
239            } else {
240                (10, body)
241            };
242        let value = BigInt::from_radix(digits, radix)?;
243        Some(if negative { value.negate() } else { value })
244    }
245
246    /// The negation.
247    pub fn negate(&self) -> BigInt {
248        if self.is_zero() {
249            // `-0n` is `0n`, not a negative zero.
250            return BigInt::zero();
251        }
252        BigInt {
253            negative: !self.negative,
254            mag: self.mag.clone(),
255        }
256    }
257
258    /// The absolute value.
259    pub fn abs(&self) -> BigInt {
260        BigInt {
261            negative: false,
262            mag: self.mag.clone(),
263        }
264    }
265
266    /// Signed addition.
267    pub fn add(&self, other: &BigInt) -> BigInt {
268        if self.negative == other.negative {
269            let mut mag = add_mag(&self.mag, &other.mag);
270            bigint_trim(&mut mag);
271            return BigInt {
272                negative: self.negative && !mag.is_empty(),
273                mag,
274            };
275        }
276        // Opposite signs: the larger magnitude decides the sign and the difference is the
277        // result.
278        match cmp_mag(&self.mag, &other.mag) {
279            std::cmp::Ordering::Equal => BigInt::zero(),
280            std::cmp::Ordering::Greater => {
281                let mut mag = sub_mag(&self.mag, &other.mag);
282                bigint_trim(&mut mag);
283                BigInt {
284                    negative: self.negative,
285                    mag,
286                }
287            }
288            std::cmp::Ordering::Less => {
289                let mut mag = sub_mag(&other.mag, &self.mag);
290                bigint_trim(&mut mag);
291                BigInt {
292                    negative: other.negative,
293                    mag,
294                }
295            }
296        }
297    }
298
299    /// Signed subtraction.
300    pub fn sub(&self, other: &BigInt) -> BigInt {
301        self.add(&other.negate())
302    }
303
304    /// Signed multiplication.
305    pub fn mul(&self, other: &BigInt) -> BigInt {
306        if self.is_zero() || other.is_zero() {
307            return BigInt::zero();
308        }
309        let mut mag = vec![0u32; self.mag.len() + other.mag.len()];
310        for (i, a) in self.mag.iter().enumerate() {
311            let mut carry = 0u64;
312            for (j, b) in other.mag.iter().enumerate() {
313                let slot = &mut mag[i + j];
314                let total = (*a as u64) * (*b as u64) + (*slot as u64) + carry;
315                *slot = total as u32;
316                carry = total >> 32;
317            }
318            let mut k = i + other.mag.len();
319            while carry != 0 {
320                let total = mag[k] as u64 + carry;
321                mag[k] = total as u32;
322                carry = total >> 32;
323                k += 1;
324            }
325        }
326        bigint_trim(&mut mag);
327        BigInt {
328            negative: self.negative != other.negative,
329            mag,
330        }
331    }
332
333    /// Signed division, truncating toward zero, with the remainder.
334    ///
335    /// `None` for a zero divisor, which the caller turns into a `RangeError`.
336    pub fn div_rem(&self, other: &BigInt) -> Option<(BigInt, BigInt)> {
337        if other.is_zero() {
338            return None;
339        }
340        let (quotient, remainder) = div_rem_mag(&self.mag, &other.mag);
341        let mut quotient = quotient;
342        let mut remainder = remainder;
343        bigint_trim(&mut quotient);
344        bigint_trim(&mut remainder);
345        Some((
346            BigInt {
347                // Truncation toward zero, so the sign of the quotient is the product of the
348                // signs — that is what makes `-7n / 2n` equal `-3n`.
349                negative: (self.negative != other.negative) && !quotient.is_empty(),
350                mag: quotient,
351            },
352            BigInt {
353                negative: self.negative && !remainder.is_empty(),
354                mag: remainder,
355            },
356        ))
357    }
358
359    /// `self` raised to `exponent`, by repeated squaring.
360    pub fn pow(&self, exponent: &BigInt) -> Option<BigInt> {
361        if exponent.negative {
362            // A negative exponent on integers is `RangeError` — there is no fraction.
363            return None;
364        }
365        let mut exponent = exponent.to_i64()? as u64;
366        // Guard the allocation: the result needs `bits(self) * exponent` bits.
367        let bits = self.mag.len() as u64 * 32;
368        if bits.saturating_mul(exponent) > MAX_POW_BITS {
369            return None;
370        }
371        let mut base = self.clone();
372        let mut result = BigInt::one();
373        while exponent > 0 {
374            if exponent & 1 == 1 {
375                result = result.mul(&base);
376            }
377            exponent >>= 1;
378            if exponent > 0 {
379                base = base.mul(&base);
380            }
381        }
382        Some(result)
383    }
384
385    /// `self << bits`.
386    pub fn shl(&self, bits: u64) -> BigInt {
387        if self.is_zero() || bits == 0 {
388            return self.clone();
389        }
390        let words = (bits / 32) as usize;
391        let shift = (bits % 32) as u32;
392        let mut mag = vec![0u32; words];
393        if shift == 0 {
394            mag.extend_from_slice(&self.mag);
395        } else {
396            // Each word contributes its low bits to its own slot and its high bits to
397            // the next one, so the carry has to travel with the loop.
398            let mut carry = 0u32;
399            for word in &self.mag {
400                mag.push((*word << shift) | carry);
401                carry = *word >> (32 - shift);
402            }
403            if carry != 0 {
404                mag.push(carry);
405            }
406        }
407        bigint_trim(&mut mag);
408        BigInt {
409            negative: self.negative,
410            mag,
411        }
412    }
413
414    /// `self >> bits`, arithmetic — the same as `floor(self / 2^bits)`.
415    pub fn shr(&self, bits: u64) -> BigInt {
416        if bits == 0 {
417            return self.clone();
418        }
419        let words = (bits / 32) as usize;
420        let shift = (bits % 32) as u32;
421        if words >= self.mag.len() {
422            // Everything is shifted out; the floor of a negative value is `-1`.
423            return if self.negative {
424                BigInt::from_i64(-1)
425            } else {
426                BigInt::zero()
427            };
428        }
429        let mut mag = self.mag[words..].to_vec();
430        let mut lost_bit = false;
431        if shift != 0 {
432            for index in 0..mag.len() {
433                let next = mag.get(index + 1).copied().unwrap_or(0);
434                if index == 0 && mag[0] & ((1 << shift) - 1) != 0 {
435                    lost_bit = true;
436                }
437                mag[index] = (mag[index] >> shift) | (next << (32 - shift));
438            }
439        }
440        // The words that were dropped entirely also count as shifted-out bits.
441        if self.mag[..words].iter().any(|word| *word != 0) {
442            lost_bit = true;
443        }
444        bigint_trim(&mut mag);
445        let mut result = BigInt {
446            negative: self.negative && !mag.is_empty(),
447            mag,
448        };
449        // Truncating a negative value rounds *toward zero*, so the floor needs one more
450        // step down whenever a bit was discarded.
451        if self.negative && lost_bit {
452            result = result.sub(&BigInt::one());
453        }
454        result
455    }
456
457    /// `self & other`, on the infinite two's-complement form.
458    pub fn bitand(&self, other: &BigInt) -> BigInt {
459        self.bitwise(other, |a, b| a & b)
460    }
461
462    /// `self | other`.
463    pub fn bitor(&self, other: &BigInt) -> BigInt {
464        self.bitwise(other, |a, b| a | b)
465    }
466
467    /// `self ^ other`.
468    pub fn bitxor(&self, other: &BigInt) -> BigInt {
469        self.bitwise(other, |a, b| a ^ b)
470    }
471
472    /// `~self`.
473    pub fn bitnot(&self) -> BigInt {
474        // `~x` is `-x - 1` for every integer, which needs no width at all.
475        self.negate().sub(&BigInt::one())
476    }
477
478    fn bitwise(&self, other: &BigInt, op: impl Fn(u32, u32) -> u32) -> BigInt {
479        // One extra word so the sign extension is materialised rather than inferred.
480        let width = self.mag.len().max(other.mag.len()) + 1;
481        let left = self.twos_complement(width);
482        let right = other.twos_complement(width);
483        let words: Vec<u32> = left
484            .iter()
485            .zip(right.iter())
486            .map(|(a, b)| op(*a, *b))
487            .collect();
488        BigInt::from_twos_complement(words)
489    }
490
491    /// The low `width` words of the two's-complement form.
492    fn twos_complement(&self, width: usize) -> Vec<u32> {
493        let mut words = vec![0u32; width];
494        for (index, word) in self.mag.iter().enumerate().take(width) {
495            words[index] = *word;
496        }
497        if self.negative {
498            for word in words.iter_mut() {
499                *word = !*word;
500            }
501            let mut carry = 1u64;
502            for word in words.iter_mut() {
503                let total = *word as u64 + carry;
504                *word = total as u32;
505                carry = total >> 32;
506            }
507        }
508        words
509    }
510
511    /// Interpret `words` as two's complement, whose top bit decides the sign.
512    fn from_twos_complement(mut words: Vec<u32>) -> BigInt {
513        let negative = words.last().is_some_and(|word| word & 0x8000_0000 != 0);
514        if negative {
515            for word in words.iter_mut() {
516                *word = !*word;
517            }
518            let mut carry = 1u64;
519            for word in words.iter_mut() {
520                let total = *word as u64 + carry;
521                *word = total as u32;
522                carry = total >> 32;
523            }
524        }
525        bigint_trim(&mut words);
526        BigInt {
527            negative: negative && !words.is_empty(),
528            mag: words,
529        }
530    }
531
532    /// `BigInt.asUintN(bits, self)`.
533    pub fn as_uint_n(&self, bits: u64) -> BigInt {
534        if bits == 0 {
535            return BigInt::zero();
536        }
537        let mask_words = bits.div_ceil(32) as usize;
538        let mut words = self.twos_complement(mask_words);
539        let spare = (mask_words as u64 * 32 - bits) as u32;
540        if spare > 0
541            && let Some(last) = words.last_mut()
542        {
543            *last &= u32::MAX >> spare;
544        }
545        bigint_trim(&mut words);
546        BigInt {
547            negative: false,
548            mag: words,
549        }
550    }
551
552    /// `BigInt.asIntN(bits, self)`.
553    pub fn as_int_n(&self, bits: u64) -> BigInt {
554        if bits == 0 {
555            return BigInt::zero();
556        }
557        let mask_words = bits.div_ceil(32) as usize;
558        let mut words = self.twos_complement(mask_words);
559        let spare = (mask_words as u64 * 32 - bits) as u32;
560        if spare > 0
561            && let Some(last) = words.last_mut()
562        {
563            // Keep the bit below the spare ones as the sign, then re-extend.
564            *last &= u32::MAX >> spare;
565        }
566        let negative = words
567            .last()
568            .is_some_and(|word| word & (1 << ((bits - 1) % 32)) != 0);
569        if negative && spare > 0 {
570            if let Some(last) = words.last_mut() {
571                *last |= u32::MAX << (32 - spare);
572            }
573        }
574        BigInt::from_twos_complement(words)
575    }
576
577    /// The decimal text, which is what `toString()` and the printer need.
578    pub fn to_decimal_string(&self) -> String {
579        self.to_radix_string(10)
580    }
581
582    /// The text in `radix`.
583    pub fn to_radix_string(&self, radix: u32) -> String {
584        if self.is_zero() {
585            return "0".to_string();
586        }
587        let radix = radix.clamp(2, 36);
588        let mut digits = Vec::new();
589        let mut magnitude = self.mag.clone();
590        // Peel off nine decimal digits at a time, which is the largest power of ten that
591        // fits a `u32` and therefore the cheapest chunk the long division can take.
592        let chunk = 1_000_000_000u32;
593        if radix == 10 {
594            while !magnitude.is_empty() {
595                let remainder = div_rem_small(&mut magnitude, chunk);
596                if magnitude.is_empty() {
597                    digits.push(remainder.to_string());
598                } else {
599                    digits.push(format!("{remainder:09}"));
600                }
601            }
602        } else {
603            while !magnitude.is_empty() {
604                let remainder = div_rem_small(&mut magnitude, radix);
605                digits.push(
606                    char::from_digit(remainder, radix)
607                        .unwrap_or('0')
608                        .to_string(),
609                );
610            }
611        }
612        digits.reverse();
613        let body = digits.concat();
614        if self.negative {
615            format!("-{body}")
616        } else {
617            body
618        }
619    }
620}
621
622impl js_gc::Trace for BigInt {
623    /// Nothing in a bignum is a GC value: it is a sign and machine words.
624    fn trace(&self, _tracer: &mut js_gc::Tracer) {}
625}
626
627impl fmt::Display for BigInt {
628    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629        write!(f, "{}", self.to_decimal_string())
630    }
631}
632
633impl PartialOrd for BigInt {
634    fn partial_cmp(&self, other: &BigInt) -> Option<std::cmp::Ordering> {
635        Some(self.cmp(other))
636    }
637}
638
639impl Ord for BigInt {
640    fn cmp(&self, other: &BigInt) -> std::cmp::Ordering {
641        use std::cmp::Ordering;
642        match (self.negative, other.negative) {
643            (false, true) => Ordering::Greater,
644            (true, false) => Ordering::Less,
645            (false, false) => cmp_mag(&self.mag, &other.mag),
646            (true, true) => cmp_mag(&other.mag, &self.mag),
647        }
648    }
649}
650
651/// Drop trailing zero words, so every value has one representation.
652fn bigint_trim(words: &mut Vec<u32>) {
653    while words.last() == Some(&0) {
654        words.pop();
655    }
656}
657
658fn cmp_mag(a: &[u32], b: &[u32]) -> std::cmp::Ordering {
659    if a.len() != b.len() {
660        return a.len().cmp(&b.len());
661    }
662    for index in (0..a.len()).rev() {
663        if a[index] != b[index] {
664            return a[index].cmp(&b[index]);
665        }
666    }
667    std::cmp::Ordering::Equal
668}
669
670fn add_mag(a: &[u32], b: &[u32]) -> Vec<u32> {
671    let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };
672    let mut out = Vec::with_capacity(long.len() + 1);
673    let mut carry = 0u64;
674    for (index, word) in long.iter().enumerate() {
675        let total = *word as u64 + short.get(index).copied().unwrap_or(0) as u64 + carry;
676        out.push(total as u32);
677        carry = total >> 32;
678    }
679    if carry != 0 {
680        out.push(carry as u32);
681    }
682    out
683}
684
685/// `a - b`, requiring `a >= b`.
686fn sub_mag(a: &[u32], b: &[u32]) -> Vec<u32> {
687    let mut out = Vec::with_capacity(a.len());
688    let mut borrow = 0i64;
689    for (index, word) in a.iter().enumerate() {
690        let total = *word as i64 - b.get(index).copied().unwrap_or(0) as i64 - borrow;
691        if total < 0 {
692            out.push((total + (1i64 << 32)) as u32);
693            borrow = 1;
694        } else {
695            out.push(total as u32);
696            borrow = 0;
697        }
698    }
699    out
700}
701
702/// Divide the magnitude by a small value, returning the remainder.
703fn div_rem_small(words: &mut Vec<u32>, divisor: u32) -> u32 {
704    let mut remainder = 0u64;
705    for index in (0..words.len()).rev() {
706        let total = (remainder << 32) | words[index] as u64;
707        words[index] = (total / divisor as u64) as u32;
708        remainder = total % divisor as u64;
709    }
710    bigint_trim(words);
711    remainder as u32
712}
713
714/// Binary long division on the magnitudes.
715///
716/// Simple and obviously correct rather than fast: shift the divisor up to the dividend's
717/// bit length, then subtract wherever it fits, which is the textbook restoring division.
718fn div_rem_mag(a: &[u32], b: &[u32]) -> (Vec<u32>, Vec<u32>) {
719    let mut remainder = Vec::new();
720    let mut quotient = vec![0u32; a.len()];
721    let bits = a.len() as u64 * 32;
722    for bit in (0..bits).rev() {
723        // `remainder = remainder << 1 | bit_of_a`
724        let mut carry = (a[(bit / 32) as usize] >> (bit % 32)) & 1;
725        for word in remainder.iter_mut() {
726            let next = *word >> 31;
727            *word = (*word << 1) | carry;
728            carry = next;
729        }
730        if carry != 0 {
731            remainder.push(carry);
732        }
733        bigint_trim(&mut remainder);
734        if cmp_mag(&remainder, b) != std::cmp::Ordering::Less {
735            remainder = sub_mag(&remainder, b);
736            bigint_trim(&mut remainder);
737            quotient[(bit / 32) as usize] |= 1 << (bit % 32);
738        }
739    }
740    (quotient, remainder)
741}
742
743#[cfg(test)]
744mod tests {
745    use super::BigInt;
746
747    fn big(value: i64) -> BigInt {
748        BigInt::from_i64(value)
749    }
750
751    fn parsed(text: &str) -> BigInt {
752        BigInt::from_string(text).expect("parses")
753    }
754
755    #[test]
756    fn decimal_round_trips() {
757        for text in [
758            "0",
759            "1",
760            "-1",
761            "123456789012345678901234567890",
762            "-999999999999999999999999999999",
763        ] {
764            assert_eq!(parsed(text).to_decimal_string(), text);
765        }
766        // `-0n` is `0n`, so the sign never appears on a zero.
767        assert_eq!(parsed("-0").to_decimal_string(), "0");
768    }
769
770    #[test]
771    fn arithmetic_matches_i64_for_small_values() {
772        let cases = [
773            (7i64, 3i64),
774            (-7, 3),
775            (7, -3),
776            (-7, -3),
777            (0, 5),
778            (123456, -789),
779        ];
780        for (a, b) in cases {
781            assert_eq!(big(a).add(&big(b)).to_i64(), Some(a + b), "{a} + {b}");
782            assert_eq!(big(a).sub(&big(b)).to_i64(), Some(a - b), "{a} - {b}");
783            assert_eq!(big(a).mul(&big(b)).to_i64(), Some(a * b), "{a} * {b}");
784            // Division truncates toward zero, like the language's `BigInt` division.
785            assert_eq!(
786                big(a).div_rem(&big(b)).unwrap().0.to_i64(),
787                Some(a / b),
788                "{a} / {b}"
789            );
790            assert_eq!(
791                big(a).div_rem(&big(b)).unwrap().1.to_i64(),
792                Some(a % b),
793                "{a} % {b}"
794            );
795        }
796    }
797
798    #[test]
799    fn division_is_exact_on_large_values() {
800        // `2^1000 - (2^1000 - 1)` is 1: the arithmetic has to be exact at 1000 bits.
801        let big_power = big(2).pow(&big(1000)).unwrap();
802        let difference = big_power.sub(&big_power.sub(&big(1)));
803        assert_eq!(difference.to_decimal_string(), "1");
804        // …and dividing it back out recovers the operand.
805        let (quotient, remainder) = big_power.div_rem(&big_power.sub(&big(1))).unwrap();
806        assert_eq!(quotient.to_decimal_string(), "1");
807        assert_eq!(remainder.to_decimal_string(), "1");
808    }
809
810    #[test]
811    fn shifting_is_arithmetic() {
812        assert_eq!(
813            big(1).shl(128).to_decimal_string(),
814            "340282366920938463463374607431768211456"
815        );
816        assert_eq!(big(1).shl(128).shr(128).to_decimal_string(), "1");
817        // `-1n >> 1n` is `-1n`: the shift is a floor, not a truncation.
818        assert_eq!(big(-1).shr(1).to_decimal_string(), "-1");
819        assert_eq!(big(-2).shr(1).to_decimal_string(), "-1");
820        assert_eq!(big(-3).shr(1).to_decimal_string(), "-2");
821        assert_eq!(big(-1).shl(4).to_decimal_string(), "-16");
822    }
823
824    #[test]
825    fn bitwise_uses_twos_complement() {
826        // `-1n` is all ones, so `&` gives the other operand back and `|` gives `-1n`.
827        assert_eq!(big(-1).bitand(&big(3)).to_i64(), Some(3));
828        assert_eq!(big(-1).bitor(&big(3)).to_i64(), Some(-1));
829        assert_eq!(big(-1).bitxor(&big(3)).to_i64(), Some(-4));
830        // `~x` is `-x - 1`.
831        assert_eq!(big(0).bitnot().to_i64(), Some(-1));
832        assert_eq!(big(-1).bitnot().to_i64(), Some(0));
833        assert_eq!(big(12).bitand(&big(10)).to_i64(), Some(8));
834        assert_eq!(big(12).bitor(&big(10)).to_i64(), Some(14));
835        assert_eq!(big(12).bitxor(&big(10)).to_i64(), Some(6));
836        // A value wider than one word keeps working.
837        let wide = big(1).shl(64);
838        assert_eq!(
839            wide.bitand(&wide).to_decimal_string(),
840            "18446744073709551616"
841        );
842    }
843
844    #[test]
845    fn as_int_n_and_as_uint_n_wrap() {
846        assert_eq!(big(255).as_uint_n(8).to_i64(), Some(255));
847        assert_eq!(big(256).as_uint_n(8).to_i64(), Some(0));
848        assert_eq!(big(-1).as_uint_n(8).to_i64(), Some(255));
849        assert_eq!(big(128).as_int_n(8).to_i64(), Some(-128));
850        assert_eq!(big(127).as_int_n(8).to_i64(), Some(127));
851        assert_eq!(big(-129).as_int_n(8).to_i64(), Some(127));
852        assert_eq!(big(5).as_int_n(0).to_i64(), Some(0));
853    }
854
855    #[test]
856    fn ordering_is_signed() {
857        assert!(big(-2) < big(1));
858        assert!(big(-2) < big(-1));
859        assert!(big(2) > big(1));
860        assert_eq!(big(0), big(-0));
861        let huge = parsed("100000000000000000000000");
862        assert!(huge > big(i64::MAX));
863        assert!(huge.negate() < big(i64::MIN + 1));
864    }
865
866    #[test]
867    fn pow_guards_absurd_exponents() {
868        assert!(
869            big(2).pow(&big(-1)).is_none(),
870            "a negative exponent has no integer result"
871        );
872        assert!(
873            big(2).pow(&big(1_000_000_000)).is_none(),
874            "the result would not fit memory"
875        );
876        assert_eq!(big(2).pow(&big(10)).unwrap().to_i64(), Some(1024));
877        assert_eq!(big(0).pow(&big(0)).unwrap().to_i64(), Some(1));
878    }
879}