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