1use alloc::string::String;
9use alloc::vec::Vec;
10use core::cmp::Ordering;
11
12#[derive(Clone, PartialEq, Eq)]
14pub struct BigInt {
15 negative: bool,
17 limbs: Vec<u32>,
19}
20
21impl BigInt {
22 pub fn zero() -> Self {
24 BigInt {
25 negative: false,
26 limbs: Vec::new(),
27 }
28 }
29
30 pub fn is_zero(&self) -> bool {
32 self.limbs.is_empty()
33 }
34
35 fn normalize(mut self) -> Self {
37 while let Some(&last) = self.limbs.last() {
38 if last == 0 {
39 self.limbs.pop();
40 } else {
41 break;
42 }
43 }
44 if self.limbs.is_empty() {
45 self.negative = false;
46 }
47 self
48 }
49
50 pub fn from_i64(mut v: i64) -> Self {
52 if v == 0 {
53 return BigInt::zero();
54 }
55 let negative = v < 0;
56 let mut mag = if negative {
58 (v as i128).unsigned_abs()
59 } else {
60 v as u128
61 };
62 let _ = &mut v;
63 let mut limbs = Vec::new();
64 while mag > 0 {
65 limbs.push((mag & 0xFFFF_FFFF) as u32);
66 mag >>= 32;
67 }
68 BigInt { negative, limbs }.normalize()
69 }
70
71 pub fn from_u64(v: u64) -> Self {
73 if v == 0 {
74 return BigInt::zero();
75 }
76 let mut mag = v;
77 let mut limbs = Vec::new();
78 while mag > 0 {
79 limbs.push((mag & 0xFFFF_FFFF) as u32);
80 mag >>= 32;
81 }
82 BigInt { negative: false, limbs }.normalize()
83 }
84
85 pub fn from_f64(v: f64) -> Option<Self> {
87 if !v.is_finite() {
88 return None;
89 }
90 if libm::trunc(v) != v {
91 return None;
92 }
93 if v == 0.0 {
94 return Some(BigInt::zero());
95 }
96 let negative = v < 0.0;
97 let mut mag = libm::fabs(v);
98 let mut limbs = Vec::new();
101 let base = 4294967296.0_f64; while mag >= 1.0 {
103 let rem = mag - libm::floor(mag / base) * base;
104 limbs.push(rem as u32);
105 mag = libm::floor(mag / base);
106 }
107 Some(BigInt { negative, limbs }.normalize())
108 }
109
110 pub fn parse_decimal(s: &str) -> Option<Self> {
112 let t = s.trim();
113 if t.is_empty() {
114 return Some(BigInt::zero());
115 }
116 let (negative, digits) = match t.strip_prefix('-') {
117 Some(rest) => (true, rest),
118 None => (false, t.strip_prefix('+').unwrap_or(t)),
119 };
120 if digits.is_empty() {
121 return None;
122 }
123 let mut acc = BigInt::zero();
124 let ten = BigInt::from_i64(10);
125 for ch in digits.chars() {
126 if ch == '_' {
127 continue;
128 }
129 let d = ch.to_digit(10)?;
130 acc = acc.mul(&ten).add(&BigInt::from_i64(d as i64));
131 }
132 acc.negative = negative;
133 Some(acc.normalize())
134 }
135
136 pub fn parse_js_string(s: &str) -> Option<Self> {
138 let t = s.trim_matches(|c: char| {
139 c.is_ascii_whitespace()
140 || matches!(
141 c,
142 '\u{000B}'
143 | '\u{000C}'
144 | '\u{00A0}'
145 | '\u{1680}'
146 | '\u{2000}'..='\u{200A}'
147 | '\u{2028}'
148 | '\u{2029}'
149 | '\u{202F}'
150 | '\u{205F}'
151 | '\u{3000}'
152 | '\u{FEFF}'
153 )
154 });
155 if t.is_empty() {
156 return Some(BigInt::zero());
157 }
158 if let Some(h) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) {
159 return Self::parse_radix_strict(h, 16);
160 }
161 if let Some(o) = t.strip_prefix("0o").or_else(|| t.strip_prefix("0O")) {
162 return Self::parse_radix_strict(o, 8);
163 }
164 if let Some(b) = t.strip_prefix("0b").or_else(|| t.strip_prefix("0B")) {
165 return Self::parse_radix_strict(b, 2);
166 }
167 let (neg, digits) = match t.strip_prefix('-') {
168 Some(r) => (true, r),
169 None => (false, t.strip_prefix('+').unwrap_or(t)),
170 };
171 Self::parse_radix_strict(digits, 10).map(|mut v| {
172 if neg {
173 v.negative = !v.negative;
174 }
175 v.normalize()
176 })
177 }
178
179 fn parse_radix_strict(digits: &str, radix: u32) -> Option<Self> {
180 if digits.is_empty() {
181 return None;
182 }
183 let mut acc = BigInt::zero();
184 let base = BigInt::from_i64(radix as i64);
185 for ch in digits.chars() {
186 let d = ch.to_digit(radix)?;
187 acc = acc.mul(&base).add(&BigInt::from_i64(d as i64));
188 }
189 Some(acc)
190 }
191
192 pub fn parse_str(s: &str) -> Option<Self> {
194 let t = s.trim();
195 let (neg, body) = match t.strip_prefix('-') {
196 Some(r) => (true, r),
197 None => (false, t.strip_prefix('+').unwrap_or(t)),
198 };
199 let parsed = if let Some(h) = body.strip_prefix("0x").or_else(|| body.strip_prefix("0X")) {
200 Self::parse_radix(h, 16)
201 } else if let Some(o) = body.strip_prefix("0o").or_else(|| body.strip_prefix("0O")) {
202 Self::parse_radix(o, 8)
203 } else if let Some(b) = body.strip_prefix("0b").or_else(|| body.strip_prefix("0B")) {
204 Self::parse_radix(b, 2)
205 } else {
206 Self::parse_decimal(body)
207 };
208 parsed.map(|mut v| {
209 if neg {
210 v.negative = !v.negative;
211 }
212 v.normalize()
213 })
214 }
215
216 fn parse_radix(digits: &str, radix: u32) -> Option<Self> {
218 if digits.is_empty() {
219 return None;
220 }
221 let mut acc = BigInt::zero();
222 let base = BigInt::from_i64(radix as i64);
223 for ch in digits.chars() {
224 if ch == '_' {
225 continue;
226 }
227 let d = ch.to_digit(radix)?;
228 acc = acc.mul(&base).add(&BigInt::from_i64(d as i64));
229 }
230 Some(acc)
231 }
232
233 fn cmp_magnitude(&self, other: &Self) -> Ordering {
235 if self.limbs.len() != other.limbs.len() {
236 return self.limbs.len().cmp(&other.limbs.len());
237 }
238 for i in (0..self.limbs.len()).rev() {
240 if self.limbs[i] != other.limbs[i] {
241 return self.limbs[i].cmp(&other.limbs[i]);
242 }
243 }
244 Ordering::Equal
245 }
246
247 #[allow(clippy::should_implement_trait)]
249 pub fn cmp(&self, other: &Self) -> Ordering {
250 match (self.negative, other.negative) {
251 (false, true) => Ordering::Greater,
252 (true, false) => Ordering::Less,
253 (false, false) => self.cmp_magnitude(other),
254 (true, true) => other.cmp_magnitude(self),
255 }
256 }
257
258 fn add_magnitude(a: &[u32], b: &[u32]) -> Vec<u32> {
260 let mut out = Vec::with_capacity(a.len().max(b.len()) + 1);
261 let mut carry: u64 = 0;
262 let n = a.len().max(b.len());
263 for i in 0..n {
264 let av = *a.get(i).unwrap_or(&0) as u64;
265 let bv = *b.get(i).unwrap_or(&0) as u64;
266 let sum = av + bv + carry;
267 out.push((sum & 0xFFFF_FFFF) as u32);
268 carry = sum >> 32;
269 }
270 if carry > 0 {
271 out.push(carry as u32);
272 }
273 out
274 }
275
276 fn sub_magnitude(a: &[u32], b: &[u32]) -> Vec<u32> {
278 let mut out = Vec::with_capacity(a.len());
279 let mut borrow: i64 = 0;
280 for (i, &av_u) in a.iter().enumerate() {
281 let av = av_u as i64;
282 let bv = *b.get(i).unwrap_or(&0) as i64;
283 let mut diff = av - bv - borrow;
284 if diff < 0 {
285 diff += 1 << 32;
286 borrow = 1;
287 } else {
288 borrow = 0;
289 }
290 out.push((diff & 0xFFFF_FFFF) as u32);
291 }
292 out
293 }
294
295 pub fn add(&self, other: &Self) -> Self {
297 if self.negative == other.negative {
298 BigInt {
300 negative: self.negative,
301 limbs: Self::add_magnitude(&self.limbs, &other.limbs),
302 }
303 .normalize()
304 } else {
305 match self.cmp_magnitude(other) {
307 Ordering::Equal => BigInt::zero(),
308 Ordering::Greater => BigInt {
309 negative: self.negative,
310 limbs: Self::sub_magnitude(&self.limbs, &other.limbs),
311 }
312 .normalize(),
313 Ordering::Less => BigInt {
314 negative: other.negative,
315 limbs: Self::sub_magnitude(&other.limbs, &self.limbs),
316 }
317 .normalize(),
318 }
319 }
320 }
321
322 pub fn sub(&self, other: &Self) -> Self {
324 let neg_other = BigInt {
326 negative: !other.negative,
327 limbs: other.limbs.clone(),
328 }
329 .normalize();
330 self.add(&neg_other)
331 }
332
333 pub fn neg(&self) -> Self {
335 if self.is_zero() {
336 return BigInt::zero();
337 }
338 BigInt {
339 negative: !self.negative,
340 limbs: self.limbs.clone(),
341 }
342 }
343
344 pub fn abs(&self) -> Self {
346 BigInt {
347 negative: false,
348 limbs: self.limbs.clone(),
349 }
350 }
351
352 pub fn mul(&self, other: &Self) -> Self {
354 if self.is_zero() || other.is_zero() {
355 return BigInt::zero();
356 }
357 let mut out = alloc::vec![0u32; self.limbs.len() + other.limbs.len()];
358 for (i, &a) in self.limbs.iter().enumerate() {
359 let mut carry: u64 = 0;
360 for (j, &b) in other.limbs.iter().enumerate() {
361 let idx = i + j;
362 let cur = out[idx] as u64 + (a as u64) * (b as u64) + carry;
363 out[idx] = (cur & 0xFFFF_FFFF) as u32;
364 carry = cur >> 32;
365 }
366 let mut k = i + other.limbs.len();
368 while carry > 0 {
369 let cur = out[k] as u64 + carry;
370 out[k] = (cur & 0xFFFF_FFFF) as u32;
371 carry = cur >> 32;
372 k += 1;
373 }
374 }
375 BigInt {
376 negative: self.negative != other.negative,
377 limbs: out,
378 }
379 .normalize()
380 }
381
382 fn divmod_magnitude(a: &[u32], b: &[u32]) -> (Vec<u32>, Vec<u32>) {
385 let dividend = BigInt {
387 negative: false,
388 limbs: a.to_vec(),
389 }
390 .normalize();
391 let divisor = BigInt {
392 negative: false,
393 limbs: b.to_vec(),
394 }
395 .normalize();
396 if dividend.cmp_magnitude(&divisor) == Ordering::Less {
397 return (Vec::new(), dividend.limbs);
398 }
399 let total_bits = dividend.limbs.len() * 32;
401 let mut quotient = BigInt::zero();
402 let mut remainder = BigInt::zero();
403 let one = BigInt::from_i64(1);
404 for i in (0..total_bits).rev() {
405 remainder = remainder.shl_bits(1);
407 let limb = i / 32;
409 let bit = i % 32;
410 if (dividend.limbs[limb] >> bit) & 1 == 1 {
411 remainder = remainder.add(&one);
412 }
413 if remainder.cmp_magnitude(&divisor) != Ordering::Less {
414 remainder = BigInt {
415 negative: false,
416 limbs: Self::sub_magnitude(&remainder.limbs, &divisor.limbs),
417 }
418 .normalize();
419 quotient = quotient.set_bit(i);
420 }
421 }
422 (quotient.normalize().limbs, remainder.normalize().limbs)
423 }
424
425 fn shl_bits(&self, bits: usize) -> Self {
427 if self.is_zero() || bits == 0 {
428 return self.clone();
429 }
430 let limb_shift = bits / 32;
431 let bit_shift = bits % 32;
432 let mut out = alloc::vec![0u32; self.limbs.len() + limb_shift + 1];
433 for (i, &v) in self.limbs.iter().enumerate() {
434 let val = (v as u64) << bit_shift;
435 out[i + limb_shift] |= (val & 0xFFFF_FFFF) as u32;
436 out[i + limb_shift + 1] |= (val >> 32) as u32;
437 }
438 BigInt {
439 negative: self.negative,
440 limbs: out,
441 }
442 .normalize()
443 }
444
445 fn shr_bits(&self, bits: usize) -> Self {
447 if self.is_zero() || bits == 0 {
448 return self.clone();
449 }
450 let limb_shift = bits / 32;
451 let bit_shift = bits % 32;
452 if limb_shift >= self.limbs.len() {
453 return BigInt::zero();
454 }
455 let mut out = alloc::vec![0u32; self.limbs.len() - limb_shift];
456 for (i, slot) in out.iter_mut().enumerate() {
457 let lo = self.limbs[i + limb_shift] >> bit_shift;
458 let hi = if bit_shift > 0 && i + limb_shift + 1 < self.limbs.len() {
459 self.limbs[i + limb_shift + 1] << (32 - bit_shift)
460 } else {
461 0
462 };
463 *slot = lo | hi;
464 }
465 BigInt {
466 negative: self.negative,
467 limbs: out,
468 }
469 .normalize()
470 }
471
472 fn set_bit(&self, i: usize) -> Self {
474 let limb = i / 32;
475 let bit = i % 32;
476 let mut limbs = self.limbs.clone();
477 if limb >= limbs.len() {
478 limbs.resize(limb + 1, 0);
479 }
480 limbs[limb] |= 1 << bit;
481 BigInt {
482 negative: self.negative,
483 limbs,
484 }
485 }
486
487 pub fn div(&self, other: &Self) -> Option<Self> {
489 if other.is_zero() {
490 return None;
491 }
492 let (q, _) = Self::divmod_magnitude(&self.limbs, &other.limbs);
493 Some(
494 BigInt {
495 negative: self.negative != other.negative,
496 limbs: q,
497 }
498 .normalize(),
499 )
500 }
501
502 pub fn rem(&self, other: &Self) -> Option<Self> {
504 if other.is_zero() {
505 return None;
506 }
507 let (_, r) = Self::divmod_magnitude(&self.limbs, &other.limbs);
508 Some(
509 BigInt {
510 negative: self.negative,
511 limbs: r,
512 }
513 .normalize(),
514 )
515 }
516
517 pub fn pow(&self, exp: &Self) -> Option<Self> {
519 if exp.negative {
520 return None;
521 }
522 if exp.is_zero() {
523 return Some(BigInt::from_i64(1));
524 }
525 let mut result = BigInt::from_i64(1);
526 let mut base = self.clone();
527 let mut e = exp.clone();
528 let two = BigInt::from_i64(2);
529 while !e.is_zero() {
530 let (_, r) = Self::divmod_magnitude(&e.limbs, &two.limbs);
532 let odd = !r.is_empty();
533 if odd {
534 result = result.mul(&base);
535 }
536 base = base.mul(&base);
537 e = e.shr_bits(1).abs();
538 }
539 Some(result)
540 }
541
542 pub fn to_decimal_string(&self) -> String {
544 if self.is_zero() {
545 return String::from("0");
546 }
547 let mut digits_rev: Vec<u32> = Vec::new();
549 let chunk = BigInt::from_i64(1_000_000_000);
550 let mut cur = self.abs();
551 while !cur.is_zero() {
552 let (q, r) = Self::divmod_magnitude(&cur.limbs, &chunk.limbs);
553 let rem_val = limbs_to_u64(&r) as u32;
554 digits_rev.push(rem_val);
555 cur = BigInt {
556 negative: false,
557 limbs: q,
558 }
559 .normalize();
560 }
561 let mut s = String::new();
562 if self.negative {
563 s.push('-');
564 }
565 for (i, chunk_val) in digits_rev.iter().rev().enumerate() {
567 if i == 0 {
568 s.push_str(&alloc::format!("{}", chunk_val));
569 } else {
570 s.push_str(&alloc::format!("{:09}", chunk_val));
571 }
572 }
573 s
574 }
575
576 pub fn to_radix_string(&self, radix: u32) -> String {
578 if radix == 10 || !(2..=36).contains(&radix) {
579 return self.to_decimal_string();
580 }
581 if self.is_zero() {
582 return String::from("0");
583 }
584 let base = BigInt::from_u64(radix as u64);
585 let mut digits_rev: Vec<char> = Vec::new();
586 let mut cur = self.abs();
587 while !cur.is_zero() {
588 let (q, r) = Self::divmod_magnitude(&cur.limbs, &base.limbs);
589 let d = limbs_to_u64(&r) as u32;
590 digits_rev.push(core::char::from_digit(d, radix).unwrap_or('0'));
591 cur = BigInt { negative: false, limbs: q }.normalize();
592 }
593 let mut s = String::new();
594 if self.negative {
595 s.push('-');
596 }
597 s.extend(digits_rev.iter().rev());
598 s
599 }
600
601 pub fn to_f64(&self) -> f64 {
603 let mut result = 0.0_f64;
604 let base = 4294967296.0_f64; for &limb in self.limbs.iter().rev() {
606 result = result * base + (limb as f64);
607 }
608 if self.negative {
609 -result
610 } else {
611 result
612 }
613 }
614
615 pub fn is_one(&self) -> bool {
617 !self.negative && self.limbs.len() == 1 && self.limbs[0] == 1
618 }
619
620 fn bit_length(&self) -> usize {
622 match self.limbs.last() {
623 None => 0,
624 Some(&top) => (self.limbs.len() - 1) * 32 + (32 - top.leading_zeros() as usize),
625 }
626 }
627
628 fn to_twos_complement(&self, width: usize) -> Vec<u32> {
631 let mut out = alloc::vec![0u32; width];
632 for (i, slot) in out.iter_mut().enumerate() {
633 *slot = *self.limbs.get(i).unwrap_or(&0);
634 }
635 if self.negative {
636 for slot in out.iter_mut() {
638 *slot = !*slot;
639 }
640 let mut carry = 1u64;
641 for slot in out.iter_mut() {
642 let v = *slot as u64 + carry;
643 *slot = (v & 0xFFFF_FFFF) as u32;
644 carry = v >> 32;
645 if carry == 0 {
646 break;
647 }
648 }
649 }
650 out
651 }
652
653 fn from_twos_complement(mut limbs: Vec<u32>) -> Self {
656 let negative = limbs
657 .last()
658 .map(|&top| (top >> 31) & 1 == 1)
659 .unwrap_or(false);
660 if negative {
661 for slot in limbs.iter_mut() {
663 *slot = !*slot;
664 }
665 let mut carry = 1u64;
666 for slot in limbs.iter_mut() {
667 let v = *slot as u64 + carry;
668 *slot = (v & 0xFFFF_FFFF) as u32;
669 carry = v >> 32;
670 if carry == 0 {
671 break;
672 }
673 }
674 }
675 BigInt { negative, limbs }.normalize()
676 }
677
678 fn bitop_width(&self, other: &Self) -> usize {
680 let bits = self.bit_length().max(other.bit_length());
681 (bits / 32) + 2
683 }
684
685 pub fn bitand(&self, other: &Self) -> Self {
687 let w = self.bitop_width(other);
688 let a = self.to_twos_complement(w);
689 let b = other.to_twos_complement(w);
690 let out: Vec<u32> = a.iter().zip(b.iter()).map(|(x, y)| x & y).collect();
691 Self::from_twos_complement(out)
692 }
693
694 pub fn bitor(&self, other: &Self) -> Self {
696 let w = self.bitop_width(other);
697 let a = self.to_twos_complement(w);
698 let b = other.to_twos_complement(w);
699 let out: Vec<u32> = a.iter().zip(b.iter()).map(|(x, y)| x | y).collect();
700 Self::from_twos_complement(out)
701 }
702
703 pub fn bitxor(&self, other: &Self) -> Self {
705 let w = self.bitop_width(other);
706 let a = self.to_twos_complement(w);
707 let b = other.to_twos_complement(w);
708 let out: Vec<u32> = a.iter().zip(b.iter()).map(|(x, y)| x ^ y).collect();
709 Self::from_twos_complement(out)
710 }
711
712 pub fn bitnot(&self) -> Self {
714 self.neg().sub(&BigInt::from_i64(1))
716 }
717
718 pub fn shl(&self, count: i64) -> Self {
720 if count < 0 {
721 return self.shr(-count);
722 }
723 let shifted = self.shl_bits(count as usize);
724 BigInt {
725 negative: self.negative,
726 limbs: shifted.limbs,
727 }
728 .normalize()
729 }
730
731 pub fn shr(&self, count: i64) -> Self {
733 if count < 0 {
734 return self.shl(-count);
735 }
736 let n = count as usize;
737 if !self.negative {
738 let shifted = self.shr_bits(n);
740 return BigInt {
741 negative: false,
742 limbs: shifted.limbs,
743 }
744 .normalize();
745 }
746 let full_limbs = n / 32;
749 let rem_bits = n % 32;
750 let mut truncated_bits = false;
751 for &l in self.limbs.iter().take(full_limbs) {
752 if l != 0 {
753 truncated_bits = true;
754 break;
755 }
756 }
757 if !truncated_bits && rem_bits > 0 {
758 if let Some(&l) = self.limbs.get(full_limbs) {
759 let mask = (1u32 << rem_bits) - 1;
760 if (l & mask) != 0 {
761 truncated_bits = true;
762 }
763 }
764 }
765 let mag = self.shr_bits(n);
766 let mut result = BigInt {
767 negative: true,
768 limbs: mag.limbs,
769 }
770 .normalize();
771 if truncated_bits {
772 result = result.sub(&BigInt::from_i64(1));
774 }
775 result
776 }
777
778 pub fn as_uint_n(&self, bits: u64) -> Self {
780 if bits == 0 {
781 return BigInt::zero();
782 }
783 let full_limbs = (bits / 32) as usize;
784 let rem_bits = (bits % 32) as usize;
785 let width = full_limbs + if rem_bits > 0 { 1 } else { 0 } + 1;
786 let tc = self.to_twos_complement(width);
787 let out_limbs_count = full_limbs + if rem_bits > 0 { 1 } else { 0 };
788 let mut out = alloc::vec![0u32; out_limbs_count];
789 for i in 0..full_limbs {
790 if i < tc.len() {
791 out[i] = tc[i];
792 }
793 }
794 if rem_bits > 0 && full_limbs < tc.len() {
795 let mask = (1u32 << rem_bits) - 1;
796 out[full_limbs] = tc[full_limbs] & mask;
797 }
798 BigInt {
800 negative: false,
801 limbs: out,
802 }
803 .normalize()
804 }
805
806 pub fn as_int_n(&self, bits: u64) -> Self {
808 if bits == 0 {
809 return BigInt::zero();
810 }
811 let unsigned = self.as_uint_n(bits);
812 let top = (bits - 1) as usize;
814 let limb = top / 32;
815 let bit = top % 32;
816 let is_neg = limb < unsigned.limbs.len() && (unsigned.limbs[limb] >> bit) & 1 == 1;
817 if is_neg {
818 let two_pow = BigInt::from_i64(1).shl(bits as i64);
820 unsigned.sub(&two_pow)
821 } else {
822 unsigned
823 }
824 }
825
826 pub fn to_u64_truncated(&self) -> u64 {
829 let unsigned = self.as_uint_n(64);
830 let low = *unsigned.limbs.first().unwrap_or(&0) as u64;
831 let high = *unsigned.limbs.get(1).unwrap_or(&0) as u64;
832 low | (high << 32)
833 }
834}
835
836fn limbs_to_u64(limbs: &[u32]) -> u64 {
838 let mut v = 0u64;
839 for (i, &l) in limbs.iter().enumerate().take(2) {
840 v |= (l as u64) << (32 * i);
841 }
842 v
843}
844
845pub fn selftest() -> (usize, usize) {
848 let mut pass = 0usize;
849 let mut total = 0usize;
850
851 fn check_str(pass: &mut usize, total: &mut usize, got: &str, want: &str) {
853 *total += 1;
854 if got == want {
855 *pass += 1;
856 }
857 }
858 fn check_bool(pass: &mut usize, total: &mut usize, cond: bool) {
860 *total += 1;
861 if cond {
862 *pass += 1;
863 }
864 }
865 fn check_opt(pass: &mut usize, total: &mut usize, got: Option<String>, want: &str) {
868 *total += 1;
869 if got.as_deref() == Some(want) {
870 *pass += 1;
871 }
872 }
873
874 let bi = BigInt::from_i64;
875 let p = &mut pass;
876 let t = &mut total;
877
878 check_opt(
880 p,
881 t,
882 BigInt::parse_str("0").map(|b| b.to_decimal_string()),
883 "0",
884 );
885 check_opt(
886 p,
887 t,
888 BigInt::parse_str("12345678901234567890").map(|b| b.to_decimal_string()),
889 "12345678901234567890",
890 );
891 check_opt(
892 p,
893 t,
894 BigInt::parse_str("-98765432109876543210").map(|b| b.to_decimal_string()),
895 "-98765432109876543210",
896 );
897 check_opt(
898 p,
899 t,
900 BigInt::parse_str("0xff").map(|b| b.to_decimal_string()),
901 "255",
902 );
903 check_opt(
904 p,
905 t,
906 BigInt::parse_str("0b1010").map(|b| b.to_decimal_string()),
907 "10",
908 );
909 check_opt(
910 p,
911 t,
912 BigInt::parse_str("0o17").map(|b| b.to_decimal_string()),
913 "15",
914 );
915 check_opt(
916 p,
917 t,
918 BigInt::parse_str("1_000_000").map(|b| b.to_decimal_string()),
919 "1000000",
920 );
921
922 check_str(p, t, &bi(2).add(&bi(3)).to_decimal_string(), "5");
924 check_opt(
925 p,
926 t,
927 BigInt::parse_str("4294967295").map(|b| b.add(&bi(1)).to_decimal_string()),
928 "4294967296",
929 );
930 check_str(p, t, &bi(5).sub(&bi(8)).to_decimal_string(), "-3");
931 check_str(p, t, &bi(-5).add(&bi(5)).to_decimal_string(), "0");
932 check_opt(
933 p,
934 t,
935 BigInt::parse_str("18446744073709551616").map(|b| b.sub(&bi(1)).to_decimal_string()),
936 "18446744073709551615",
937 );
938
939 check_str(
941 p,
942 t,
943 &bi(123456789).mul(&bi(987654321)).to_decimal_string(),
944 "121932631112635269",
945 );
946 check_str(p, t, &bi(-7).mul(&bi(6)).to_decimal_string(), "-42");
947 check_opt(
948 p,
949 t,
950 BigInt::parse_str("99999999999999999999").and_then(|a| {
951 BigInt::parse_str("99999999999999999999").map(|b| a.mul(&b).to_decimal_string())
952 }),
953 "9999999999999999999800000000000000000001",
954 );
955
956 check_opt(
958 p,
959 t,
960 bi(100).div(&bi(7)).map(|b| b.to_decimal_string()),
961 "14",
962 );
963 check_opt(
964 p,
965 t,
966 bi(100).rem(&bi(7)).map(|b| b.to_decimal_string()),
967 "2",
968 );
969 check_opt(
970 p,
971 t,
972 bi(-100).div(&bi(7)).map(|b| b.to_decimal_string()),
973 "-14",
974 );
975 check_opt(
976 p,
977 t,
978 bi(-100).rem(&bi(7)).map(|b| b.to_decimal_string()),
979 "-2",
980 );
981 check_bool(p, t, bi(1).div(&bi(0)).is_none());
982
983 check_opt(
985 p,
986 t,
987 bi(2).pow(&bi(64)).map(|b| b.to_decimal_string()),
988 "18446744073709551616",
989 );
990 check_opt(p, t, bi(3).pow(&bi(0)).map(|b| b.to_decimal_string()), "1");
991 check_opt(
992 p,
993 t,
994 bi(-2).pow(&bi(3)).map(|b| b.to_decimal_string()),
995 "-8",
996 );
997
998 check_bool(p, t, bi(5).cmp(&bi(7)) == Ordering::Less);
1000 check_bool(p, t, bi(-3).cmp(&bi(-9)) == Ordering::Greater);
1001 check_bool(p, t, bi(42).cmp(&bi(42)) == Ordering::Equal);
1002
1003 check_str(
1005 p,
1006 t,
1007 &bi(0b1100).bitand(&bi(0b1010)).to_decimal_string(),
1008 "8",
1009 ); check_str(
1011 p,
1012 t,
1013 &bi(0b1100).bitor(&bi(0b1010)).to_decimal_string(),
1014 "14",
1015 ); check_str(
1017 p,
1018 t,
1019 &bi(0b1100).bitxor(&bi(0b1010)).to_decimal_string(),
1020 "6",
1021 ); check_str(p, t, &bi(5).bitnot().to_decimal_string(), "-6"); check_str(p, t, &bi(-1).bitnot().to_decimal_string(), "0"); check_str(p, t, &bi(-1).bitand(&bi(5)).to_decimal_string(), "5"); check_str(p, t, &bi(-1).bitor(&bi(5)).to_decimal_string(), "-1"); check_str(p, t, &bi(-2).bitand(&bi(3)).to_decimal_string(), "2"); check_str(p, t, &bi(-1).bitxor(&bi(-1)).to_decimal_string(), "0"); check_str(
1033 p,
1034 t,
1035 &bi(1).shl(64).to_decimal_string(),
1036 "18446744073709551616",
1037 );
1038 check_str(p, t, &bi(255).shr(4).to_decimal_string(), "15");
1039 check_str(p, t, &bi(-8).shr(1).to_decimal_string(), "-4");
1041 check_str(p, t, &bi(-7).shr(1).to_decimal_string(), "-4");
1042 check_str(p, t, &bi(-1).shr(5).to_decimal_string(), "-1");
1043 check_str(
1044 p,
1045 t,
1046 &bi(12345).shl(40).shr(40).to_decimal_string(),
1047 "12345",
1048 );
1049
1050 check_str(p, t, &bi(256).as_uint_n(8).to_decimal_string(), "0");
1052 check_str(p, t, &bi(257).as_uint_n(8).to_decimal_string(), "1");
1053 check_str(p, t, &bi(-1).as_uint_n(8).to_decimal_string(), "255");
1054 check_str(p, t, &bi(255).as_int_n(8).to_decimal_string(), "-1");
1055 check_str(p, t, &bi(128).as_int_n(8).to_decimal_string(), "-128");
1056 check_str(p, t, &bi(127).as_int_n(8).to_decimal_string(), "127");
1057 check_str(p, t, &bi(0x8000).as_int_n(16).to_decimal_string(), "-32768");
1058
1059 check_bool(p, t, bi(9007199254740992).to_f64() == 9007199254740992.0);
1061 check_bool(
1062 p,
1063 t,
1064 BigInt::from_f64(42.0).map(|b| b.to_decimal_string()) == Some(String::from("42")),
1065 );
1066 check_bool(p, t, BigInt::from_f64(1.5).is_none());
1067
1068 (pass, total)
1069}