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 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 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 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 pub fn from_u64(value: u64) -> BigInt {
147 BigInt::from_u64_magnitude(value)
148 }
149
150 pub fn to_u64_wrapping(&self) -> u64 {
156 let low = self.mag.first().copied().unwrap_or(0) as u64;
157 let high = self.mag.get(1).copied().unwrap_or(0) as u64;
158 let magnitude = low | (high << 32);
159 if self.negative {
160 magnitude.wrapping_neg()
161 } else {
162 magnitude
163 }
164 }
165
166 pub fn to_i64_wrapping(&self) -> i64 {
168 self.to_u64_wrapping() as i64
169 }
170
171 pub fn from_radix(text: &str, radix: u32) -> Option<BigInt> {
176 if !(2..=36).contains(&radix) || text.is_empty() {
177 return None;
178 }
179 let mut result = BigInt::zero();
180 let multiplier = BigInt::from_i64(radix as i64);
181 for character in text.chars() {
182 let digit = character.to_digit(radix)?;
183 result = result.mul(&multiplier).add(&BigInt::from_i64(digit as i64));
184 }
185 Some(result)
186 }
187
188 pub fn from_string(text: &str) -> Option<BigInt> {
198 let text = text.trim();
199 if text.is_empty() {
200 return Some(BigInt::zero());
201 }
202 let (negative, body) = match text.strip_prefix('-') {
203 Some(rest) => (true, rest),
204 None => (false, text.strip_prefix('+').unwrap_or(text)),
205 };
206 let has_radix_prefix = body.starts_with("0x")
210 || body.starts_with("0X")
211 || body.starts_with("0o")
212 || body.starts_with("0O")
213 || body.starts_with("0b")
214 || body.starts_with("0B");
215 if has_radix_prefix && negative {
216 return None;
217 }
218 if has_radix_prefix && text.starts_with('+') {
219 return None;
220 }
221 let (radix, digits) =
222 if let Some(rest) = body.strip_prefix("0x").or(body.strip_prefix("0X")) {
223 (16, rest)
224 } else if let Some(rest) = body.strip_prefix("0o").or(body.strip_prefix("0O")) {
225 (8, rest)
226 } else if let Some(rest) = body.strip_prefix("0b").or(body.strip_prefix("0B")) {
227 (2, rest)
228 } else {
229 (10, body)
230 };
231 let value = BigInt::from_radix(digits, radix)?;
232 Some(if negative { value.negate() } else { value })
233 }
234
235 pub fn negate(&self) -> BigInt {
237 if self.is_zero() {
238 return BigInt::zero();
240 }
241 BigInt {
242 negative: !self.negative,
243 mag: self.mag.clone(),
244 }
245 }
246
247 pub fn abs(&self) -> BigInt {
249 BigInt {
250 negative: false,
251 mag: self.mag.clone(),
252 }
253 }
254
255 pub fn add(&self, other: &BigInt) -> BigInt {
257 if self.negative == other.negative {
258 let mut mag = add_mag(&self.mag, &other.mag);
259 bigint_trim(&mut mag);
260 return BigInt {
261 negative: self.negative && !mag.is_empty(),
262 mag,
263 };
264 }
265 match cmp_mag(&self.mag, &other.mag) {
268 std::cmp::Ordering::Equal => BigInt::zero(),
269 std::cmp::Ordering::Greater => {
270 let mut mag = sub_mag(&self.mag, &other.mag);
271 bigint_trim(&mut mag);
272 BigInt {
273 negative: self.negative,
274 mag,
275 }
276 }
277 std::cmp::Ordering::Less => {
278 let mut mag = sub_mag(&other.mag, &self.mag);
279 bigint_trim(&mut mag);
280 BigInt {
281 negative: other.negative,
282 mag,
283 }
284 }
285 }
286 }
287
288 pub fn sub(&self, other: &BigInt) -> BigInt {
290 self.add(&other.negate())
291 }
292
293 pub fn mul(&self, other: &BigInt) -> BigInt {
295 if self.is_zero() || other.is_zero() {
296 return BigInt::zero();
297 }
298 let mut mag = vec![0u32; self.mag.len() + other.mag.len()];
299 for (i, a) in self.mag.iter().enumerate() {
300 let mut carry = 0u64;
301 for (j, b) in other.mag.iter().enumerate() {
302 let slot = &mut mag[i + j];
303 let total = (*a as u64) * (*b as u64) + (*slot as u64) + carry;
304 *slot = total as u32;
305 carry = total >> 32;
306 }
307 let mut k = i + other.mag.len();
308 while carry != 0 {
309 let total = mag[k] as u64 + carry;
310 mag[k] = total as u32;
311 carry = total >> 32;
312 k += 1;
313 }
314 }
315 bigint_trim(&mut mag);
316 BigInt {
317 negative: self.negative != other.negative,
318 mag,
319 }
320 }
321
322 pub fn div_rem(&self, other: &BigInt) -> Option<(BigInt, BigInt)> {
326 if other.is_zero() {
327 return None;
328 }
329 let (quotient, remainder) = div_rem_mag(&self.mag, &other.mag);
330 let mut quotient = quotient;
331 let mut remainder = remainder;
332 bigint_trim(&mut quotient);
333 bigint_trim(&mut remainder);
334 Some((
335 BigInt {
336 negative: (self.negative != other.negative) && !quotient.is_empty(),
339 mag: quotient,
340 },
341 BigInt {
342 negative: self.negative && !remainder.is_empty(),
343 mag: remainder,
344 },
345 ))
346 }
347
348 pub fn pow(&self, exponent: &BigInt) -> Option<BigInt> {
350 if exponent.negative {
351 return None;
353 }
354 let mut exponent = exponent.to_i64()? as u64;
355 let bits = self.mag.len() as u64 * 32;
357 if bits.saturating_mul(exponent) > MAX_POW_BITS {
358 return None;
359 }
360 let mut base = self.clone();
361 let mut result = BigInt::one();
362 while exponent > 0 {
363 if exponent & 1 == 1 {
364 result = result.mul(&base);
365 }
366 exponent >>= 1;
367 if exponent > 0 {
368 base = base.mul(&base);
369 }
370 }
371 Some(result)
372 }
373
374 pub fn shl(&self, bits: u64) -> BigInt {
376 if self.is_zero() || bits == 0 {
377 return self.clone();
378 }
379 let words = (bits / 32) as usize;
380 let shift = (bits % 32) as u32;
381 let mut mag = vec![0u32; words];
382 if shift == 0 {
383 mag.extend_from_slice(&self.mag);
384 } else {
385 let mut carry = 0u32;
388 for word in &self.mag {
389 mag.push((*word << shift) | carry);
390 carry = *word >> (32 - shift);
391 }
392 if carry != 0 {
393 mag.push(carry);
394 }
395 }
396 bigint_trim(&mut mag);
397 BigInt {
398 negative: self.negative,
399 mag,
400 }
401 }
402
403 pub fn shr(&self, bits: u64) -> BigInt {
405 if bits == 0 {
406 return self.clone();
407 }
408 let words = (bits / 32) as usize;
409 let shift = (bits % 32) as u32;
410 if words >= self.mag.len() {
411 return if self.negative {
413 BigInt::from_i64(-1)
414 } else {
415 BigInt::zero()
416 };
417 }
418 let mut mag = self.mag[words..].to_vec();
419 let mut lost_bit = false;
420 if shift != 0 {
421 for index in 0..mag.len() {
422 let next = mag.get(index + 1).copied().unwrap_or(0);
423 if index == 0 && mag[0] & ((1 << shift) - 1) != 0 {
424 lost_bit = true;
425 }
426 mag[index] = (mag[index] >> shift) | (next << (32 - shift));
427 }
428 }
429 if self.mag[..words].iter().any(|word| *word != 0) {
431 lost_bit = true;
432 }
433 bigint_trim(&mut mag);
434 let mut result = BigInt {
435 negative: self.negative && !mag.is_empty(),
436 mag,
437 };
438 if self.negative && lost_bit {
441 result = result.sub(&BigInt::one());
442 }
443 result
444 }
445
446 pub fn bitand(&self, other: &BigInt) -> BigInt {
448 self.bitwise(other, |a, b| a & b)
449 }
450
451 pub fn bitor(&self, other: &BigInt) -> BigInt {
453 self.bitwise(other, |a, b| a | b)
454 }
455
456 pub fn bitxor(&self, other: &BigInt) -> BigInt {
458 self.bitwise(other, |a, b| a ^ b)
459 }
460
461 pub fn bitnot(&self) -> BigInt {
463 self.negate().sub(&BigInt::one())
465 }
466
467 fn bitwise(&self, other: &BigInt, op: impl Fn(u32, u32) -> u32) -> BigInt {
468 let width = self.mag.len().max(other.mag.len()) + 1;
470 let left = self.twos_complement(width);
471 let right = other.twos_complement(width);
472 let words: Vec<u32> = left
473 .iter()
474 .zip(right.iter())
475 .map(|(a, b)| op(*a, *b))
476 .collect();
477 BigInt::from_twos_complement(words)
478 }
479
480 fn twos_complement(&self, width: usize) -> Vec<u32> {
482 let mut words = vec![0u32; width];
483 for (index, word) in self.mag.iter().enumerate().take(width) {
484 words[index] = *word;
485 }
486 if self.negative {
487 for word in words.iter_mut() {
488 *word = !*word;
489 }
490 let mut carry = 1u64;
491 for word in words.iter_mut() {
492 let total = *word as u64 + carry;
493 *word = total as u32;
494 carry = total >> 32;
495 }
496 }
497 words
498 }
499
500 fn from_twos_complement(mut words: Vec<u32>) -> BigInt {
502 let negative = words.last().is_some_and(|word| word & 0x8000_0000 != 0);
503 if negative {
504 for word in words.iter_mut() {
505 *word = !*word;
506 }
507 let mut carry = 1u64;
508 for word in words.iter_mut() {
509 let total = *word as u64 + carry;
510 *word = total as u32;
511 carry = total >> 32;
512 }
513 }
514 bigint_trim(&mut words);
515 BigInt {
516 negative: negative && !words.is_empty(),
517 mag: words,
518 }
519 }
520
521 pub fn as_uint_n(&self, bits: u64) -> BigInt {
523 if bits == 0 {
524 return BigInt::zero();
525 }
526 let mask_words = bits.div_ceil(32) as usize;
527 let mut words = self.twos_complement(mask_words);
528 let spare = (mask_words as u64 * 32 - bits) as u32;
529 if spare > 0
530 && let Some(last) = words.last_mut()
531 {
532 *last &= u32::MAX >> spare;
533 }
534 bigint_trim(&mut words);
535 BigInt {
536 negative: false,
537 mag: words,
538 }
539 }
540
541 pub fn as_int_n(&self, bits: u64) -> BigInt {
543 if bits == 0 {
544 return BigInt::zero();
545 }
546 let mask_words = bits.div_ceil(32) as usize;
547 let mut words = self.twos_complement(mask_words);
548 let spare = (mask_words as u64 * 32 - bits) as u32;
549 if spare > 0
550 && let Some(last) = words.last_mut()
551 {
552 *last &= u32::MAX >> spare;
554 }
555 let negative = words
556 .last()
557 .is_some_and(|word| word & (1 << ((bits - 1) % 32)) != 0);
558 if negative && spare > 0 {
559 if let Some(last) = words.last_mut() {
560 *last |= u32::MAX << (32 - spare);
561 }
562 }
563 BigInt::from_twos_complement(words)
564 }
565
566 pub fn to_decimal_string(&self) -> String {
568 self.to_radix_string(10)
569 }
570
571 pub fn to_radix_string(&self, radix: u32) -> String {
573 if self.is_zero() {
574 return "0".to_string();
575 }
576 let radix = radix.clamp(2, 36);
577 let mut digits = Vec::new();
578 let mut magnitude = self.mag.clone();
579 let chunk = 1_000_000_000u32;
582 if radix == 10 {
583 while !magnitude.is_empty() {
584 let remainder = div_rem_small(&mut magnitude, chunk);
585 if magnitude.is_empty() {
586 digits.push(remainder.to_string());
587 } else {
588 digits.push(format!("{remainder:09}"));
589 }
590 }
591 } else {
592 while !magnitude.is_empty() {
593 let remainder = div_rem_small(&mut magnitude, radix);
594 digits.push(
595 char::from_digit(remainder, radix)
596 .unwrap_or('0')
597 .to_string(),
598 );
599 }
600 }
601 digits.reverse();
602 let body = digits.concat();
603 if self.negative {
604 format!("-{body}")
605 } else {
606 body
607 }
608 }
609}
610
611impl js_gc::Trace for BigInt {
612 fn trace(&self, _tracer: &mut js_gc::Tracer) {}
614}
615
616impl fmt::Display for BigInt {
617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618 write!(f, "{}", self.to_decimal_string())
619 }
620}
621
622impl PartialOrd for BigInt {
623 fn partial_cmp(&self, other: &BigInt) -> Option<std::cmp::Ordering> {
624 Some(self.cmp(other))
625 }
626}
627
628impl Ord for BigInt {
629 fn cmp(&self, other: &BigInt) -> std::cmp::Ordering {
630 use std::cmp::Ordering;
631 match (self.negative, other.negative) {
632 (false, true) => Ordering::Greater,
633 (true, false) => Ordering::Less,
634 (false, false) => cmp_mag(&self.mag, &other.mag),
635 (true, true) => cmp_mag(&other.mag, &self.mag),
636 }
637 }
638}
639
640fn bigint_trim(words: &mut Vec<u32>) {
642 while words.last() == Some(&0) {
643 words.pop();
644 }
645}
646
647fn cmp_mag(a: &[u32], b: &[u32]) -> std::cmp::Ordering {
648 if a.len() != b.len() {
649 return a.len().cmp(&b.len());
650 }
651 for index in (0..a.len()).rev() {
652 if a[index] != b[index] {
653 return a[index].cmp(&b[index]);
654 }
655 }
656 std::cmp::Ordering::Equal
657}
658
659fn add_mag(a: &[u32], b: &[u32]) -> Vec<u32> {
660 let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };
661 let mut out = Vec::with_capacity(long.len() + 1);
662 let mut carry = 0u64;
663 for (index, word) in long.iter().enumerate() {
664 let total = *word as u64 + short.get(index).copied().unwrap_or(0) as u64 + carry;
665 out.push(total as u32);
666 carry = total >> 32;
667 }
668 if carry != 0 {
669 out.push(carry as u32);
670 }
671 out
672}
673
674fn sub_mag(a: &[u32], b: &[u32]) -> Vec<u32> {
676 let mut out = Vec::with_capacity(a.len());
677 let mut borrow = 0i64;
678 for (index, word) in a.iter().enumerate() {
679 let total = *word as i64 - b.get(index).copied().unwrap_or(0) as i64 - borrow;
680 if total < 0 {
681 out.push((total + (1i64 << 32)) as u32);
682 borrow = 1;
683 } else {
684 out.push(total as u32);
685 borrow = 0;
686 }
687 }
688 out
689}
690
691fn div_rem_small(words: &mut Vec<u32>, divisor: u32) -> u32 {
693 let mut remainder = 0u64;
694 for index in (0..words.len()).rev() {
695 let total = (remainder << 32) | words[index] as u64;
696 words[index] = (total / divisor as u64) as u32;
697 remainder = total % divisor as u64;
698 }
699 bigint_trim(words);
700 remainder as u32
701}
702
703fn div_rem_mag(a: &[u32], b: &[u32]) -> (Vec<u32>, Vec<u32>) {
708 let mut remainder = Vec::new();
709 let mut quotient = vec![0u32; a.len()];
710 let bits = a.len() as u64 * 32;
711 for bit in (0..bits).rev() {
712 let mut carry = (a[(bit / 32) as usize] >> (bit % 32)) & 1;
714 for word in remainder.iter_mut() {
715 let next = *word >> 31;
716 *word = (*word << 1) | carry;
717 carry = next;
718 }
719 if carry != 0 {
720 remainder.push(carry);
721 }
722 bigint_trim(&mut remainder);
723 if cmp_mag(&remainder, b) != std::cmp::Ordering::Less {
724 remainder = sub_mag(&remainder, b);
725 bigint_trim(&mut remainder);
726 quotient[(bit / 32) as usize] |= 1 << (bit % 32);
727 }
728 }
729 (quotient, remainder)
730}
731
732#[cfg(test)]
733mod tests {
734 use super::BigInt;
735
736 fn big(value: i64) -> BigInt {
737 BigInt::from_i64(value)
738 }
739
740 fn parsed(text: &str) -> BigInt {
741 BigInt::from_string(text).expect("parses")
742 }
743
744 #[test]
745 fn decimal_round_trips() {
746 for text in [
747 "0",
748 "1",
749 "-1",
750 "123456789012345678901234567890",
751 "-999999999999999999999999999999",
752 ] {
753 assert_eq!(parsed(text).to_decimal_string(), text);
754 }
755 assert_eq!(parsed("-0").to_decimal_string(), "0");
757 }
758
759 #[test]
760 fn arithmetic_matches_i64_for_small_values() {
761 let cases = [
762 (7i64, 3i64),
763 (-7, 3),
764 (7, -3),
765 (-7, -3),
766 (0, 5),
767 (123456, -789),
768 ];
769 for (a, b) in cases {
770 assert_eq!(big(a).add(&big(b)).to_i64(), Some(a + b), "{a} + {b}");
771 assert_eq!(big(a).sub(&big(b)).to_i64(), Some(a - b), "{a} - {b}");
772 assert_eq!(big(a).mul(&big(b)).to_i64(), Some(a * b), "{a} * {b}");
773 assert_eq!(
775 big(a).div_rem(&big(b)).unwrap().0.to_i64(),
776 Some(a / b),
777 "{a} / {b}"
778 );
779 assert_eq!(
780 big(a).div_rem(&big(b)).unwrap().1.to_i64(),
781 Some(a % b),
782 "{a} % {b}"
783 );
784 }
785 }
786
787 #[test]
788 fn division_is_exact_on_large_values() {
789 let big_power = big(2).pow(&big(1000)).unwrap();
791 let difference = big_power.sub(&big_power.sub(&big(1)));
792 assert_eq!(difference.to_decimal_string(), "1");
793 let (quotient, remainder) = big_power.div_rem(&big_power.sub(&big(1))).unwrap();
795 assert_eq!(quotient.to_decimal_string(), "1");
796 assert_eq!(remainder.to_decimal_string(), "1");
797 }
798
799 #[test]
800 fn shifting_is_arithmetic() {
801 assert_eq!(
802 big(1).shl(128).to_decimal_string(),
803 "340282366920938463463374607431768211456"
804 );
805 assert_eq!(big(1).shl(128).shr(128).to_decimal_string(), "1");
806 assert_eq!(big(-1).shr(1).to_decimal_string(), "-1");
808 assert_eq!(big(-2).shr(1).to_decimal_string(), "-1");
809 assert_eq!(big(-3).shr(1).to_decimal_string(), "-2");
810 assert_eq!(big(-1).shl(4).to_decimal_string(), "-16");
811 }
812
813 #[test]
814 fn bitwise_uses_twos_complement() {
815 assert_eq!(big(-1).bitand(&big(3)).to_i64(), Some(3));
817 assert_eq!(big(-1).bitor(&big(3)).to_i64(), Some(-1));
818 assert_eq!(big(-1).bitxor(&big(3)).to_i64(), Some(-4));
819 assert_eq!(big(0).bitnot().to_i64(), Some(-1));
821 assert_eq!(big(-1).bitnot().to_i64(), Some(0));
822 assert_eq!(big(12).bitand(&big(10)).to_i64(), Some(8));
823 assert_eq!(big(12).bitor(&big(10)).to_i64(), Some(14));
824 assert_eq!(big(12).bitxor(&big(10)).to_i64(), Some(6));
825 let wide = big(1).shl(64);
827 assert_eq!(
828 wide.bitand(&wide).to_decimal_string(),
829 "18446744073709551616"
830 );
831 }
832
833 #[test]
834 fn as_int_n_and_as_uint_n_wrap() {
835 assert_eq!(big(255).as_uint_n(8).to_i64(), Some(255));
836 assert_eq!(big(256).as_uint_n(8).to_i64(), Some(0));
837 assert_eq!(big(-1).as_uint_n(8).to_i64(), Some(255));
838 assert_eq!(big(128).as_int_n(8).to_i64(), Some(-128));
839 assert_eq!(big(127).as_int_n(8).to_i64(), Some(127));
840 assert_eq!(big(-129).as_int_n(8).to_i64(), Some(127));
841 assert_eq!(big(5).as_int_n(0).to_i64(), Some(0));
842 }
843
844 #[test]
845 fn ordering_is_signed() {
846 assert!(big(-2) < big(1));
847 assert!(big(-2) < big(-1));
848 assert!(big(2) > big(1));
849 assert_eq!(big(0), big(-0));
850 let huge = parsed("100000000000000000000000");
851 assert!(huge > big(i64::MAX));
852 assert!(huge.negate() < big(i64::MIN + 1));
853 }
854
855 #[test]
856 fn pow_guards_absurd_exponents() {
857 assert!(
858 big(2).pow(&big(-1)).is_none(),
859 "a negative exponent has no integer result"
860 );
861 assert!(
862 big(2).pow(&big(1_000_000_000)).is_none(),
863 "the result would not fit memory"
864 );
865 assert_eq!(big(2).pow(&big(10)).unwrap().to_i64(), Some(1024));
866 assert_eq!(big(0).pow(&big(0)).unwrap().to_i64(), Some(1));
867 }
868}