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