1use std::fmt;
27
28const MAX_POW_BITS: u64 = 1 << 24;
31
32#[derive(Clone, PartialEq, Eq, Debug)]
34pub struct BigInt {
35 negative: bool,
37 mag: Vec<u32>,
39}
40
41impl BigInt {
42 pub fn zero() -> BigInt {
44 BigInt {
45 negative: false,
46 mag: Vec::new(),
47 }
48 }
49
50 pub fn one() -> BigInt {
52 BigInt::from_i64(1)
53 }
54
55 pub fn from_i64(value: i64) -> BigInt {
57 let negative = value < 0;
58 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 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 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 pub fn is_zero(&self) -> bool {
102 self.mag.is_empty()
103 }
104
105 pub fn is_one(&self) -> bool {
107 !self.negative && self.mag.len() == 1 && self.mag[0] == 1
108 }
109
110 pub fn is_negative(&self) -> bool {
112 self.negative
113 }
114
115 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 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 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 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 pub fn from_u64(value: u64) -> BigInt {
158 BigInt::from_u64_magnitude(value)
159 }
160
161 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 pub fn to_i64_wrapping(&self) -> i64 {
179 self.to_u64_wrapping() as i64
180 }
181
182 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 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 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 pub fn negate(&self) -> BigInt {
248 if self.is_zero() {
249 return BigInt::zero();
251 }
252 BigInt {
253 negative: !self.negative,
254 mag: self.mag.clone(),
255 }
256 }
257
258 pub fn abs(&self) -> BigInt {
260 BigInt {
261 negative: false,
262 mag: self.mag.clone(),
263 }
264 }
265
266 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 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 pub fn sub(&self, other: &BigInt) -> BigInt {
301 self.add(&other.negate())
302 }
303
304 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 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 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 pub fn pow(&self, exponent: &BigInt) -> Option<BigInt> {
361 if exponent.negative {
362 return None;
364 }
365 let mut exponent = exponent.to_i64()? as u64;
366 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 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 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 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 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 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 if self.negative && lost_bit {
452 result = result.sub(&BigInt::one());
453 }
454 result
455 }
456
457 pub fn bitand(&self, other: &BigInt) -> BigInt {
459 self.bitwise(other, |a, b| a & b)
460 }
461
462 pub fn bitor(&self, other: &BigInt) -> BigInt {
464 self.bitwise(other, |a, b| a | b)
465 }
466
467 pub fn bitxor(&self, other: &BigInt) -> BigInt {
469 self.bitwise(other, |a, b| a ^ b)
470 }
471
472 pub fn bitnot(&self) -> BigInt {
474 self.negate().sub(&BigInt::one())
476 }
477
478 fn bitwise(&self, other: &BigInt, op: impl Fn(u32, u32) -> u32) -> BigInt {
479 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 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 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 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 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 *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 pub fn to_decimal_string(&self) -> String {
579 self.to_radix_string(10)
580 }
581
582 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 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 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
651fn 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
685fn 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
702fn 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
714fn 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 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 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 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 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 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 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 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 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 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}