cw_bigint/bigint.rs
1// `Add`/`Sub` ops may flip from `BigInt` to its `BigUint` magnitude
2#![allow(clippy::suspicious_arithmetic_impl)]
3
4use crate::std_alloc::{String, Vec};
5use core::cmp::Ordering::{self, Equal};
6use core::default::Default;
7use core::fmt;
8use core::hash;
9use core::ops::{Neg, Not};
10use core::str;
11use core::{i128, u128};
12use core::{i64, u64};
13
14use num_integer::{Integer, Roots};
15use num_traits::{Num, One, Pow, Signed, Zero};
16
17use self::Sign::{Minus, NoSign, Plus};
18
19use crate::big_digit::BigDigit;
20use crate::biguint::to_str_radix_reversed;
21use crate::biguint::{BigUint, IntDigits, U32Digits, U64Digits};
22
23mod addition;
24mod division;
25mod multiplication;
26mod subtraction;
27
28mod bits;
29mod convert;
30mod power;
31mod shift;
32
33#[cfg(any(feature = "quickcheck", feature = "arbitrary"))]
34mod arbitrary;
35
36#[cfg(feature = "serde")]
37mod serde;
38
39/// A Sign is a `BigInt`'s composing element.
40#[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, Hash)]
41pub enum Sign {
42 Minus,
43 NoSign,
44 Plus,
45}
46
47impl Neg for Sign {
48 type Output = Sign;
49
50 /// Negate Sign value.
51 #[inline]
52 fn neg(self) -> Sign {
53 match self {
54 Minus => Plus,
55 NoSign => NoSign,
56 Plus => Minus,
57 }
58 }
59}
60
61/// A big signed integer type.
62pub struct BigInt {
63 sign: Sign,
64 data: BigUint,
65}
66
67// Note: derived `Clone` doesn't specialize `clone_from`,
68// but we want to keep the allocation in `data`.
69impl Clone for BigInt {
70 #[inline]
71 fn clone(&self) -> Self {
72 BigInt {
73 sign: self.sign,
74 data: self.data.clone(),
75 }
76 }
77
78 #[inline]
79 fn clone_from(&mut self, other: &Self) {
80 self.sign = other.sign;
81 self.data.clone_from(&other.data);
82 }
83}
84
85impl hash::Hash for BigInt {
86 #[inline]
87 fn hash<H: hash::Hasher>(&self, state: &mut H) {
88 debug_assert!((self.sign != NoSign) ^ self.data.is_zero());
89 self.sign.hash(state);
90 if self.sign != NoSign {
91 self.data.hash(state);
92 }
93 }
94}
95
96impl PartialEq for BigInt {
97 #[inline]
98 fn eq(&self, other: &BigInt) -> bool {
99 debug_assert!((self.sign != NoSign) ^ self.data.is_zero());
100 debug_assert!((other.sign != NoSign) ^ other.data.is_zero());
101 self.sign == other.sign && (self.sign == NoSign || self.data == other.data)
102 }
103}
104
105impl Eq for BigInt {}
106
107impl PartialOrd for BigInt {
108 #[inline]
109 fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
110 Some(self.cmp(other))
111 }
112}
113
114impl Ord for BigInt {
115 #[inline]
116 fn cmp(&self, other: &BigInt) -> Ordering {
117 debug_assert!((self.sign != NoSign) ^ self.data.is_zero());
118 debug_assert!((other.sign != NoSign) ^ other.data.is_zero());
119 let scmp = self.sign.cmp(&other.sign);
120 if scmp != Equal {
121 return scmp;
122 }
123
124 match self.sign {
125 NoSign => Equal,
126 Plus => self.data.cmp(&other.data),
127 Minus => other.data.cmp(&self.data),
128 }
129 }
130}
131
132impl Default for BigInt {
133 #[inline]
134 fn default() -> BigInt {
135 Zero::zero()
136 }
137}
138
139impl fmt::Debug for BigInt {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 fmt::Display::fmt(self, f)
142 }
143}
144
145impl fmt::Display for BigInt {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 f.pad_integral(
148 !self.is_negative(),
149 "",
150 &self.data.to_str_radix(16).to_ascii_uppercase()
151 )
152 }
153}
154
155impl fmt::Binary for BigInt {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 f.pad_integral(!self.is_negative(), "0b", &self.data.to_str_radix(2))
158 }
159}
160
161impl fmt::Octal for BigInt {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 f.pad_integral(!self.is_negative(), "0o", &self.data.to_str_radix(8))
164 }
165}
166
167impl fmt::LowerHex for BigInt {
168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169 f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16))
170 }
171}
172
173impl fmt::UpperHex for BigInt {
174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175 let mut s = self.data.to_str_radix(16);
176 s.make_ascii_uppercase();
177 f.pad_integral(!self.is_negative(), "0x", &s)
178 }
179}
180
181// !-2 = !...f fe = ...0 01 = +1
182// !-1 = !...f ff = ...0 00 = 0
183// ! 0 = !...0 00 = ...f ff = -1
184// !+1 = !...0 01 = ...f fe = -2
185impl Not for BigInt {
186 type Output = BigInt;
187
188 fn not(mut self) -> BigInt {
189 match self.sign {
190 NoSign | Plus => {
191 self.data += 1u32;
192 self.sign = Minus;
193 }
194 Minus => {
195 self.data -= 1u32;
196 self.sign = if self.data.is_zero() { NoSign } else { Plus };
197 }
198 }
199 self
200 }
201}
202
203impl<'a> Not for &'a BigInt {
204 type Output = BigInt;
205
206 fn not(self) -> BigInt {
207 match self.sign {
208 NoSign => -BigInt::one(),
209 Plus => -BigInt::from(&self.data + 1u32),
210 Minus => BigInt::from(&self.data - 1u32),
211 }
212 }
213}
214
215impl Zero for BigInt {
216 #[inline]
217 fn zero() -> BigInt {
218 BigInt {
219 sign: NoSign,
220 data: BigUint::zero(),
221 }
222 }
223
224 #[inline]
225 fn set_zero(&mut self) {
226 self.data.set_zero();
227 self.sign = NoSign;
228 }
229
230 #[inline]
231 fn is_zero(&self) -> bool {
232 self.sign == NoSign
233 }
234}
235
236impl One for BigInt {
237 #[inline]
238 fn one() -> BigInt {
239 BigInt {
240 sign: Plus,
241 data: BigUint::one(),
242 }
243 }
244
245 #[inline]
246 fn set_one(&mut self) {
247 self.data.set_one();
248 self.sign = Plus;
249 }
250
251 #[inline]
252 fn is_one(&self) -> bool {
253 self.sign == Plus && self.data.is_one()
254 }
255}
256
257impl Signed for BigInt {
258 #[inline]
259 fn abs(&self) -> BigInt {
260 match self.sign {
261 Plus | NoSign => self.clone(),
262 Minus => BigInt::from(self.data.clone()),
263 }
264 }
265
266 #[inline]
267 fn abs_sub(&self, other: &BigInt) -> BigInt {
268 if *self <= *other {
269 Zero::zero()
270 } else {
271 self - other
272 }
273 }
274
275 #[inline]
276 fn signum(&self) -> BigInt {
277 match self.sign {
278 Plus => BigInt::one(),
279 Minus => -BigInt::one(),
280 NoSign => BigInt::zero(),
281 }
282 }
283
284 #[inline]
285 fn is_positive(&self) -> bool {
286 self.sign == Plus
287 }
288
289 #[inline]
290 fn is_negative(&self) -> bool {
291 self.sign == Minus
292 }
293}
294
295trait UnsignedAbs {
296 type Unsigned;
297
298 /// A convenience method for getting the absolute value of a signed primitive as unsigned
299 /// See also `unsigned_abs`: https://github.com/rust-lang/rust/issues/74913
300 fn uabs(self) -> Self::Unsigned;
301
302 fn checked_uabs(self) -> CheckedUnsignedAbs<Self::Unsigned>;
303}
304
305enum CheckedUnsignedAbs<T> {
306 Positive(T),
307 Negative(T),
308}
309use self::CheckedUnsignedAbs::{Negative, Positive};
310
311macro_rules! impl_unsigned_abs {
312 ($Signed:ty, $Unsigned:ty) => {
313 impl UnsignedAbs for $Signed {
314 type Unsigned = $Unsigned;
315
316 #[inline]
317 fn uabs(self) -> $Unsigned {
318 self.wrapping_abs() as $Unsigned
319 }
320
321 #[inline]
322 fn checked_uabs(self) -> CheckedUnsignedAbs<Self::Unsigned> {
323 if self >= 0 {
324 Positive(self as $Unsigned)
325 } else {
326 Negative(self.wrapping_neg() as $Unsigned)
327 }
328 }
329 }
330 };
331}
332impl_unsigned_abs!(i8, u8);
333impl_unsigned_abs!(i16, u16);
334impl_unsigned_abs!(i32, u32);
335impl_unsigned_abs!(i64, u64);
336impl_unsigned_abs!(i128, u128);
337impl_unsigned_abs!(isize, usize);
338
339impl Neg for BigInt {
340 type Output = BigInt;
341
342 #[inline]
343 fn neg(mut self) -> BigInt {
344 self.sign = -self.sign;
345 self
346 }
347}
348
349impl<'a> Neg for &'a BigInt {
350 type Output = BigInt;
351
352 #[inline]
353 fn neg(self) -> BigInt {
354 -self.clone()
355 }
356}
357
358impl Integer for BigInt {
359 #[inline]
360 fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) {
361 // r.sign == self.sign
362 let (d_ui, r_ui) = self.data.div_rem(&other.data);
363 let d = BigInt::from_biguint(self.sign, d_ui);
364 let r = BigInt::from_biguint(self.sign, r_ui);
365 if other.is_negative() {
366 (-d, r)
367 } else {
368 (d, r)
369 }
370 }
371
372 #[inline]
373 fn div_floor(&self, other: &BigInt) -> BigInt {
374 let (d_ui, m) = self.data.div_mod_floor(&other.data);
375 let d = BigInt::from(d_ui);
376 match (self.sign, other.sign) {
377 (Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => d,
378 (Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => {
379 if m.is_zero() {
380 -d
381 } else {
382 -d - 1u32
383 }
384 }
385 (_, NoSign) => unreachable!(),
386 }
387 }
388
389 #[inline]
390 fn mod_floor(&self, other: &BigInt) -> BigInt {
391 // m.sign == other.sign
392 let m_ui = self.data.mod_floor(&other.data);
393 let m = BigInt::from_biguint(other.sign, m_ui);
394 match (self.sign, other.sign) {
395 (Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => m,
396 (Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => {
397 if m.is_zero() {
398 m
399 } else {
400 other - m
401 }
402 }
403 (_, NoSign) => unreachable!(),
404 }
405 }
406
407 fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) {
408 // m.sign == other.sign
409 let (d_ui, m_ui) = self.data.div_mod_floor(&other.data);
410 let d = BigInt::from(d_ui);
411 let m = BigInt::from_biguint(other.sign, m_ui);
412 match (self.sign, other.sign) {
413 (Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => (d, m),
414 (Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => {
415 if m.is_zero() {
416 (-d, m)
417 } else {
418 (-d - 1u32, other - m)
419 }
420 }
421 (_, NoSign) => unreachable!(),
422 }
423 }
424
425 #[inline]
426 fn div_ceil(&self, other: &Self) -> Self {
427 let (d_ui, m) = self.data.div_mod_floor(&other.data);
428 let d = BigInt::from(d_ui);
429 match (self.sign, other.sign) {
430 (Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => -d,
431 (Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => {
432 if m.is_zero() {
433 d
434 } else {
435 d + 1u32
436 }
437 }
438 (_, NoSign) => unreachable!(),
439 }
440 }
441
442 /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
443 ///
444 /// The result is always positive.
445 #[inline]
446 fn gcd(&self, other: &BigInt) -> BigInt {
447 BigInt::from(self.data.gcd(&other.data))
448 }
449
450 /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
451 #[inline]
452 fn lcm(&self, other: &BigInt) -> BigInt {
453 BigInt::from(self.data.lcm(&other.data))
454 }
455
456 /// Calculates the Greatest Common Divisor (GCD) and
457 /// Lowest Common Multiple (LCM) together.
458 #[inline]
459 fn gcd_lcm(&self, other: &BigInt) -> (BigInt, BigInt) {
460 let (gcd, lcm) = self.data.gcd_lcm(&other.data);
461 (BigInt::from(gcd), BigInt::from(lcm))
462 }
463
464 /// Greatest common divisor, least common multiple, and Bézout coefficients.
465 #[inline]
466 fn extended_gcd_lcm(&self, other: &BigInt) -> (num_integer::ExtendedGcd<BigInt>, BigInt) {
467 let egcd = self.extended_gcd(other);
468 let lcm = if egcd.gcd.is_zero() {
469 BigInt::zero()
470 } else {
471 BigInt::from(&self.data / &egcd.gcd.data * &other.data)
472 };
473 (egcd, lcm)
474 }
475
476 /// Deprecated, use `is_multiple_of` instead.
477 #[inline]
478 fn divides(&self, other: &BigInt) -> bool {
479 self.is_multiple_of(other)
480 }
481
482 /// Returns `true` if the number is a multiple of `other`.
483 #[inline]
484 fn is_multiple_of(&self, other: &BigInt) -> bool {
485 self.data.is_multiple_of(&other.data)
486 }
487
488 /// Returns `true` if the number is divisible by `2`.
489 #[inline]
490 fn is_even(&self) -> bool {
491 self.data.is_even()
492 }
493
494 /// Returns `true` if the number is not divisible by `2`.
495 #[inline]
496 fn is_odd(&self) -> bool {
497 self.data.is_odd()
498 }
499
500 /// Rounds up to nearest multiple of argument.
501 #[inline]
502 fn next_multiple_of(&self, other: &Self) -> Self {
503 let m = self.mod_floor(other);
504 if m.is_zero() {
505 self.clone()
506 } else {
507 self + (other - m)
508 }
509 }
510 /// Rounds down to nearest multiple of argument.
511 #[inline]
512 fn prev_multiple_of(&self, other: &Self) -> Self {
513 self - self.mod_floor(other)
514 }
515}
516
517impl Roots for BigInt {
518 fn nth_root(&self, n: u32) -> Self {
519 assert!(
520 !(self.is_negative() && n.is_even()),
521 "root of degree {} is imaginary",
522 n
523 );
524
525 BigInt::from_biguint(self.sign, self.data.nth_root(n))
526 }
527
528 fn sqrt(&self) -> Self {
529 assert!(!self.is_negative(), "square root is imaginary");
530
531 BigInt::from_biguint(self.sign, self.data.sqrt())
532 }
533
534 fn cbrt(&self) -> Self {
535 BigInt::from_biguint(self.sign, self.data.cbrt())
536 }
537}
538
539impl IntDigits for BigInt {
540 #[inline]
541 fn digits(&self) -> &[BigDigit] {
542 self.data.digits()
543 }
544 #[inline]
545 fn digits_mut(&mut self) -> &mut Vec<BigDigit> {
546 self.data.digits_mut()
547 }
548 #[inline]
549 fn normalize(&mut self) {
550 self.data.normalize();
551 if self.data.is_zero() {
552 self.sign = NoSign;
553 }
554 }
555 #[inline]
556 fn capacity(&self) -> usize {
557 self.data.capacity()
558 }
559 #[inline]
560 fn len(&self) -> usize {
561 self.data.len()
562 }
563}
564
565/// A generic trait for converting a value to a `BigInt`. This may return
566/// `None` when converting from `f32` or `f64`, and will always succeed
567/// when converting from any integer or unsigned primitive, or `BigUint`.
568pub trait ToBigInt {
569 /// Converts the value of `self` to a `BigInt`.
570 fn to_bigint(&self) -> Option<BigInt>;
571}
572
573impl BigInt {
574 /// Creates and initializes a BigInt.
575 ///
576 /// The base 2<sup>32</sup> digits are ordered least significant digit first.
577 #[inline]
578 pub fn new(sign: Sign, digits: Vec<u32>) -> BigInt {
579 BigInt::from_biguint(sign, BigUint::new(digits))
580 }
581
582 /// Creates and initializes a `BigInt`.
583 ///
584 /// The base 2<sup>32</sup> digits are ordered least significant digit first.
585 #[inline]
586 pub fn from_biguint(mut sign: Sign, mut data: BigUint) -> BigInt {
587 if sign == NoSign {
588 data.assign_from_slice(&[]);
589 } else if data.is_zero() {
590 sign = NoSign;
591 }
592
593 BigInt { sign, data }
594 }
595
596 /// Creates and initializes a `BigInt`.
597 ///
598 /// The base 2<sup>32</sup> digits are ordered least significant digit first.
599 #[inline]
600 pub fn from_slice(sign: Sign, slice: &[u32]) -> BigInt {
601 BigInt::from_biguint(sign, BigUint::from_slice(slice))
602 }
603
604 /// Reinitializes a `BigInt`.
605 ///
606 /// The base 2<sup>32</sup> digits are ordered least significant digit first.
607 #[inline]
608 pub fn assign_from_slice(&mut self, sign: Sign, slice: &[u32]) {
609 if sign == NoSign {
610 self.set_zero();
611 } else {
612 self.data.assign_from_slice(slice);
613 self.sign = if self.data.is_zero() { NoSign } else { sign };
614 }
615 }
616
617 /// Creates and initializes a `BigInt`.
618 ///
619 /// The bytes are in big-endian byte order.
620 ///
621 /// # Examples
622 ///
623 /// ```
624 /// use num_bigint::{BigInt, Sign};
625 ///
626 /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"),
627 /// BigInt::parse_bytes(b"65", 10).unwrap());
628 /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AA"),
629 /// BigInt::parse_bytes(b"16705", 10).unwrap());
630 /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AB"),
631 /// BigInt::parse_bytes(b"16706", 10).unwrap());
632 /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"),
633 /// BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
634 /// ```
635 #[inline]
636 pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt {
637 BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes))
638 }
639
640 /// Creates and initializes a `BigInt`.
641 ///
642 /// The bytes are in little-endian byte order.
643 #[inline]
644 pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt {
645 BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes))
646 }
647
648 /// Creates and initializes a `BigInt` from an array of bytes in
649 /// two's complement binary representation.
650 ///
651 /// The digits are in big-endian base 2<sup>8</sup>.
652 #[inline]
653 pub fn from_signed_bytes_be(digits: &[u8]) -> BigInt {
654 convert::from_signed_bytes_be(digits)
655 }
656
657 /// Creates and initializes a `BigInt` from an array of bytes in two's complement.
658 ///
659 /// The digits are in little-endian base 2<sup>8</sup>.
660 #[inline]
661 pub fn from_signed_bytes_le(digits: &[u8]) -> BigInt {
662 convert::from_signed_bytes_le(digits)
663 }
664
665 /// Creates and initializes a `BigInt`.
666 ///
667 /// # Examples
668 ///
669 /// ```
670 /// use num_bigint::{BigInt, ToBigInt};
671 ///
672 /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234));
673 /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD));
674 /// assert_eq!(BigInt::parse_bytes(b"G", 16), None);
675 /// ```
676 #[inline]
677 pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigInt> {
678 let s = str::from_utf8(buf).ok()?;
679 BigInt::from_str_radix(s, radix).ok()
680 }
681
682 /// Creates and initializes a `BigInt`. Each u8 of the input slice is
683 /// interpreted as one digit of the number
684 /// and must therefore be less than `radix`.
685 ///
686 /// The bytes are in big-endian byte order.
687 /// `radix` must be in the range `2...256`.
688 ///
689 /// # Examples
690 ///
691 /// ```
692 /// use num_bigint::{BigInt, Sign};
693 ///
694 /// let inbase190 = vec![15, 33, 125, 12, 14];
695 /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap();
696 /// assert_eq!(a.to_radix_be(190), (Sign:: Minus, inbase190));
697 /// ```
698 pub fn from_radix_be(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt> {
699 let u = BigUint::from_radix_be(buf, radix)?;
700 Some(BigInt::from_biguint(sign, u))
701 }
702
703 /// Creates and initializes a `BigInt`. Each u8 of the input slice is
704 /// interpreted as one digit of the number
705 /// and must therefore be less than `radix`.
706 ///
707 /// The bytes are in little-endian byte order.
708 /// `radix` must be in the range `2...256`.
709 ///
710 /// # Examples
711 ///
712 /// ```
713 /// use num_bigint::{BigInt, Sign};
714 ///
715 /// let inbase190 = vec![14, 12, 125, 33, 15];
716 /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap();
717 /// assert_eq!(a.to_radix_be(190), (Sign::Minus, inbase190));
718 /// ```
719 pub fn from_radix_le(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt> {
720 let u = BigUint::from_radix_le(buf, radix)?;
721 Some(BigInt::from_biguint(sign, u))
722 }
723
724 /// Returns the sign and the byte representation of the `BigInt` in big-endian byte order.
725 ///
726 /// # Examples
727 ///
728 /// ```
729 /// use num_bigint::{ToBigInt, Sign};
730 ///
731 /// let i = -1125.to_bigint().unwrap();
732 /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101]));
733 /// ```
734 #[inline]
735 pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) {
736 (self.sign, self.data.to_bytes_be())
737 }
738
739 /// Returns the sign and the byte representation of the `BigInt` in little-endian byte order.
740 ///
741 /// # Examples
742 ///
743 /// ```
744 /// use num_bigint::{ToBigInt, Sign};
745 ///
746 /// let i = -1125.to_bigint().unwrap();
747 /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4]));
748 /// ```
749 #[inline]
750 pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) {
751 (self.sign, self.data.to_bytes_le())
752 }
753
754 /// Returns the sign and the `u32` digits representation of the `BigInt` ordered least
755 /// significant digit first.
756 ///
757 /// # Examples
758 ///
759 /// ```
760 /// use num_bigint::{BigInt, Sign};
761 ///
762 /// assert_eq!(BigInt::from(-1125).to_u32_digits(), (Sign::Minus, vec![1125]));
763 /// assert_eq!(BigInt::from(4294967295u32).to_u32_digits(), (Sign::Plus, vec![4294967295]));
764 /// assert_eq!(BigInt::from(4294967296u64).to_u32_digits(), (Sign::Plus, vec![0, 1]));
765 /// assert_eq!(BigInt::from(-112500000000i64).to_u32_digits(), (Sign::Minus, vec![830850304, 26]));
766 /// assert_eq!(BigInt::from(112500000000i64).to_u32_digits(), (Sign::Plus, vec![830850304, 26]));
767 /// ```
768 #[inline]
769 pub fn to_u32_digits(&self) -> (Sign, Vec<u32>) {
770 (self.sign, self.data.to_u32_digits())
771 }
772
773 /// Returns the sign and the `u64` digits representation of the `BigInt` ordered least
774 /// significant digit first.
775 ///
776 /// # Examples
777 ///
778 /// ```
779 /// use num_bigint::{BigInt, Sign};
780 ///
781 /// assert_eq!(BigInt::from(-1125).to_u64_digits(), (Sign::Minus, vec![1125]));
782 /// assert_eq!(BigInt::from(4294967295u32).to_u64_digits(), (Sign::Plus, vec![4294967295]));
783 /// assert_eq!(BigInt::from(4294967296u64).to_u64_digits(), (Sign::Plus, vec![4294967296]));
784 /// assert_eq!(BigInt::from(-112500000000i64).to_u64_digits(), (Sign::Minus, vec![112500000000]));
785 /// assert_eq!(BigInt::from(112500000000i64).to_u64_digits(), (Sign::Plus, vec![112500000000]));
786 /// assert_eq!(BigInt::from(1u128 << 64).to_u64_digits(), (Sign::Plus, vec![0, 1]));
787 /// ```
788 #[inline]
789 pub fn to_u64_digits(&self) -> (Sign, Vec<u64>) {
790 (self.sign, self.data.to_u64_digits())
791 }
792
793 /// Returns an iterator of `u32` digits representation of the `BigInt` ordered least
794 /// significant digit first.
795 ///
796 /// # Examples
797 ///
798 /// ```
799 /// use num_bigint::BigInt;
800 ///
801 /// assert_eq!(BigInt::from(-1125).iter_u32_digits().collect::<Vec<u32>>(), vec![1125]);
802 /// assert_eq!(BigInt::from(4294967295u32).iter_u32_digits().collect::<Vec<u32>>(), vec![4294967295]);
803 /// assert_eq!(BigInt::from(4294967296u64).iter_u32_digits().collect::<Vec<u32>>(), vec![0, 1]);
804 /// assert_eq!(BigInt::from(-112500000000i64).iter_u32_digits().collect::<Vec<u32>>(), vec![830850304, 26]);
805 /// assert_eq!(BigInt::from(112500000000i64).iter_u32_digits().collect::<Vec<u32>>(), vec![830850304, 26]);
806 /// ```
807 #[inline]
808 pub fn iter_u32_digits(&self) -> U32Digits<'_> {
809 self.data.iter_u32_digits()
810 }
811
812 /// Returns an iterator of `u64` digits representation of the `BigInt` ordered least
813 /// significant digit first.
814 ///
815 /// # Examples
816 ///
817 /// ```
818 /// use num_bigint::BigInt;
819 ///
820 /// assert_eq!(BigInt::from(-1125).iter_u64_digits().collect::<Vec<u64>>(), vec![1125u64]);
821 /// assert_eq!(BigInt::from(4294967295u32).iter_u64_digits().collect::<Vec<u64>>(), vec![4294967295u64]);
822 /// assert_eq!(BigInt::from(4294967296u64).iter_u64_digits().collect::<Vec<u64>>(), vec![4294967296u64]);
823 /// assert_eq!(BigInt::from(-112500000000i64).iter_u64_digits().collect::<Vec<u64>>(), vec![112500000000u64]);
824 /// assert_eq!(BigInt::from(112500000000i64).iter_u64_digits().collect::<Vec<u64>>(), vec![112500000000u64]);
825 /// assert_eq!(BigInt::from(1u128 << 64).iter_u64_digits().collect::<Vec<u64>>(), vec![0, 1]);
826 /// ```
827 #[inline]
828 pub fn iter_u64_digits(&self) -> U64Digits<'_> {
829 self.data.iter_u64_digits()
830 }
831
832 /// Returns the two's-complement byte representation of the `BigInt` in big-endian byte order.
833 ///
834 /// # Examples
835 ///
836 /// ```
837 /// use num_bigint::ToBigInt;
838 ///
839 /// let i = -1125.to_bigint().unwrap();
840 /// assert_eq!(i.to_signed_bytes_be(), vec![251, 155]);
841 /// ```
842 #[inline]
843 pub fn to_signed_bytes_be(&self) -> Vec<u8> {
844 convert::to_signed_bytes_be(self)
845 }
846
847 /// Returns the two's-complement byte representation of the `BigInt` in little-endian byte order.
848 ///
849 /// # Examples
850 ///
851 /// ```
852 /// use num_bigint::ToBigInt;
853 ///
854 /// let i = -1125.to_bigint().unwrap();
855 /// assert_eq!(i.to_signed_bytes_le(), vec![155, 251]);
856 /// ```
857 #[inline]
858 pub fn to_signed_bytes_le(&self) -> Vec<u8> {
859 convert::to_signed_bytes_le(self)
860 }
861
862 /// Returns the integer formatted as a string in the given radix.
863 /// `radix` must be in the range `2...36`.
864 ///
865 /// # Examples
866 ///
867 /// ```
868 /// use num_bigint::BigInt;
869 ///
870 /// let i = BigInt::parse_bytes(b"ff", 16).unwrap();
871 /// assert_eq!(i.to_str_radix(16), "ff");
872 /// ```
873 #[inline]
874 pub fn to_str_radix(&self, radix: u32) -> String {
875 let mut v = to_str_radix_reversed(&self.data, radix);
876
877 if self.is_negative() {
878 v.push(b'-');
879 }
880
881 v.reverse();
882 unsafe { String::from_utf8_unchecked(v) }
883 }
884
885 /// Returns the integer in the requested base in big-endian digit order.
886 /// The output is not given in a human readable alphabet but as a zero
887 /// based u8 number.
888 /// `radix` must be in the range `2...256`.
889 ///
890 /// # Examples
891 ///
892 /// ```
893 /// use num_bigint::{BigInt, Sign};
894 ///
895 /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_be(159),
896 /// (Sign::Minus, vec![2, 94, 27]));
897 /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27
898 /// ```
899 #[inline]
900 pub fn to_radix_be(&self, radix: u32) -> (Sign, Vec<u8>) {
901 (self.sign, self.data.to_radix_be(radix))
902 }
903
904 /// Returns the integer in the requested base in little-endian digit order.
905 /// The output is not given in a human readable alphabet but as a zero
906 /// based u8 number.
907 /// `radix` must be in the range `2...256`.
908 ///
909 /// # Examples
910 ///
911 /// ```
912 /// use num_bigint::{BigInt, Sign};
913 ///
914 /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_le(159),
915 /// (Sign::Minus, vec![27, 94, 2]));
916 /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2)
917 /// ```
918 #[inline]
919 pub fn to_radix_le(&self, radix: u32) -> (Sign, Vec<u8>) {
920 (self.sign, self.data.to_radix_le(radix))
921 }
922
923 /// Returns the sign of the `BigInt` as a `Sign`.
924 ///
925 /// # Examples
926 ///
927 /// ```
928 /// use num_bigint::{BigInt, Sign};
929 /// use num_traits::Zero;
930 ///
931 /// assert_eq!(BigInt::from(1234).sign(), Sign::Plus);
932 /// assert_eq!(BigInt::from(-4321).sign(), Sign::Minus);
933 /// assert_eq!(BigInt::zero().sign(), Sign::NoSign);
934 /// ```
935 #[inline]
936 pub fn sign(&self) -> Sign {
937 self.sign
938 }
939
940 /// Returns the magnitude of the `BigInt` as a `BigUint`.
941 ///
942 /// # Examples
943 ///
944 /// ```
945 /// use num_bigint::{BigInt, BigUint};
946 /// use num_traits::Zero;
947 ///
948 /// assert_eq!(BigInt::from(1234).magnitude(), &BigUint::from(1234u32));
949 /// assert_eq!(BigInt::from(-4321).magnitude(), &BigUint::from(4321u32));
950 /// assert!(BigInt::zero().magnitude().is_zero());
951 /// ```
952 #[inline]
953 pub fn magnitude(&self) -> &BigUint {
954 &self.data
955 }
956
957 /// Convert this `BigInt` into its `Sign` and `BigUint` magnitude,
958 /// the reverse of `BigInt::from_biguint`.
959 ///
960 /// # Examples
961 ///
962 /// ```
963 /// use num_bigint::{BigInt, BigUint, Sign};
964 /// use num_traits::Zero;
965 ///
966 /// assert_eq!(BigInt::from(1234).into_parts(), (Sign::Plus, BigUint::from(1234u32)));
967 /// assert_eq!(BigInt::from(-4321).into_parts(), (Sign::Minus, BigUint::from(4321u32)));
968 /// assert_eq!(BigInt::zero().into_parts(), (Sign::NoSign, BigUint::zero()));
969 /// ```
970 #[inline]
971 pub fn into_parts(self) -> (Sign, BigUint) {
972 (self.sign, self.data)
973 }
974
975 /// Determines the fewest bits necessary to express the `BigInt`,
976 /// not including the sign.
977 #[inline]
978 pub fn bits(&self) -> u64 {
979 self.data.bits()
980 }
981
982 /// Converts this `BigInt` into a `BigUint`, if it's not negative.
983 #[inline]
984 pub fn to_biguint(&self) -> Option<BigUint> {
985 match self.sign {
986 Plus => Some(self.data.clone()),
987 NoSign => Some(Zero::zero()),
988 Minus => None,
989 }
990 }
991
992 #[inline]
993 pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
994 Some(self + v)
995 }
996
997 #[inline]
998 pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
999 Some(self - v)
1000 }
1001
1002 #[inline]
1003 pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
1004 Some(self * v)
1005 }
1006
1007 #[inline]
1008 pub fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
1009 if v.is_zero() {
1010 return None;
1011 }
1012 Some(self / v)
1013 }
1014
1015 /// Returns `self ^ exponent`.
1016 pub fn pow(&self, exponent: u32) -> Self {
1017 Pow::pow(self, exponent)
1018 }
1019
1020 /// Returns `(self ^ exponent) mod modulus`
1021 ///
1022 /// Note that this rounds like `mod_floor`, not like the `%` operator,
1023 /// which makes a difference when given a negative `self` or `modulus`.
1024 /// The result will be in the interval `[0, modulus)` for `modulus > 0`,
1025 /// or in the interval `(modulus, 0]` for `modulus < 0`
1026 ///
1027 /// Panics if the exponent is negative or the modulus is zero.
1028 pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self {
1029 power::modpow(self, exponent, modulus)
1030 }
1031
1032 /// Returns the truncated principal square root of `self` --
1033 /// see [Roots::sqrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.sqrt).
1034 pub fn sqrt(&self) -> Self {
1035 Roots::sqrt(self)
1036 }
1037
1038 /// Returns the truncated principal cube root of `self` --
1039 /// see [Roots::cbrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.cbrt).
1040 pub fn cbrt(&self) -> Self {
1041 Roots::cbrt(self)
1042 }
1043
1044 /// Returns the truncated principal `n`th root of `self` --
1045 /// See [Roots::nth_root](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#tymethod.nth_root).
1046 pub fn nth_root(&self, n: u32) -> Self {
1047 Roots::nth_root(self, n)
1048 }
1049
1050 /// Returns the number of least-significant bits that are zero,
1051 /// or `None` if the entire number is zero.
1052 pub fn trailing_zeros(&self) -> Option<u64> {
1053 self.data.trailing_zeros()
1054 }
1055
1056 /// Returns whether the bit in position `bit` is set,
1057 /// using the two's complement for negative numbers
1058 pub fn bit(&self, bit: u64) -> bool {
1059 if self.is_negative() {
1060 // Let the binary representation of a number be
1061 // ... 0 x 1 0 ... 0
1062 // Then the two's complement is
1063 // ... 1 !x 1 0 ... 0
1064 // where !x is obtained from x by flipping each bit
1065 if bit >= u64::from(crate::big_digit::BITS) * self.len() as u64 {
1066 true
1067 } else {
1068 let trailing_zeros = self.data.trailing_zeros().unwrap();
1069 match Ord::cmp(&bit, &trailing_zeros) {
1070 Ordering::Less => false,
1071 Ordering::Equal => true,
1072 Ordering::Greater => !self.data.bit(bit),
1073 }
1074 }
1075 } else {
1076 self.data.bit(bit)
1077 }
1078 }
1079
1080 /// Sets or clears the bit in the given position,
1081 /// using the two's complement for negative numbers
1082 ///
1083 /// Note that setting/clearing a bit (for positive/negative numbers,
1084 /// respectively) greater than the current bit length, a reallocation
1085 /// may be needed to store the new digits
1086 pub fn set_bit(&mut self, bit: u64, value: bool) {
1087 match self.sign {
1088 Sign::Plus => self.data.set_bit(bit, value),
1089 Sign::Minus => bits::set_negative_bit(self, bit, value),
1090 Sign::NoSign => {
1091 if value {
1092 self.data.set_bit(bit, true);
1093 self.sign = Sign::Plus;
1094 } else {
1095 // Clearing a bit for zero is a no-op
1096 }
1097 }
1098 }
1099 // The top bit may have been cleared, so normalize
1100 self.normalize();
1101 }
1102}
1103
1104#[test]
1105fn test_from_biguint() {
1106 fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) {
1107 let inp = BigInt::from_biguint(inp_s, BigUint::from(inp_n));
1108 let ans = BigInt {
1109 sign: ans_s,
1110 data: BigUint::from(ans_n),
1111 };
1112 assert_eq!(inp, ans);
1113 }
1114 check(Plus, 1, Plus, 1);
1115 check(Plus, 0, NoSign, 0);
1116 check(Minus, 1, Minus, 1);
1117 check(NoSign, 1, NoSign, 0);
1118}
1119
1120#[test]
1121fn test_from_slice() {
1122 fn check(inp_s: Sign, inp_n: u32, ans_s: Sign, ans_n: u32) {
1123 let inp = BigInt::from_slice(inp_s, &[inp_n]);
1124 let ans = BigInt {
1125 sign: ans_s,
1126 data: BigUint::from(ans_n),
1127 };
1128 assert_eq!(inp, ans);
1129 }
1130 check(Plus, 1, Plus, 1);
1131 check(Plus, 0, NoSign, 0);
1132 check(Minus, 1, Minus, 1);
1133 check(NoSign, 1, NoSign, 0);
1134}
1135
1136#[test]
1137fn test_assign_from_slice() {
1138 fn check(inp_s: Sign, inp_n: u32, ans_s: Sign, ans_n: u32) {
1139 let mut inp = BigInt::from_slice(Minus, &[2627_u32, 0_u32, 9182_u32, 42_u32]);
1140 inp.assign_from_slice(inp_s, &[inp_n]);
1141 let ans = BigInt {
1142 sign: ans_s,
1143 data: BigUint::from(ans_n),
1144 };
1145 assert_eq!(inp, ans);
1146 }
1147 check(Plus, 1, Plus, 1);
1148 check(Plus, 0, NoSign, 0);
1149 check(Minus, 1, Minus, 1);
1150 check(NoSign, 1, NoSign, 0);
1151}