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