1 #[allow(deprecated, unused_imports)]
2 use std::ascii::AsciiExt;
3 use std::cmp::Ordering::{self, Equal, Greater, Less};
4 use std::default::Default;
5 use std::fmt;
6 use std::iter::{Product, Sum};
7 use std::mem;
8 use std::ops::{
9     Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign,
10     Mul, MulAssign, Neg, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign,
11 };
12 use std::str::{self, FromStr};
13 #[cfg(has_i128)]
14 use std::{i128, u128};
15 use std::{i64, u64};
16 
17 #[cfg(feature = "serde")]
18 use serde;
19 
20 use integer::{Integer, Roots};
21 use traits::{
22     CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, FromPrimitive, Num, One, Pow, Signed,
23     ToPrimitive, Zero,
24 };
25 
26 use self::Sign::{Minus, NoSign, Plus};
27 
28 use super::ParseBigIntError;
29 use big_digit::{self, BigDigit, DoubleBigDigit};
30 use biguint;
31 use biguint::to_str_radix_reversed;
32 use biguint::{BigUint, IntDigits};
33 
34 use IsizePromotion;
35 use UsizePromotion;
36 
37 #[cfg(feature = "quickcheck")]
38 use quickcheck::{Arbitrary, Gen};
39 
40 /// A Sign is a `BigInt`'s composing element.
41 #[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, Hash)]
42 pub enum Sign {
43     Minus,
44     NoSign,
45     Plus,
46 }
47 
48 impl Neg for Sign {
49     type Output = Sign;
50 
51     /// Negate Sign value.
52     #[inline]
neg(self) -> Sign53     fn neg(self) -> Sign {
54         match self {
55             Minus => Plus,
56             NoSign => NoSign,
57             Plus => Minus,
58         }
59     }
60 }
61 
62 impl Mul<Sign> for Sign {
63     type Output = Sign;
64 
65     #[inline]
mul(self, other: Sign) -> Sign66     fn mul(self, other: Sign) -> Sign {
67         match (self, other) {
68             (NoSign, _) | (_, NoSign) => NoSign,
69             (Plus, Plus) | (Minus, Minus) => Plus,
70             (Plus, Minus) | (Minus, Plus) => Minus,
71         }
72     }
73 }
74 
75 #[cfg(feature = "serde")]
76 impl serde::Serialize for Sign {
serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer,77     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
78     where
79         S: serde::Serializer,
80     {
81         // Note: do not change the serialization format, or it may break
82         // forward and backward compatibility of serialized data!
83         match *self {
84             Sign::Minus => (-1i8).serialize(serializer),
85             Sign::NoSign => 0i8.serialize(serializer),
86             Sign::Plus => 1i8.serialize(serializer),
87         }
88     }
89 }
90 
91 #[cfg(feature = "serde")]
92 impl<'de> serde::Deserialize<'de> for Sign {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>,93     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
94     where
95         D: serde::Deserializer<'de>,
96     {
97         use serde::de::Error;
98         use serde::de::Unexpected;
99 
100         let sign: i8 = serde::Deserialize::deserialize(deserializer)?;
101         match sign {
102             -1 => Ok(Sign::Minus),
103             0 => Ok(Sign::NoSign),
104             1 => Ok(Sign::Plus),
105             _ => Err(D::Error::invalid_value(
106                 Unexpected::Signed(sign.into()),
107                 &"a sign of -1, 0, or 1",
108             )),
109         }
110     }
111 }
112 
113 /// A big signed integer type.
114 #[derive(Clone, Debug, Hash)]
115 pub struct BigInt {
116     sign: Sign,
117     data: BigUint,
118 }
119 
120 #[cfg(feature = "quickcheck")]
121 impl Arbitrary for BigInt {
arbitrary<G: Gen>(g: &mut G) -> Self122     fn arbitrary<G: Gen>(g: &mut G) -> Self {
123         let positive = bool::arbitrary(g);
124         let sign = if positive { Sign::Plus } else { Sign::Minus };
125         Self::from_biguint(sign, BigUint::arbitrary(g))
126     }
127 
128     #[allow(bare_trait_objects)] // `dyn` needs Rust 1.27 to parse, even when cfg-disabled
shrink(&self) -> Box<Iterator<Item = Self>>129     fn shrink(&self) -> Box<Iterator<Item = Self>> {
130         let sign = self.sign();
131         let unsigned_shrink = self.data.shrink();
132         Box::new(unsigned_shrink.map(move |x| BigInt::from_biguint(sign, x)))
133     }
134 }
135 
136 /// Return the magnitude of a `BigInt`.
137 ///
138 /// This is in a private module, pseudo pub(crate)
139 #[cfg(feature = "rand")]
magnitude(i: &BigInt) -> &BigUint140 pub fn magnitude(i: &BigInt) -> &BigUint {
141     &i.data
142 }
143 
144 /// Return the owned magnitude of a `BigInt`.
145 ///
146 /// This is in a private module, pseudo pub(crate)
147 #[cfg(feature = "rand")]
into_magnitude(i: BigInt) -> BigUint148 pub fn into_magnitude(i: BigInt) -> BigUint {
149     i.data
150 }
151 
152 impl PartialEq for BigInt {
153     #[inline]
eq(&self, other: &BigInt) -> bool154     fn eq(&self, other: &BigInt) -> bool {
155         self.cmp(other) == Equal
156     }
157 }
158 
159 impl Eq for BigInt {}
160 
161 impl PartialOrd for BigInt {
162     #[inline]
partial_cmp(&self, other: &BigInt) -> Option<Ordering>163     fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
164         Some(self.cmp(other))
165     }
166 }
167 
168 impl Ord for BigInt {
169     #[inline]
cmp(&self, other: &BigInt) -> Ordering170     fn cmp(&self, other: &BigInt) -> Ordering {
171         let scmp = self.sign.cmp(&other.sign);
172         if scmp != Equal {
173             return scmp;
174         }
175 
176         match self.sign {
177             NoSign => Equal,
178             Plus => self.data.cmp(&other.data),
179             Minus => other.data.cmp(&self.data),
180         }
181     }
182 }
183 
184 impl Default for BigInt {
185     #[inline]
default() -> BigInt186     fn default() -> BigInt {
187         Zero::zero()
188     }
189 }
190 
191 impl fmt::Display for BigInt {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result192     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
193         f.pad_integral(!self.is_negative(), "", &self.data.to_str_radix(10))
194     }
195 }
196 
197 impl fmt::Binary for BigInt {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result198     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
199         f.pad_integral(!self.is_negative(), "0b", &self.data.to_str_radix(2))
200     }
201 }
202 
203 impl fmt::Octal for BigInt {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result204     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
205         f.pad_integral(!self.is_negative(), "0o", &self.data.to_str_radix(8))
206     }
207 }
208 
209 impl fmt::LowerHex for BigInt {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result210     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
211         f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16))
212     }
213 }
214 
215 impl fmt::UpperHex for BigInt {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result216     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
217         let mut s = self.data.to_str_radix(16);
218         s.make_ascii_uppercase();
219         f.pad_integral(!self.is_negative(), "0x", &s)
220     }
221 }
222 
223 // Negation in two's complement.
224 // acc must be initialized as 1 for least-significant digit.
225 //
226 // When negating, a carry (acc == 1) means that all the digits
227 // considered to this point were zero. This means that if all the
228 // digits of a negative BigInt have been considered, carry must be
229 // zero as we cannot have negative zero.
230 //
231 //    01 -> ...f    ff
232 //    ff -> ...f    01
233 // 01 00 -> ...f ff 00
234 // 01 01 -> ...f fe ff
235 // 01 ff -> ...f fe 01
236 // ff 00 -> ...f 01 00
237 // ff 01 -> ...f 00 ff
238 // ff ff -> ...f 00 01
239 #[inline]
negate_carry(a: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit240 fn negate_carry(a: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit {
241     *acc += DoubleBigDigit::from(!a);
242     let lo = *acc as BigDigit;
243     *acc >>= big_digit::BITS;
244     lo
245 }
246 
247 // !-2 = !...f fe = ...0 01 = +1
248 // !-1 = !...f ff = ...0 00 =  0
249 // ! 0 = !...0 00 = ...f ff = -1
250 // !+1 = !...0 01 = ...f fe = -2
251 impl Not for BigInt {
252     type Output = BigInt;
253 
not(mut self) -> BigInt254     fn not(mut self) -> BigInt {
255         match self.sign {
256             NoSign | Plus => {
257                 self.data += 1u32;
258                 self.sign = Minus;
259             }
260             Minus => {
261                 self.data -= 1u32;
262                 self.sign = if self.data.is_zero() { NoSign } else { Plus };
263             }
264         }
265         self
266     }
267 }
268 
269 impl<'a> Not for &'a BigInt {
270     type Output = BigInt;
271 
not(self) -> BigInt272     fn not(self) -> BigInt {
273         match self.sign {
274             NoSign | Plus => BigInt::from_biguint(Minus, &self.data + 1u32),
275             Minus => BigInt::from_biguint(Plus, &self.data - 1u32),
276         }
277     }
278 }
279 
280 // + 1 & -ff = ...0 01 & ...f 01 = ...0 01 = + 1
281 // +ff & - 1 = ...0 ff & ...f ff = ...0 ff = +ff
282 // answer is pos, has length of a
bitand_pos_neg(a: &mut Vec<BigDigit>, b: &[BigDigit])283 fn bitand_pos_neg(a: &mut Vec<BigDigit>, b: &[BigDigit]) {
284     let mut carry_b = 1;
285     for (ai, &bi) in a.iter_mut().zip(b.iter()) {
286         let twos_b = negate_carry(bi, &mut carry_b);
287         *ai &= twos_b;
288     }
289     debug_assert!(b.len() > a.len() || carry_b == 0);
290 }
291 
292 // - 1 & +ff = ...f ff & ...0 ff = ...0 ff = +ff
293 // -ff & + 1 = ...f 01 & ...0 01 = ...0 01 = + 1
294 // answer is pos, has length of b
bitand_neg_pos(a: &mut Vec<BigDigit>, b: &[BigDigit])295 fn bitand_neg_pos(a: &mut Vec<BigDigit>, b: &[BigDigit]) {
296     let mut carry_a = 1;
297     for (ai, &bi) in a.iter_mut().zip(b.iter()) {
298         let twos_a = negate_carry(*ai, &mut carry_a);
299         *ai = twos_a & bi;
300     }
301     debug_assert!(a.len() > b.len() || carry_a == 0);
302     if a.len() > b.len() {
303         a.truncate(b.len());
304     } else if b.len() > a.len() {
305         let extra = &b[a.len()..];
306         a.extend(extra.iter().cloned());
307     }
308 }
309 
310 // - 1 & -ff = ...f ff & ...f 01 = ...f 01 = - ff
311 // -ff & - 1 = ...f 01 & ...f ff = ...f 01 = - ff
312 // -ff & -fe = ...f 01 & ...f 02 = ...f 00 = -100
313 // answer is neg, has length of longest with a possible carry
bitand_neg_neg(a: &mut Vec<BigDigit>, b: &[BigDigit])314 fn bitand_neg_neg(a: &mut Vec<BigDigit>, b: &[BigDigit]) {
315     let mut carry_a = 1;
316     let mut carry_b = 1;
317     let mut carry_and = 1;
318     for (ai, &bi) in a.iter_mut().zip(b.iter()) {
319         let twos_a = negate_carry(*ai, &mut carry_a);
320         let twos_b = negate_carry(bi, &mut carry_b);
321         *ai = negate_carry(twos_a & twos_b, &mut carry_and);
322     }
323     debug_assert!(a.len() > b.len() || carry_a == 0);
324     debug_assert!(b.len() > a.len() || carry_b == 0);
325     if a.len() > b.len() {
326         for ai in a[b.len()..].iter_mut() {
327             let twos_a = negate_carry(*ai, &mut carry_a);
328             *ai = negate_carry(twos_a, &mut carry_and);
329         }
330         debug_assert!(carry_a == 0);
331     } else if b.len() > a.len() {
332         let extra = &b[a.len()..];
333         a.extend(extra.iter().map(|&bi| {
334             let twos_b = negate_carry(bi, &mut carry_b);
335             negate_carry(twos_b, &mut carry_and)
336         }));
337         debug_assert!(carry_b == 0);
338     }
339     if carry_and != 0 {
340         a.push(1);
341     }
342 }
343 
344 forward_val_val_binop!(impl BitAnd for BigInt, bitand);
345 forward_ref_val_binop!(impl BitAnd for BigInt, bitand);
346 
347 // do not use forward_ref_ref_binop_commutative! for bitand so that we can
348 // clone as needed, avoiding over-allocation
349 impl<'a, 'b> BitAnd<&'b BigInt> for &'a BigInt {
350     type Output = BigInt;
351 
352     #[inline]
bitand(self, other: &BigInt) -> BigInt353     fn bitand(self, other: &BigInt) -> BigInt {
354         match (self.sign, other.sign) {
355             (NoSign, _) | (_, NoSign) => BigInt::from_slice(NoSign, &[]),
356             (Plus, Plus) => BigInt::from_biguint(Plus, &self.data & &other.data),
357             (Plus, Minus) => self.clone() & other,
358             (Minus, Plus) => other.clone() & self,
359             (Minus, Minus) => {
360                 // forward to val-ref, choosing the larger to clone
361                 if self.len() >= other.len() {
362                     self.clone() & other
363                 } else {
364                     other.clone() & self
365                 }
366             }
367         }
368     }
369 }
370 
371 impl<'a> BitAnd<&'a BigInt> for BigInt {
372     type Output = BigInt;
373 
374     #[inline]
bitand(mut self, other: &BigInt) -> BigInt375     fn bitand(mut self, other: &BigInt) -> BigInt {
376         self &= other;
377         self
378     }
379 }
380 
381 forward_val_assign!(impl BitAndAssign for BigInt, bitand_assign);
382 
383 impl<'a> BitAndAssign<&'a BigInt> for BigInt {
bitand_assign(&mut self, other: &BigInt)384     fn bitand_assign(&mut self, other: &BigInt) {
385         match (self.sign, other.sign) {
386             (NoSign, _) => {}
387             (_, NoSign) => self.assign_from_slice(NoSign, &[]),
388             (Plus, Plus) => {
389                 self.data &= &other.data;
390                 if self.data.is_zero() {
391                     self.sign = NoSign;
392                 }
393             }
394             (Plus, Minus) => {
395                 bitand_pos_neg(self.digits_mut(), other.digits());
396                 self.normalize();
397             }
398             (Minus, Plus) => {
399                 bitand_neg_pos(self.digits_mut(), other.digits());
400                 self.sign = Plus;
401                 self.normalize();
402             }
403             (Minus, Minus) => {
404                 bitand_neg_neg(self.digits_mut(), other.digits());
405                 self.normalize();
406             }
407         }
408     }
409 }
410 
411 // + 1 | -ff = ...0 01 | ...f 01 = ...f 01 = -ff
412 // +ff | - 1 = ...0 ff | ...f ff = ...f ff = - 1
413 // answer is neg, has length of b
bitor_pos_neg(a: &mut Vec<BigDigit>, b: &[BigDigit])414 fn bitor_pos_neg(a: &mut Vec<BigDigit>, b: &[BigDigit]) {
415     let mut carry_b = 1;
416     let mut carry_or = 1;
417     for (ai, &bi) in a.iter_mut().zip(b.iter()) {
418         let twos_b = negate_carry(bi, &mut carry_b);
419         *ai = negate_carry(*ai | twos_b, &mut carry_or);
420     }
421     debug_assert!(b.len() > a.len() || carry_b == 0);
422     if a.len() > b.len() {
423         a.truncate(b.len());
424     } else if b.len() > a.len() {
425         let extra = &b[a.len()..];
426         a.extend(extra.iter().map(|&bi| {
427             let twos_b = negate_carry(bi, &mut carry_b);
428             negate_carry(twos_b, &mut carry_or)
429         }));
430         debug_assert!(carry_b == 0);
431     }
432     // for carry_or to be non-zero, we would need twos_b == 0
433     debug_assert!(carry_or == 0);
434 }
435 
436 // - 1 | +ff = ...f ff | ...0 ff = ...f ff = - 1
437 // -ff | + 1 = ...f 01 | ...0 01 = ...f 01 = -ff
438 // answer is neg, has length of a
bitor_neg_pos(a: &mut Vec<BigDigit>, b: &[BigDigit])439 fn bitor_neg_pos(a: &mut Vec<BigDigit>, b: &[BigDigit]) {
440     let mut carry_a = 1;
441     let mut carry_or = 1;
442     for (ai, &bi) in a.iter_mut().zip(b.iter()) {
443         let twos_a = negate_carry(*ai, &mut carry_a);
444         *ai = negate_carry(twos_a | bi, &mut carry_or);
445     }
446     debug_assert!(a.len() > b.len() || carry_a == 0);
447     if a.len() > b.len() {
448         for ai in a[b.len()..].iter_mut() {
449             let twos_a = negate_carry(*ai, &mut carry_a);
450             *ai = negate_carry(twos_a, &mut carry_or);
451         }
452         debug_assert!(carry_a == 0);
453     }
454     // for carry_or to be non-zero, we would need twos_a == 0
455     debug_assert!(carry_or == 0);
456 }
457 
458 // - 1 | -ff = ...f ff | ...f 01 = ...f ff = -1
459 // -ff | - 1 = ...f 01 | ...f ff = ...f ff = -1
460 // answer is neg, has length of shortest
bitor_neg_neg(a: &mut Vec<BigDigit>, b: &[BigDigit])461 fn bitor_neg_neg(a: &mut Vec<BigDigit>, b: &[BigDigit]) {
462     let mut carry_a = 1;
463     let mut carry_b = 1;
464     let mut carry_or = 1;
465     for (ai, &bi) in a.iter_mut().zip(b.iter()) {
466         let twos_a = negate_carry(*ai, &mut carry_a);
467         let twos_b = negate_carry(bi, &mut carry_b);
468         *ai = negate_carry(twos_a | twos_b, &mut carry_or);
469     }
470     debug_assert!(a.len() > b.len() || carry_a == 0);
471     debug_assert!(b.len() > a.len() || carry_b == 0);
472     if a.len() > b.len() {
473         a.truncate(b.len());
474     }
475     // for carry_or to be non-zero, we would need twos_a == 0 or twos_b == 0
476     debug_assert!(carry_or == 0);
477 }
478 
479 forward_val_val_binop!(impl BitOr for BigInt, bitor);
480 forward_ref_val_binop!(impl BitOr for BigInt, bitor);
481 
482 // do not use forward_ref_ref_binop_commutative! for bitor so that we can
483 // clone as needed, avoiding over-allocation
484 impl<'a, 'b> BitOr<&'b BigInt> for &'a BigInt {
485     type Output = BigInt;
486 
487     #[inline]
bitor(self, other: &BigInt) -> BigInt488     fn bitor(self, other: &BigInt) -> BigInt {
489         match (self.sign, other.sign) {
490             (NoSign, _) => other.clone(),
491             (_, NoSign) => self.clone(),
492             (Plus, Plus) => BigInt::from_biguint(Plus, &self.data | &other.data),
493             (Plus, Minus) => other.clone() | self,
494             (Minus, Plus) => self.clone() | other,
495             (Minus, Minus) => {
496                 // forward to val-ref, choosing the smaller to clone
497                 if self.len() <= other.len() {
498                     self.clone() | other
499                 } else {
500                     other.clone() | self
501                 }
502             }
503         }
504     }
505 }
506 
507 impl<'a> BitOr<&'a BigInt> for BigInt {
508     type Output = BigInt;
509 
510     #[inline]
bitor(mut self, other: &BigInt) -> BigInt511     fn bitor(mut self, other: &BigInt) -> BigInt {
512         self |= other;
513         self
514     }
515 }
516 
517 forward_val_assign!(impl BitOrAssign for BigInt, bitor_assign);
518 
519 impl<'a> BitOrAssign<&'a BigInt> for BigInt {
bitor_assign(&mut self, other: &BigInt)520     fn bitor_assign(&mut self, other: &BigInt) {
521         match (self.sign, other.sign) {
522             (_, NoSign) => {}
523             (NoSign, _) => self.assign_from_slice(other.sign, other.digits()),
524             (Plus, Plus) => self.data |= &other.data,
525             (Plus, Minus) => {
526                 bitor_pos_neg(self.digits_mut(), other.digits());
527                 self.sign = Minus;
528                 self.normalize();
529             }
530             (Minus, Plus) => {
531                 bitor_neg_pos(self.digits_mut(), other.digits());
532                 self.normalize();
533             }
534             (Minus, Minus) => {
535                 bitor_neg_neg(self.digits_mut(), other.digits());
536                 self.normalize();
537             }
538         }
539     }
540 }
541 
542 // + 1 ^ -ff = ...0 01 ^ ...f 01 = ...f 00 = -100
543 // +ff ^ - 1 = ...0 ff ^ ...f ff = ...f 00 = -100
544 // answer is neg, has length of longest with a possible carry
bitxor_pos_neg(a: &mut Vec<BigDigit>, b: &[BigDigit])545 fn bitxor_pos_neg(a: &mut Vec<BigDigit>, b: &[BigDigit]) {
546     let mut carry_b = 1;
547     let mut carry_xor = 1;
548     for (ai, &bi) in a.iter_mut().zip(b.iter()) {
549         let twos_b = negate_carry(bi, &mut carry_b);
550         *ai = negate_carry(*ai ^ twos_b, &mut carry_xor);
551     }
552     debug_assert!(b.len() > a.len() || carry_b == 0);
553     if a.len() > b.len() {
554         for ai in a[b.len()..].iter_mut() {
555             let twos_b = !0;
556             *ai = negate_carry(*ai ^ twos_b, &mut carry_xor);
557         }
558     } else if b.len() > a.len() {
559         let extra = &b[a.len()..];
560         a.extend(extra.iter().map(|&bi| {
561             let twos_b = negate_carry(bi, &mut carry_b);
562             negate_carry(twos_b, &mut carry_xor)
563         }));
564         debug_assert!(carry_b == 0);
565     }
566     if carry_xor != 0 {
567         a.push(1);
568     }
569 }
570 
571 // - 1 ^ +ff = ...f ff ^ ...0 ff = ...f 00 = -100
572 // -ff ^ + 1 = ...f 01 ^ ...0 01 = ...f 00 = -100
573 // answer is neg, has length of longest with a possible carry
bitxor_neg_pos(a: &mut Vec<BigDigit>, b: &[BigDigit])574 fn bitxor_neg_pos(a: &mut Vec<BigDigit>, b: &[BigDigit]) {
575     let mut carry_a = 1;
576     let mut carry_xor = 1;
577     for (ai, &bi) in a.iter_mut().zip(b.iter()) {
578         let twos_a = negate_carry(*ai, &mut carry_a);
579         *ai = negate_carry(twos_a ^ bi, &mut carry_xor);
580     }
581     debug_assert!(a.len() > b.len() || carry_a == 0);
582     if a.len() > b.len() {
583         for ai in a[b.len()..].iter_mut() {
584             let twos_a = negate_carry(*ai, &mut carry_a);
585             *ai = negate_carry(twos_a, &mut carry_xor);
586         }
587         debug_assert!(carry_a == 0);
588     } else if b.len() > a.len() {
589         let extra = &b[a.len()..];
590         a.extend(extra.iter().map(|&bi| {
591             let twos_a = !0;
592             negate_carry(twos_a ^ bi, &mut carry_xor)
593         }));
594     }
595     if carry_xor != 0 {
596         a.push(1);
597     }
598 }
599 
600 // - 1 ^ -ff = ...f ff ^ ...f 01 = ...0 fe = +fe
601 // -ff & - 1 = ...f 01 ^ ...f ff = ...0 fe = +fe
602 // answer is pos, has length of longest
bitxor_neg_neg(a: &mut Vec<BigDigit>, b: &[BigDigit])603 fn bitxor_neg_neg(a: &mut Vec<BigDigit>, b: &[BigDigit]) {
604     let mut carry_a = 1;
605     let mut carry_b = 1;
606     for (ai, &bi) in a.iter_mut().zip(b.iter()) {
607         let twos_a = negate_carry(*ai, &mut carry_a);
608         let twos_b = negate_carry(bi, &mut carry_b);
609         *ai = twos_a ^ twos_b;
610     }
611     debug_assert!(a.len() > b.len() || carry_a == 0);
612     debug_assert!(b.len() > a.len() || carry_b == 0);
613     if a.len() > b.len() {
614         for ai in a[b.len()..].iter_mut() {
615             let twos_a = negate_carry(*ai, &mut carry_a);
616             let twos_b = !0;
617             *ai = twos_a ^ twos_b;
618         }
619         debug_assert!(carry_a == 0);
620     } else if b.len() > a.len() {
621         let extra = &b[a.len()..];
622         a.extend(extra.iter().map(|&bi| {
623             let twos_a = !0;
624             let twos_b = negate_carry(bi, &mut carry_b);
625             twos_a ^ twos_b
626         }));
627         debug_assert!(carry_b == 0);
628     }
629 }
630 
631 forward_all_binop_to_val_ref_commutative!(impl BitXor for BigInt, bitxor);
632 
633 impl<'a> BitXor<&'a BigInt> for BigInt {
634     type Output = BigInt;
635 
636     #[inline]
bitxor(mut self, other: &BigInt) -> BigInt637     fn bitxor(mut self, other: &BigInt) -> BigInt {
638         self ^= other;
639         self
640     }
641 }
642 
643 forward_val_assign!(impl BitXorAssign for BigInt, bitxor_assign);
644 
645 impl<'a> BitXorAssign<&'a BigInt> for BigInt {
bitxor_assign(&mut self, other: &BigInt)646     fn bitxor_assign(&mut self, other: &BigInt) {
647         match (self.sign, other.sign) {
648             (_, NoSign) => {}
649             (NoSign, _) => self.assign_from_slice(other.sign, other.digits()),
650             (Plus, Plus) => {
651                 self.data ^= &other.data;
652                 if self.data.is_zero() {
653                     self.sign = NoSign;
654                 }
655             }
656             (Plus, Minus) => {
657                 bitxor_pos_neg(self.digits_mut(), other.digits());
658                 self.sign = Minus;
659                 self.normalize();
660             }
661             (Minus, Plus) => {
662                 bitxor_neg_pos(self.digits_mut(), other.digits());
663                 self.normalize();
664             }
665             (Minus, Minus) => {
666                 bitxor_neg_neg(self.digits_mut(), other.digits());
667                 self.sign = Plus;
668                 self.normalize();
669             }
670         }
671     }
672 }
673 
674 impl FromStr for BigInt {
675     type Err = ParseBigIntError;
676 
677     #[inline]
from_str(s: &str) -> Result<BigInt, ParseBigIntError>678     fn from_str(s: &str) -> Result<BigInt, ParseBigIntError> {
679         BigInt::from_str_radix(s, 10)
680     }
681 }
682 
683 impl Num for BigInt {
684     type FromStrRadixErr = ParseBigIntError;
685 
686     /// Creates and initializes a BigInt.
687     #[inline]
from_str_radix(mut s: &str, radix: u32) -> Result<BigInt, ParseBigIntError>688     fn from_str_radix(mut s: &str, radix: u32) -> Result<BigInt, ParseBigIntError> {
689         let sign = if s.starts_with('-') {
690             let tail = &s[1..];
691             if !tail.starts_with('+') {
692                 s = tail
693             }
694             Minus
695         } else {
696             Plus
697         };
698         let bu = BigUint::from_str_radix(s, radix)?;
699         Ok(BigInt::from_biguint(sign, bu))
700     }
701 }
702 
703 impl Shl<usize> for BigInt {
704     type Output = BigInt;
705 
706     #[inline]
shl(mut self, rhs: usize) -> BigInt707     fn shl(mut self, rhs: usize) -> BigInt {
708         self <<= rhs;
709         self
710     }
711 }
712 
713 impl<'a> Shl<usize> for &'a BigInt {
714     type Output = BigInt;
715 
716     #[inline]
shl(self, rhs: usize) -> BigInt717     fn shl(self, rhs: usize) -> BigInt {
718         BigInt::from_biguint(self.sign, &self.data << rhs)
719     }
720 }
721 
722 impl ShlAssign<usize> for BigInt {
723     #[inline]
shl_assign(&mut self, rhs: usize)724     fn shl_assign(&mut self, rhs: usize) {
725         self.data <<= rhs;
726     }
727 }
728 
729 // Negative values need a rounding adjustment if there are any ones in the
730 // bits that are getting shifted out.
shr_round_down(i: &BigInt, rhs: usize) -> bool731 fn shr_round_down(i: &BigInt, rhs: usize) -> bool {
732     i.is_negative()
733         && biguint::trailing_zeros(&i.data)
734             .map(|n| n < rhs)
735             .unwrap_or(false)
736 }
737 
738 impl Shr<usize> for BigInt {
739     type Output = BigInt;
740 
741     #[inline]
shr(mut self, rhs: usize) -> BigInt742     fn shr(mut self, rhs: usize) -> BigInt {
743         self >>= rhs;
744         self
745     }
746 }
747 
748 impl<'a> Shr<usize> for &'a BigInt {
749     type Output = BigInt;
750 
751     #[inline]
shr(self, rhs: usize) -> BigInt752     fn shr(self, rhs: usize) -> BigInt {
753         let round_down = shr_round_down(self, rhs);
754         let data = &self.data >> rhs;
755         BigInt::from_biguint(self.sign, if round_down { data + 1u8 } else { data })
756     }
757 }
758 
759 impl ShrAssign<usize> for BigInt {
760     #[inline]
shr_assign(&mut self, rhs: usize)761     fn shr_assign(&mut self, rhs: usize) {
762         let round_down = shr_round_down(self, rhs);
763         self.data >>= rhs;
764         if round_down {
765             self.data += 1u8;
766         } else if self.data.is_zero() {
767             self.sign = NoSign;
768         }
769     }
770 }
771 
772 impl Zero for BigInt {
773     #[inline]
zero() -> BigInt774     fn zero() -> BigInt {
775         BigInt::from_biguint(NoSign, Zero::zero())
776     }
777 
778     #[inline]
set_zero(&mut self)779     fn set_zero(&mut self) {
780         self.data.set_zero();
781         self.sign = NoSign;
782     }
783 
784     #[inline]
is_zero(&self) -> bool785     fn is_zero(&self) -> bool {
786         self.sign == NoSign
787     }
788 }
789 
790 impl One for BigInt {
791     #[inline]
one() -> BigInt792     fn one() -> BigInt {
793         BigInt::from_biguint(Plus, One::one())
794     }
795 
796     #[inline]
set_one(&mut self)797     fn set_one(&mut self) {
798         self.data.set_one();
799         self.sign = Plus;
800     }
801 
802     #[inline]
is_one(&self) -> bool803     fn is_one(&self) -> bool {
804         self.sign == Plus && self.data.is_one()
805     }
806 }
807 
808 impl Signed for BigInt {
809     #[inline]
abs(&self) -> BigInt810     fn abs(&self) -> BigInt {
811         match self.sign {
812             Plus | NoSign => self.clone(),
813             Minus => BigInt::from_biguint(Plus, self.data.clone()),
814         }
815     }
816 
817     #[inline]
abs_sub(&self, other: &BigInt) -> BigInt818     fn abs_sub(&self, other: &BigInt) -> BigInt {
819         if *self <= *other {
820             Zero::zero()
821         } else {
822             self - other
823         }
824     }
825 
826     #[inline]
signum(&self) -> BigInt827     fn signum(&self) -> BigInt {
828         match self.sign {
829             Plus => BigInt::from_biguint(Plus, One::one()),
830             Minus => BigInt::from_biguint(Minus, One::one()),
831             NoSign => Zero::zero(),
832         }
833     }
834 
835     #[inline]
is_positive(&self) -> bool836     fn is_positive(&self) -> bool {
837         self.sign == Plus
838     }
839 
840     #[inline]
is_negative(&self) -> bool841     fn is_negative(&self) -> bool {
842         self.sign == Minus
843     }
844 }
845 
846 /// Help function for pow
847 ///
848 /// Computes the effect of the exponent on the sign.
849 #[inline]
powsign<T: Integer>(sign: Sign, other: &T) -> Sign850 fn powsign<T: Integer>(sign: Sign, other: &T) -> Sign {
851     if other.is_zero() {
852         Plus
853     } else if sign != Minus {
854         sign
855     } else if other.is_odd() {
856         sign
857     } else {
858         -sign
859     }
860 }
861 
862 macro_rules! pow_impl {
863     ($T:ty) => {
864         impl<'a> Pow<$T> for &'a BigInt {
865             type Output = BigInt;
866 
867             #[inline]
868             fn pow(self, rhs: $T) -> BigInt {
869                 BigInt::from_biguint(powsign(self.sign, &rhs), (&self.data).pow(rhs))
870             }
871         }
872 
873         impl<'a, 'b> Pow<&'b $T> for &'a BigInt {
874             type Output = BigInt;
875 
876             #[inline]
877             fn pow(self, rhs: &$T) -> BigInt {
878                 BigInt::from_biguint(powsign(self.sign, rhs), (&self.data).pow(rhs))
879             }
880         }
881     };
882 }
883 
884 pow_impl!(u8);
885 pow_impl!(u16);
886 pow_impl!(u32);
887 pow_impl!(u64);
888 pow_impl!(usize);
889 #[cfg(has_i128)]
890 pow_impl!(u128);
891 pow_impl!(BigUint);
892 
893 // A convenience method for getting the absolute value of an i32 in a u32.
894 #[inline]
i32_abs_as_u32(a: i32) -> u32895 fn i32_abs_as_u32(a: i32) -> u32 {
896     if a == i32::min_value() {
897         a as u32
898     } else {
899         a.abs() as u32
900     }
901 }
902 
903 // A convenience method for getting the absolute value of an i64 in a u64.
904 #[inline]
i64_abs_as_u64(a: i64) -> u64905 fn i64_abs_as_u64(a: i64) -> u64 {
906     if a == i64::min_value() {
907         a as u64
908     } else {
909         a.abs() as u64
910     }
911 }
912 
913 // A convenience method for getting the absolute value of an i128 in a u128.
914 #[cfg(has_i128)]
915 #[inline]
i128_abs_as_u128(a: i128) -> u128916 fn i128_abs_as_u128(a: i128) -> u128 {
917     if a == i128::min_value() {
918         a as u128
919     } else {
920         a.abs() as u128
921     }
922 }
923 
924 // We want to forward to BigUint::add, but it's not clear how that will go until
925 // we compare both sign and magnitude.  So we duplicate this body for every
926 // val/ref combination, deferring that decision to BigUint's own forwarding.
927 macro_rules! bigint_add {
928     ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
929         match ($a.sign, $b.sign) {
930             (_, NoSign) => $a_owned,
931             (NoSign, _) => $b_owned,
932             // same sign => keep the sign with the sum of magnitudes
933             (Plus, Plus) | (Minus, Minus) => BigInt::from_biguint($a.sign, $a_data + $b_data),
934             // opposite signs => keep the sign of the larger with the difference of magnitudes
935             (Plus, Minus) | (Minus, Plus) => match $a.data.cmp(&$b.data) {
936                 Less => BigInt::from_biguint($b.sign, $b_data - $a_data),
937                 Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
938                 Equal => Zero::zero(),
939             },
940         }
941     };
942 }
943 
944 impl<'a, 'b> Add<&'b BigInt> for &'a BigInt {
945     type Output = BigInt;
946 
947     #[inline]
add(self, other: &BigInt) -> BigInt948     fn add(self, other: &BigInt) -> BigInt {
949         bigint_add!(
950             self,
951             self.clone(),
952             &self.data,
953             other,
954             other.clone(),
955             &other.data
956         )
957     }
958 }
959 
960 impl<'a> Add<BigInt> for &'a BigInt {
961     type Output = BigInt;
962 
963     #[inline]
add(self, other: BigInt) -> BigInt964     fn add(self, other: BigInt) -> BigInt {
965         bigint_add!(self, self.clone(), &self.data, other, other, other.data)
966     }
967 }
968 
969 impl<'a> Add<&'a BigInt> for BigInt {
970     type Output = BigInt;
971 
972     #[inline]
add(self, other: &BigInt) -> BigInt973     fn add(self, other: &BigInt) -> BigInt {
974         bigint_add!(self, self, self.data, other, other.clone(), &other.data)
975     }
976 }
977 
978 impl Add<BigInt> for BigInt {
979     type Output = BigInt;
980 
981     #[inline]
add(self, other: BigInt) -> BigInt982     fn add(self, other: BigInt) -> BigInt {
983         bigint_add!(self, self, self.data, other, other, other.data)
984     }
985 }
986 
987 impl<'a> AddAssign<&'a BigInt> for BigInt {
988     #[inline]
add_assign(&mut self, other: &BigInt)989     fn add_assign(&mut self, other: &BigInt) {
990         let n = mem::replace(self, BigInt::zero());
991         *self = n + other;
992     }
993 }
994 forward_val_assign!(impl AddAssign for BigInt, add_assign);
995 
996 promote_all_scalars!(impl Add for BigInt, add);
997 promote_all_scalars_assign!(impl AddAssign for BigInt, add_assign);
998 forward_all_scalar_binop_to_val_val_commutative!(impl Add<u32> for BigInt, add);
999 forward_all_scalar_binop_to_val_val_commutative!(impl Add<u64> for BigInt, add);
1000 #[cfg(has_i128)]
1001 forward_all_scalar_binop_to_val_val_commutative!(impl Add<u128> for BigInt, add);
1002 
1003 impl Add<u32> for BigInt {
1004     type Output = BigInt;
1005 
1006     #[inline]
add(self, other: u32) -> BigInt1007     fn add(self, other: u32) -> BigInt {
1008         match self.sign {
1009             NoSign => From::from(other),
1010             Plus => BigInt::from_biguint(Plus, self.data + other),
1011             Minus => match self.data.cmp(&From::from(other)) {
1012                 Equal => Zero::zero(),
1013                 Less => BigInt::from_biguint(Plus, other - self.data),
1014                 Greater => BigInt::from_biguint(Minus, self.data - other),
1015             },
1016         }
1017     }
1018 }
1019 impl AddAssign<u32> for BigInt {
1020     #[inline]
add_assign(&mut self, other: u32)1021     fn add_assign(&mut self, other: u32) {
1022         let n = mem::replace(self, BigInt::zero());
1023         *self = n + other;
1024     }
1025 }
1026 
1027 impl Add<u64> for BigInt {
1028     type Output = BigInt;
1029 
1030     #[inline]
add(self, other: u64) -> BigInt1031     fn add(self, other: u64) -> BigInt {
1032         match self.sign {
1033             NoSign => From::from(other),
1034             Plus => BigInt::from_biguint(Plus, self.data + other),
1035             Minus => match self.data.cmp(&From::from(other)) {
1036                 Equal => Zero::zero(),
1037                 Less => BigInt::from_biguint(Plus, other - self.data),
1038                 Greater => BigInt::from_biguint(Minus, self.data - other),
1039             },
1040         }
1041     }
1042 }
1043 impl AddAssign<u64> for BigInt {
1044     #[inline]
add_assign(&mut self, other: u64)1045     fn add_assign(&mut self, other: u64) {
1046         let n = mem::replace(self, BigInt::zero());
1047         *self = n + other;
1048     }
1049 }
1050 
1051 #[cfg(has_i128)]
1052 impl Add<u128> for BigInt {
1053     type Output = BigInt;
1054 
1055     #[inline]
add(self, other: u128) -> BigInt1056     fn add(self, other: u128) -> BigInt {
1057         match self.sign {
1058             NoSign => From::from(other),
1059             Plus => BigInt::from_biguint(Plus, self.data + other),
1060             Minus => match self.data.cmp(&From::from(other)) {
1061                 Equal => Zero::zero(),
1062                 Less => BigInt::from_biguint(Plus, other - self.data),
1063                 Greater => BigInt::from_biguint(Minus, self.data - other),
1064             },
1065         }
1066     }
1067 }
1068 #[cfg(has_i128)]
1069 impl AddAssign<u128> for BigInt {
1070     #[inline]
add_assign(&mut self, other: u128)1071     fn add_assign(&mut self, other: u128) {
1072         let n = mem::replace(self, BigInt::zero());
1073         *self = n + other;
1074     }
1075 }
1076 
1077 forward_all_scalar_binop_to_val_val_commutative!(impl Add<i32> for BigInt, add);
1078 forward_all_scalar_binop_to_val_val_commutative!(impl Add<i64> for BigInt, add);
1079 #[cfg(has_i128)]
1080 forward_all_scalar_binop_to_val_val_commutative!(impl Add<i128> for BigInt, add);
1081 
1082 impl Add<i32> for BigInt {
1083     type Output = BigInt;
1084 
1085     #[inline]
add(self, other: i32) -> BigInt1086     fn add(self, other: i32) -> BigInt {
1087         if other >= 0 {
1088             self + other as u32
1089         } else {
1090             self - i32_abs_as_u32(other)
1091         }
1092     }
1093 }
1094 impl AddAssign<i32> for BigInt {
1095     #[inline]
add_assign(&mut self, other: i32)1096     fn add_assign(&mut self, other: i32) {
1097         if other >= 0 {
1098             *self += other as u32;
1099         } else {
1100             *self -= i32_abs_as_u32(other);
1101         }
1102     }
1103 }
1104 
1105 impl Add<i64> for BigInt {
1106     type Output = BigInt;
1107 
1108     #[inline]
add(self, other: i64) -> BigInt1109     fn add(self, other: i64) -> BigInt {
1110         if other >= 0 {
1111             self + other as u64
1112         } else {
1113             self - i64_abs_as_u64(other)
1114         }
1115     }
1116 }
1117 impl AddAssign<i64> for BigInt {
1118     #[inline]
add_assign(&mut self, other: i64)1119     fn add_assign(&mut self, other: i64) {
1120         if other >= 0 {
1121             *self += other as u64;
1122         } else {
1123             *self -= i64_abs_as_u64(other);
1124         }
1125     }
1126 }
1127 
1128 #[cfg(has_i128)]
1129 impl Add<i128> for BigInt {
1130     type Output = BigInt;
1131 
1132     #[inline]
add(self, other: i128) -> BigInt1133     fn add(self, other: i128) -> BigInt {
1134         if other >= 0 {
1135             self + other as u128
1136         } else {
1137             self - i128_abs_as_u128(other)
1138         }
1139     }
1140 }
1141 #[cfg(has_i128)]
1142 impl AddAssign<i128> for BigInt {
1143     #[inline]
add_assign(&mut self, other: i128)1144     fn add_assign(&mut self, other: i128) {
1145         if other >= 0 {
1146             *self += other as u128;
1147         } else {
1148             *self -= i128_abs_as_u128(other);
1149         }
1150     }
1151 }
1152 
1153 // We want to forward to BigUint::sub, but it's not clear how that will go until
1154 // we compare both sign and magnitude.  So we duplicate this body for every
1155 // val/ref combination, deferring that decision to BigUint's own forwarding.
1156 macro_rules! bigint_sub {
1157     ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
1158         match ($a.sign, $b.sign) {
1159             (_, NoSign) => $a_owned,
1160             (NoSign, _) => -$b_owned,
1161             // opposite signs => keep the sign of the left with the sum of magnitudes
1162             (Plus, Minus) | (Minus, Plus) => BigInt::from_biguint($a.sign, $a_data + $b_data),
1163             // same sign => keep or toggle the sign of the left with the difference of magnitudes
1164             (Plus, Plus) | (Minus, Minus) => match $a.data.cmp(&$b.data) {
1165                 Less => BigInt::from_biguint(-$a.sign, $b_data - $a_data),
1166                 Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
1167                 Equal => Zero::zero(),
1168             },
1169         }
1170     };
1171 }
1172 
1173 impl<'a, 'b> Sub<&'b BigInt> for &'a BigInt {
1174     type Output = BigInt;
1175 
1176     #[inline]
sub(self, other: &BigInt) -> BigInt1177     fn sub(self, other: &BigInt) -> BigInt {
1178         bigint_sub!(
1179             self,
1180             self.clone(),
1181             &self.data,
1182             other,
1183             other.clone(),
1184             &other.data
1185         )
1186     }
1187 }
1188 
1189 impl<'a> Sub<BigInt> for &'a BigInt {
1190     type Output = BigInt;
1191 
1192     #[inline]
sub(self, other: BigInt) -> BigInt1193     fn sub(self, other: BigInt) -> BigInt {
1194         bigint_sub!(self, self.clone(), &self.data, other, other, other.data)
1195     }
1196 }
1197 
1198 impl<'a> Sub<&'a BigInt> for BigInt {
1199     type Output = BigInt;
1200 
1201     #[inline]
sub(self, other: &BigInt) -> BigInt1202     fn sub(self, other: &BigInt) -> BigInt {
1203         bigint_sub!(self, self, self.data, other, other.clone(), &other.data)
1204     }
1205 }
1206 
1207 impl Sub<BigInt> for BigInt {
1208     type Output = BigInt;
1209 
1210     #[inline]
sub(self, other: BigInt) -> BigInt1211     fn sub(self, other: BigInt) -> BigInt {
1212         bigint_sub!(self, self, self.data, other, other, other.data)
1213     }
1214 }
1215 
1216 impl<'a> SubAssign<&'a BigInt> for BigInt {
1217     #[inline]
sub_assign(&mut self, other: &BigInt)1218     fn sub_assign(&mut self, other: &BigInt) {
1219         let n = mem::replace(self, BigInt::zero());
1220         *self = n - other;
1221     }
1222 }
1223 forward_val_assign!(impl SubAssign for BigInt, sub_assign);
1224 
1225 promote_all_scalars!(impl Sub for BigInt, sub);
1226 promote_all_scalars_assign!(impl SubAssign for BigInt, sub_assign);
1227 forward_all_scalar_binop_to_val_val!(impl Sub<u32> for BigInt, sub);
1228 forward_all_scalar_binop_to_val_val!(impl Sub<u64> for BigInt, sub);
1229 #[cfg(has_i128)]
1230 forward_all_scalar_binop_to_val_val!(impl Sub<u128> for BigInt, sub);
1231 
1232 impl Sub<u32> for BigInt {
1233     type Output = BigInt;
1234 
1235     #[inline]
sub(self, other: u32) -> BigInt1236     fn sub(self, other: u32) -> BigInt {
1237         match self.sign {
1238             NoSign => BigInt::from_biguint(Minus, From::from(other)),
1239             Minus => BigInt::from_biguint(Minus, self.data + other),
1240             Plus => match self.data.cmp(&From::from(other)) {
1241                 Equal => Zero::zero(),
1242                 Greater => BigInt::from_biguint(Plus, self.data - other),
1243                 Less => BigInt::from_biguint(Minus, other - self.data),
1244             },
1245         }
1246     }
1247 }
1248 impl SubAssign<u32> for BigInt {
1249     #[inline]
sub_assign(&mut self, other: u32)1250     fn sub_assign(&mut self, other: u32) {
1251         let n = mem::replace(self, BigInt::zero());
1252         *self = n - other;
1253     }
1254 }
1255 
1256 impl Sub<BigInt> for u32 {
1257     type Output = BigInt;
1258 
1259     #[inline]
sub(self, other: BigInt) -> BigInt1260     fn sub(self, other: BigInt) -> BigInt {
1261         -(other - self)
1262     }
1263 }
1264 
1265 impl Sub<BigInt> for u64 {
1266     type Output = BigInt;
1267 
1268     #[inline]
sub(self, other: BigInt) -> BigInt1269     fn sub(self, other: BigInt) -> BigInt {
1270         -(other - self)
1271     }
1272 }
1273 #[cfg(has_i128)]
1274 impl Sub<BigInt> for u128 {
1275     type Output = BigInt;
1276 
1277     #[inline]
sub(self, other: BigInt) -> BigInt1278     fn sub(self, other: BigInt) -> BigInt {
1279         -(other - self)
1280     }
1281 }
1282 
1283 impl Sub<u64> for BigInt {
1284     type Output = BigInt;
1285 
1286     #[inline]
sub(self, other: u64) -> BigInt1287     fn sub(self, other: u64) -> BigInt {
1288         match self.sign {
1289             NoSign => BigInt::from_biguint(Minus, From::from(other)),
1290             Minus => BigInt::from_biguint(Minus, self.data + other),
1291             Plus => match self.data.cmp(&From::from(other)) {
1292                 Equal => Zero::zero(),
1293                 Greater => BigInt::from_biguint(Plus, self.data - other),
1294                 Less => BigInt::from_biguint(Minus, other - self.data),
1295             },
1296         }
1297     }
1298 }
1299 impl SubAssign<u64> for BigInt {
1300     #[inline]
sub_assign(&mut self, other: u64)1301     fn sub_assign(&mut self, other: u64) {
1302         let n = mem::replace(self, BigInt::zero());
1303         *self = n - other;
1304     }
1305 }
1306 
1307 #[cfg(has_i128)]
1308 impl Sub<u128> for BigInt {
1309     type Output = BigInt;
1310 
1311     #[inline]
sub(self, other: u128) -> BigInt1312     fn sub(self, other: u128) -> BigInt {
1313         match self.sign {
1314             NoSign => BigInt::from_biguint(Minus, From::from(other)),
1315             Minus => BigInt::from_biguint(Minus, self.data + other),
1316             Plus => match self.data.cmp(&From::from(other)) {
1317                 Equal => Zero::zero(),
1318                 Greater => BigInt::from_biguint(Plus, self.data - other),
1319                 Less => BigInt::from_biguint(Minus, other - self.data),
1320             },
1321         }
1322     }
1323 }
1324 #[cfg(has_i128)]
1325 impl SubAssign<u128> for BigInt {
1326     #[inline]
sub_assign(&mut self, other: u128)1327     fn sub_assign(&mut self, other: u128) {
1328         let n = mem::replace(self, BigInt::zero());
1329         *self = n - other;
1330     }
1331 }
1332 
1333 forward_all_scalar_binop_to_val_val!(impl Sub<i32> for BigInt, sub);
1334 forward_all_scalar_binop_to_val_val!(impl Sub<i64> for BigInt, sub);
1335 #[cfg(has_i128)]
1336 forward_all_scalar_binop_to_val_val!(impl Sub<i128> for BigInt, sub);
1337 
1338 impl Sub<i32> for BigInt {
1339     type Output = BigInt;
1340 
1341     #[inline]
sub(self, other: i32) -> BigInt1342     fn sub(self, other: i32) -> BigInt {
1343         if other >= 0 {
1344             self - other as u32
1345         } else {
1346             self + i32_abs_as_u32(other)
1347         }
1348     }
1349 }
1350 impl SubAssign<i32> for BigInt {
1351     #[inline]
sub_assign(&mut self, other: i32)1352     fn sub_assign(&mut self, other: i32) {
1353         if other >= 0 {
1354             *self -= other as u32;
1355         } else {
1356             *self += i32_abs_as_u32(other);
1357         }
1358     }
1359 }
1360 
1361 impl Sub<BigInt> for i32 {
1362     type Output = BigInt;
1363 
1364     #[inline]
sub(self, other: BigInt) -> BigInt1365     fn sub(self, other: BigInt) -> BigInt {
1366         if self >= 0 {
1367             self as u32 - other
1368         } else {
1369             -other - i32_abs_as_u32(self)
1370         }
1371     }
1372 }
1373 
1374 impl Sub<i64> for BigInt {
1375     type Output = BigInt;
1376 
1377     #[inline]
sub(self, other: i64) -> BigInt1378     fn sub(self, other: i64) -> BigInt {
1379         if other >= 0 {
1380             self - other as u64
1381         } else {
1382             self + i64_abs_as_u64(other)
1383         }
1384     }
1385 }
1386 impl SubAssign<i64> for BigInt {
1387     #[inline]
sub_assign(&mut self, other: i64)1388     fn sub_assign(&mut self, other: i64) {
1389         if other >= 0 {
1390             *self -= other as u64;
1391         } else {
1392             *self += i64_abs_as_u64(other);
1393         }
1394     }
1395 }
1396 
1397 impl Sub<BigInt> for i64 {
1398     type Output = BigInt;
1399 
1400     #[inline]
sub(self, other: BigInt) -> BigInt1401     fn sub(self, other: BigInt) -> BigInt {
1402         if self >= 0 {
1403             self as u64 - other
1404         } else {
1405             -other - i64_abs_as_u64(self)
1406         }
1407     }
1408 }
1409 
1410 #[cfg(has_i128)]
1411 impl Sub<i128> for BigInt {
1412     type Output = BigInt;
1413 
1414     #[inline]
sub(self, other: i128) -> BigInt1415     fn sub(self, other: i128) -> BigInt {
1416         if other >= 0 {
1417             self - other as u128
1418         } else {
1419             self + i128_abs_as_u128(other)
1420         }
1421     }
1422 }
1423 #[cfg(has_i128)]
1424 impl SubAssign<i128> for BigInt {
1425     #[inline]
sub_assign(&mut self, other: i128)1426     fn sub_assign(&mut self, other: i128) {
1427         if other >= 0 {
1428             *self -= other as u128;
1429         } else {
1430             *self += i128_abs_as_u128(other);
1431         }
1432     }
1433 }
1434 #[cfg(has_i128)]
1435 impl Sub<BigInt> for i128 {
1436     type Output = BigInt;
1437 
1438     #[inline]
sub(self, other: BigInt) -> BigInt1439     fn sub(self, other: BigInt) -> BigInt {
1440         if self >= 0 {
1441             self as u128 - other
1442         } else {
1443             -other - i128_abs_as_u128(self)
1444         }
1445     }
1446 }
1447 
1448 forward_all_binop_to_ref_ref!(impl Mul for BigInt, mul);
1449 
1450 impl<'a, 'b> Mul<&'b BigInt> for &'a BigInt {
1451     type Output = BigInt;
1452 
1453     #[inline]
mul(self, other: &BigInt) -> BigInt1454     fn mul(self, other: &BigInt) -> BigInt {
1455         BigInt::from_biguint(self.sign * other.sign, &self.data * &other.data)
1456     }
1457 }
1458 
1459 impl<'a> MulAssign<&'a BigInt> for BigInt {
1460     #[inline]
mul_assign(&mut self, other: &BigInt)1461     fn mul_assign(&mut self, other: &BigInt) {
1462         *self = &*self * other;
1463     }
1464 }
1465 forward_val_assign!(impl MulAssign for BigInt, mul_assign);
1466 
1467 promote_all_scalars!(impl Mul for BigInt, mul);
1468 promote_all_scalars_assign!(impl MulAssign for BigInt, mul_assign);
1469 forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u32> for BigInt, mul);
1470 forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u64> for BigInt, mul);
1471 #[cfg(has_i128)]
1472 forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u128> for BigInt, mul);
1473 
1474 impl Mul<u32> for BigInt {
1475     type Output = BigInt;
1476 
1477     #[inline]
mul(self, other: u32) -> BigInt1478     fn mul(self, other: u32) -> BigInt {
1479         BigInt::from_biguint(self.sign, self.data * other)
1480     }
1481 }
1482 
1483 impl MulAssign<u32> for BigInt {
1484     #[inline]
mul_assign(&mut self, other: u32)1485     fn mul_assign(&mut self, other: u32) {
1486         self.data *= other;
1487         if self.data.is_zero() {
1488             self.sign = NoSign;
1489         }
1490     }
1491 }
1492 
1493 impl Mul<u64> for BigInt {
1494     type Output = BigInt;
1495 
1496     #[inline]
mul(self, other: u64) -> BigInt1497     fn mul(self, other: u64) -> BigInt {
1498         BigInt::from_biguint(self.sign, self.data * other)
1499     }
1500 }
1501 
1502 impl MulAssign<u64> for BigInt {
1503     #[inline]
mul_assign(&mut self, other: u64)1504     fn mul_assign(&mut self, other: u64) {
1505         self.data *= other;
1506         if self.data.is_zero() {
1507             self.sign = NoSign;
1508         }
1509     }
1510 }
1511 #[cfg(has_i128)]
1512 impl Mul<u128> for BigInt {
1513     type Output = BigInt;
1514 
1515     #[inline]
mul(self, other: u128) -> BigInt1516     fn mul(self, other: u128) -> BigInt {
1517         BigInt::from_biguint(self.sign, self.data * other)
1518     }
1519 }
1520 #[cfg(has_i128)]
1521 impl MulAssign<u128> for BigInt {
1522     #[inline]
mul_assign(&mut self, other: u128)1523     fn mul_assign(&mut self, other: u128) {
1524         self.data *= other;
1525         if self.data.is_zero() {
1526             self.sign = NoSign;
1527         }
1528     }
1529 }
1530 
1531 forward_all_scalar_binop_to_val_val_commutative!(impl Mul<i32> for BigInt, mul);
1532 forward_all_scalar_binop_to_val_val_commutative!(impl Mul<i64> for BigInt, mul);
1533 #[cfg(has_i128)]
1534 forward_all_scalar_binop_to_val_val_commutative!(impl Mul<i128> for BigInt, mul);
1535 
1536 impl Mul<i32> for BigInt {
1537     type Output = BigInt;
1538 
1539     #[inline]
mul(self, other: i32) -> BigInt1540     fn mul(self, other: i32) -> BigInt {
1541         if other >= 0 {
1542             self * other as u32
1543         } else {
1544             -(self * i32_abs_as_u32(other))
1545         }
1546     }
1547 }
1548 
1549 impl MulAssign<i32> for BigInt {
1550     #[inline]
mul_assign(&mut self, other: i32)1551     fn mul_assign(&mut self, other: i32) {
1552         if other >= 0 {
1553             *self *= other as u32;
1554         } else {
1555             self.sign = -self.sign;
1556             *self *= i32_abs_as_u32(other);
1557         }
1558     }
1559 }
1560 
1561 impl Mul<i64> for BigInt {
1562     type Output = BigInt;
1563 
1564     #[inline]
mul(self, other: i64) -> BigInt1565     fn mul(self, other: i64) -> BigInt {
1566         if other >= 0 {
1567             self * other as u64
1568         } else {
1569             -(self * i64_abs_as_u64(other))
1570         }
1571     }
1572 }
1573 
1574 impl MulAssign<i64> for BigInt {
1575     #[inline]
mul_assign(&mut self, other: i64)1576     fn mul_assign(&mut self, other: i64) {
1577         if other >= 0 {
1578             *self *= other as u64;
1579         } else {
1580             self.sign = -self.sign;
1581             *self *= i64_abs_as_u64(other);
1582         }
1583     }
1584 }
1585 #[cfg(has_i128)]
1586 impl Mul<i128> for BigInt {
1587     type Output = BigInt;
1588 
1589     #[inline]
mul(self, other: i128) -> BigInt1590     fn mul(self, other: i128) -> BigInt {
1591         if other >= 0 {
1592             self * other as u128
1593         } else {
1594             -(self * i128_abs_as_u128(other))
1595         }
1596     }
1597 }
1598 #[cfg(has_i128)]
1599 impl MulAssign<i128> for BigInt {
1600     #[inline]
mul_assign(&mut self, other: i128)1601     fn mul_assign(&mut self, other: i128) {
1602         if other >= 0 {
1603             *self *= other as u128;
1604         } else {
1605             self.sign = -self.sign;
1606             *self *= i128_abs_as_u128(other);
1607         }
1608     }
1609 }
1610 
1611 forward_all_binop_to_ref_ref!(impl Div for BigInt, div);
1612 
1613 impl<'a, 'b> Div<&'b BigInt> for &'a BigInt {
1614     type Output = BigInt;
1615 
1616     #[inline]
div(self, other: &BigInt) -> BigInt1617     fn div(self, other: &BigInt) -> BigInt {
1618         let (q, _) = self.div_rem(other);
1619         q
1620     }
1621 }
1622 
1623 impl<'a> DivAssign<&'a BigInt> for BigInt {
1624     #[inline]
div_assign(&mut self, other: &BigInt)1625     fn div_assign(&mut self, other: &BigInt) {
1626         *self = &*self / other;
1627     }
1628 }
1629 forward_val_assign!(impl DivAssign for BigInt, div_assign);
1630 
1631 promote_all_scalars!(impl Div for BigInt, div);
1632 promote_all_scalars_assign!(impl DivAssign for BigInt, div_assign);
1633 forward_all_scalar_binop_to_val_val!(impl Div<u32> for BigInt, div);
1634 forward_all_scalar_binop_to_val_val!(impl Div<u64> for BigInt, div);
1635 #[cfg(has_i128)]
1636 forward_all_scalar_binop_to_val_val!(impl Div<u128> for BigInt, div);
1637 
1638 impl Div<u32> for BigInt {
1639     type Output = BigInt;
1640 
1641     #[inline]
div(self, other: u32) -> BigInt1642     fn div(self, other: u32) -> BigInt {
1643         BigInt::from_biguint(self.sign, self.data / other)
1644     }
1645 }
1646 
1647 impl DivAssign<u32> for BigInt {
1648     #[inline]
div_assign(&mut self, other: u32)1649     fn div_assign(&mut self, other: u32) {
1650         self.data /= other;
1651         if self.data.is_zero() {
1652             self.sign = NoSign;
1653         }
1654     }
1655 }
1656 
1657 impl Div<BigInt> for u32 {
1658     type Output = BigInt;
1659 
1660     #[inline]
div(self, other: BigInt) -> BigInt1661     fn div(self, other: BigInt) -> BigInt {
1662         BigInt::from_biguint(other.sign, self / other.data)
1663     }
1664 }
1665 
1666 impl Div<u64> for BigInt {
1667     type Output = BigInt;
1668 
1669     #[inline]
div(self, other: u64) -> BigInt1670     fn div(self, other: u64) -> BigInt {
1671         BigInt::from_biguint(self.sign, self.data / other)
1672     }
1673 }
1674 
1675 impl DivAssign<u64> for BigInt {
1676     #[inline]
div_assign(&mut self, other: u64)1677     fn div_assign(&mut self, other: u64) {
1678         self.data /= other;
1679         if self.data.is_zero() {
1680             self.sign = NoSign;
1681         }
1682     }
1683 }
1684 
1685 impl Div<BigInt> for u64 {
1686     type Output = BigInt;
1687 
1688     #[inline]
div(self, other: BigInt) -> BigInt1689     fn div(self, other: BigInt) -> BigInt {
1690         BigInt::from_biguint(other.sign, self / other.data)
1691     }
1692 }
1693 
1694 #[cfg(has_i128)]
1695 impl Div<u128> for BigInt {
1696     type Output = BigInt;
1697 
1698     #[inline]
div(self, other: u128) -> BigInt1699     fn div(self, other: u128) -> BigInt {
1700         BigInt::from_biguint(self.sign, self.data / other)
1701     }
1702 }
1703 
1704 #[cfg(has_i128)]
1705 impl DivAssign<u128> for BigInt {
1706     #[inline]
div_assign(&mut self, other: u128)1707     fn div_assign(&mut self, other: u128) {
1708         self.data /= other;
1709         if self.data.is_zero() {
1710             self.sign = NoSign;
1711         }
1712     }
1713 }
1714 
1715 #[cfg(has_i128)]
1716 impl Div<BigInt> for u128 {
1717     type Output = BigInt;
1718 
1719     #[inline]
div(self, other: BigInt) -> BigInt1720     fn div(self, other: BigInt) -> BigInt {
1721         BigInt::from_biguint(other.sign, self / other.data)
1722     }
1723 }
1724 
1725 forward_all_scalar_binop_to_val_val!(impl Div<i32> for BigInt, div);
1726 forward_all_scalar_binop_to_val_val!(impl Div<i64> for BigInt, div);
1727 #[cfg(has_i128)]
1728 forward_all_scalar_binop_to_val_val!(impl Div<i128> for BigInt, div);
1729 
1730 impl Div<i32> for BigInt {
1731     type Output = BigInt;
1732 
1733     #[inline]
div(self, other: i32) -> BigInt1734     fn div(self, other: i32) -> BigInt {
1735         if other >= 0 {
1736             self / other as u32
1737         } else {
1738             -(self / i32_abs_as_u32(other))
1739         }
1740     }
1741 }
1742 
1743 impl DivAssign<i32> for BigInt {
1744     #[inline]
div_assign(&mut self, other: i32)1745     fn div_assign(&mut self, other: i32) {
1746         if other >= 0 {
1747             *self /= other as u32;
1748         } else {
1749             self.sign = -self.sign;
1750             *self /= i32_abs_as_u32(other);
1751         }
1752     }
1753 }
1754 
1755 impl Div<BigInt> for i32 {
1756     type Output = BigInt;
1757 
1758     #[inline]
div(self, other: BigInt) -> BigInt1759     fn div(self, other: BigInt) -> BigInt {
1760         if self >= 0 {
1761             self as u32 / other
1762         } else {
1763             -(i32_abs_as_u32(self) / other)
1764         }
1765     }
1766 }
1767 
1768 impl Div<i64> for BigInt {
1769     type Output = BigInt;
1770 
1771     #[inline]
div(self, other: i64) -> BigInt1772     fn div(self, other: i64) -> BigInt {
1773         if other >= 0 {
1774             self / other as u64
1775         } else {
1776             -(self / i64_abs_as_u64(other))
1777         }
1778     }
1779 }
1780 
1781 impl DivAssign<i64> for BigInt {
1782     #[inline]
div_assign(&mut self, other: i64)1783     fn div_assign(&mut self, other: i64) {
1784         if other >= 0 {
1785             *self /= other as u64;
1786         } else {
1787             self.sign = -self.sign;
1788             *self /= i64_abs_as_u64(other);
1789         }
1790     }
1791 }
1792 
1793 impl Div<BigInt> for i64 {
1794     type Output = BigInt;
1795 
1796     #[inline]
div(self, other: BigInt) -> BigInt1797     fn div(self, other: BigInt) -> BigInt {
1798         if self >= 0 {
1799             self as u64 / other
1800         } else {
1801             -(i64_abs_as_u64(self) / other)
1802         }
1803     }
1804 }
1805 
1806 #[cfg(has_i128)]
1807 impl Div<i128> for BigInt {
1808     type Output = BigInt;
1809 
1810     #[inline]
div(self, other: i128) -> BigInt1811     fn div(self, other: i128) -> BigInt {
1812         if other >= 0 {
1813             self / other as u128
1814         } else {
1815             -(self / i128_abs_as_u128(other))
1816         }
1817     }
1818 }
1819 
1820 #[cfg(has_i128)]
1821 impl DivAssign<i128> for BigInt {
1822     #[inline]
div_assign(&mut self, other: i128)1823     fn div_assign(&mut self, other: i128) {
1824         if other >= 0 {
1825             *self /= other as u128;
1826         } else {
1827             self.sign = -self.sign;
1828             *self /= i128_abs_as_u128(other);
1829         }
1830     }
1831 }
1832 
1833 #[cfg(has_i128)]
1834 impl Div<BigInt> for i128 {
1835     type Output = BigInt;
1836 
1837     #[inline]
div(self, other: BigInt) -> BigInt1838     fn div(self, other: BigInt) -> BigInt {
1839         if self >= 0 {
1840             self as u128 / other
1841         } else {
1842             -(i128_abs_as_u128(self) / other)
1843         }
1844     }
1845 }
1846 
1847 forward_all_binop_to_ref_ref!(impl Rem for BigInt, rem);
1848 
1849 impl<'a, 'b> Rem<&'b BigInt> for &'a BigInt {
1850     type Output = BigInt;
1851 
1852     #[inline]
rem(self, other: &BigInt) -> BigInt1853     fn rem(self, other: &BigInt) -> BigInt {
1854         let (_, r) = self.div_rem(other);
1855         r
1856     }
1857 }
1858 
1859 impl<'a> RemAssign<&'a BigInt> for BigInt {
1860     #[inline]
rem_assign(&mut self, other: &BigInt)1861     fn rem_assign(&mut self, other: &BigInt) {
1862         *self = &*self % other;
1863     }
1864 }
1865 forward_val_assign!(impl RemAssign for BigInt, rem_assign);
1866 
1867 promote_all_scalars!(impl Rem for BigInt, rem);
1868 promote_all_scalars_assign!(impl RemAssign for BigInt, rem_assign);
1869 forward_all_scalar_binop_to_val_val!(impl Rem<u32> for BigInt, rem);
1870 forward_all_scalar_binop_to_val_val!(impl Rem<u64> for BigInt, rem);
1871 #[cfg(has_i128)]
1872 forward_all_scalar_binop_to_val_val!(impl Rem<u128> for BigInt, rem);
1873 
1874 impl Rem<u32> for BigInt {
1875     type Output = BigInt;
1876 
1877     #[inline]
rem(self, other: u32) -> BigInt1878     fn rem(self, other: u32) -> BigInt {
1879         BigInt::from_biguint(self.sign, self.data % other)
1880     }
1881 }
1882 
1883 impl RemAssign<u32> for BigInt {
1884     #[inline]
rem_assign(&mut self, other: u32)1885     fn rem_assign(&mut self, other: u32) {
1886         self.data %= other;
1887         if self.data.is_zero() {
1888             self.sign = NoSign;
1889         }
1890     }
1891 }
1892 
1893 impl Rem<BigInt> for u32 {
1894     type Output = BigInt;
1895 
1896     #[inline]
rem(self, other: BigInt) -> BigInt1897     fn rem(self, other: BigInt) -> BigInt {
1898         BigInt::from_biguint(Plus, self % other.data)
1899     }
1900 }
1901 
1902 impl Rem<u64> for BigInt {
1903     type Output = BigInt;
1904 
1905     #[inline]
rem(self, other: u64) -> BigInt1906     fn rem(self, other: u64) -> BigInt {
1907         BigInt::from_biguint(self.sign, self.data % other)
1908     }
1909 }
1910 
1911 impl RemAssign<u64> for BigInt {
1912     #[inline]
rem_assign(&mut self, other: u64)1913     fn rem_assign(&mut self, other: u64) {
1914         self.data %= other;
1915         if self.data.is_zero() {
1916             self.sign = NoSign;
1917         }
1918     }
1919 }
1920 
1921 impl Rem<BigInt> for u64 {
1922     type Output = BigInt;
1923 
1924     #[inline]
rem(self, other: BigInt) -> BigInt1925     fn rem(self, other: BigInt) -> BigInt {
1926         BigInt::from_biguint(Plus, self % other.data)
1927     }
1928 }
1929 
1930 #[cfg(has_i128)]
1931 impl Rem<u128> for BigInt {
1932     type Output = BigInt;
1933 
1934     #[inline]
rem(self, other: u128) -> BigInt1935     fn rem(self, other: u128) -> BigInt {
1936         BigInt::from_biguint(self.sign, self.data % other)
1937     }
1938 }
1939 
1940 #[cfg(has_i128)]
1941 impl RemAssign<u128> for BigInt {
1942     #[inline]
rem_assign(&mut self, other: u128)1943     fn rem_assign(&mut self, other: u128) {
1944         self.data %= other;
1945         if self.data.is_zero() {
1946             self.sign = NoSign;
1947         }
1948     }
1949 }
1950 
1951 #[cfg(has_i128)]
1952 impl Rem<BigInt> for u128 {
1953     type Output = BigInt;
1954 
1955     #[inline]
rem(self, other: BigInt) -> BigInt1956     fn rem(self, other: BigInt) -> BigInt {
1957         BigInt::from_biguint(Plus, self % other.data)
1958     }
1959 }
1960 
1961 forward_all_scalar_binop_to_val_val!(impl Rem<i32> for BigInt, rem);
1962 forward_all_scalar_binop_to_val_val!(impl Rem<i64> for BigInt, rem);
1963 #[cfg(has_i128)]
1964 forward_all_scalar_binop_to_val_val!(impl Rem<i128> for BigInt, rem);
1965 
1966 impl Rem<i32> for BigInt {
1967     type Output = BigInt;
1968 
1969     #[inline]
rem(self, other: i32) -> BigInt1970     fn rem(self, other: i32) -> BigInt {
1971         if other >= 0 {
1972             self % other as u32
1973         } else {
1974             self % i32_abs_as_u32(other)
1975         }
1976     }
1977 }
1978 
1979 impl RemAssign<i32> for BigInt {
1980     #[inline]
rem_assign(&mut self, other: i32)1981     fn rem_assign(&mut self, other: i32) {
1982         if other >= 0 {
1983             *self %= other as u32;
1984         } else {
1985             *self %= i32_abs_as_u32(other);
1986         }
1987     }
1988 }
1989 
1990 impl Rem<BigInt> for i32 {
1991     type Output = BigInt;
1992 
1993     #[inline]
rem(self, other: BigInt) -> BigInt1994     fn rem(self, other: BigInt) -> BigInt {
1995         if self >= 0 {
1996             self as u32 % other
1997         } else {
1998             -(i32_abs_as_u32(self) % other)
1999         }
2000     }
2001 }
2002 
2003 impl Rem<i64> for BigInt {
2004     type Output = BigInt;
2005 
2006     #[inline]
rem(self, other: i64) -> BigInt2007     fn rem(self, other: i64) -> BigInt {
2008         if other >= 0 {
2009             self % other as u64
2010         } else {
2011             self % i64_abs_as_u64(other)
2012         }
2013     }
2014 }
2015 
2016 impl RemAssign<i64> for BigInt {
2017     #[inline]
rem_assign(&mut self, other: i64)2018     fn rem_assign(&mut self, other: i64) {
2019         if other >= 0 {
2020             *self %= other as u64;
2021         } else {
2022             *self %= i64_abs_as_u64(other);
2023         }
2024     }
2025 }
2026 
2027 impl Rem<BigInt> for i64 {
2028     type Output = BigInt;
2029 
2030     #[inline]
rem(self, other: BigInt) -> BigInt2031     fn rem(self, other: BigInt) -> BigInt {
2032         if self >= 0 {
2033             self as u64 % other
2034         } else {
2035             -(i64_abs_as_u64(self) % other)
2036         }
2037     }
2038 }
2039 
2040 #[cfg(has_i128)]
2041 impl Rem<i128> for BigInt {
2042     type Output = BigInt;
2043 
2044     #[inline]
rem(self, other: i128) -> BigInt2045     fn rem(self, other: i128) -> BigInt {
2046         if other >= 0 {
2047             self % other as u128
2048         } else {
2049             self % i128_abs_as_u128(other)
2050         }
2051     }
2052 }
2053 #[cfg(has_i128)]
2054 impl RemAssign<i128> for BigInt {
2055     #[inline]
rem_assign(&mut self, other: i128)2056     fn rem_assign(&mut self, other: i128) {
2057         if other >= 0 {
2058             *self %= other as u128;
2059         } else {
2060             *self %= i128_abs_as_u128(other);
2061         }
2062     }
2063 }
2064 #[cfg(has_i128)]
2065 impl Rem<BigInt> for i128 {
2066     type Output = BigInt;
2067 
2068     #[inline]
rem(self, other: BigInt) -> BigInt2069     fn rem(self, other: BigInt) -> BigInt {
2070         if self >= 0 {
2071             self as u128 % other
2072         } else {
2073             -(i128_abs_as_u128(self) % other)
2074         }
2075     }
2076 }
2077 
2078 impl Neg for BigInt {
2079     type Output = BigInt;
2080 
2081     #[inline]
neg(mut self) -> BigInt2082     fn neg(mut self) -> BigInt {
2083         self.sign = -self.sign;
2084         self
2085     }
2086 }
2087 
2088 impl<'a> Neg for &'a BigInt {
2089     type Output = BigInt;
2090 
2091     #[inline]
neg(self) -> BigInt2092     fn neg(self) -> BigInt {
2093         -self.clone()
2094     }
2095 }
2096 
2097 impl CheckedAdd for BigInt {
2098     #[inline]
checked_add(&self, v: &BigInt) -> Option<BigInt>2099     fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
2100         Some(self.add(v))
2101     }
2102 }
2103 
2104 impl CheckedSub for BigInt {
2105     #[inline]
checked_sub(&self, v: &BigInt) -> Option<BigInt>2106     fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
2107         Some(self.sub(v))
2108     }
2109 }
2110 
2111 impl CheckedMul for BigInt {
2112     #[inline]
checked_mul(&self, v: &BigInt) -> Option<BigInt>2113     fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
2114         Some(self.mul(v))
2115     }
2116 }
2117 
2118 impl CheckedDiv for BigInt {
2119     #[inline]
checked_div(&self, v: &BigInt) -> Option<BigInt>2120     fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
2121         if v.is_zero() {
2122             return None;
2123         }
2124         Some(self.div(v))
2125     }
2126 }
2127 
2128 impl Integer for BigInt {
2129     #[inline]
div_rem(&self, other: &BigInt) -> (BigInt, BigInt)2130     fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) {
2131         // r.sign == self.sign
2132         let (d_ui, r_ui) = self.data.div_mod_floor(&other.data);
2133         let d = BigInt::from_biguint(self.sign, d_ui);
2134         let r = BigInt::from_biguint(self.sign, r_ui);
2135         if other.is_negative() {
2136             (-d, r)
2137         } else {
2138             (d, r)
2139         }
2140     }
2141 
2142     #[inline]
div_floor(&self, other: &BigInt) -> BigInt2143     fn div_floor(&self, other: &BigInt) -> BigInt {
2144         let (d, _) = self.div_mod_floor(other);
2145         d
2146     }
2147 
2148     #[inline]
mod_floor(&self, other: &BigInt) -> BigInt2149     fn mod_floor(&self, other: &BigInt) -> BigInt {
2150         let (_, m) = self.div_mod_floor(other);
2151         m
2152     }
2153 
div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt)2154     fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) {
2155         // m.sign == other.sign
2156         let (d_ui, m_ui) = self.data.div_rem(&other.data);
2157         let d = BigInt::from_biguint(Plus, d_ui);
2158         let m = BigInt::from_biguint(Plus, m_ui);
2159         let one: BigInt = One::one();
2160         match (self.sign, other.sign) {
2161             (_, NoSign) => panic!(),
2162             (Plus, Plus) | (NoSign, Plus) => (d, m),
2163             (Plus, Minus) | (NoSign, Minus) => {
2164                 if m.is_zero() {
2165                     (-d, Zero::zero())
2166                 } else {
2167                     (-d - one, m + other)
2168                 }
2169             }
2170             (Minus, Plus) => {
2171                 if m.is_zero() {
2172                     (-d, Zero::zero())
2173                 } else {
2174                     (-d - one, other - m)
2175                 }
2176             }
2177             (Minus, Minus) => (d, -m),
2178         }
2179     }
2180 
2181     /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
2182     ///
2183     /// The result is always positive.
2184     #[inline]
gcd(&self, other: &BigInt) -> BigInt2185     fn gcd(&self, other: &BigInt) -> BigInt {
2186         BigInt::from_biguint(Plus, self.data.gcd(&other.data))
2187     }
2188 
2189     /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
2190     #[inline]
lcm(&self, other: &BigInt) -> BigInt2191     fn lcm(&self, other: &BigInt) -> BigInt {
2192         BigInt::from_biguint(Plus, self.data.lcm(&other.data))
2193     }
2194 
2195     /// Deprecated, use `is_multiple_of` instead.
2196     #[inline]
divides(&self, other: &BigInt) -> bool2197     fn divides(&self, other: &BigInt) -> bool {
2198         self.is_multiple_of(other)
2199     }
2200 
2201     /// Returns `true` if the number is a multiple of `other`.
2202     #[inline]
is_multiple_of(&self, other: &BigInt) -> bool2203     fn is_multiple_of(&self, other: &BigInt) -> bool {
2204         self.data.is_multiple_of(&other.data)
2205     }
2206 
2207     /// Returns `true` if the number is divisible by `2`.
2208     #[inline]
is_even(&self) -> bool2209     fn is_even(&self) -> bool {
2210         self.data.is_even()
2211     }
2212 
2213     /// Returns `true` if the number is not divisible by `2`.
2214     #[inline]
is_odd(&self) -> bool2215     fn is_odd(&self) -> bool {
2216         self.data.is_odd()
2217     }
2218 }
2219 
2220 impl Roots for BigInt {
nth_root(&self, n: u32) -> Self2221     fn nth_root(&self, n: u32) -> Self {
2222         assert!(
2223             !(self.is_negative() && n.is_even()),
2224             "root of degree {} is imaginary",
2225             n
2226         );
2227 
2228         BigInt::from_biguint(self.sign, self.data.nth_root(n))
2229     }
2230 
sqrt(&self) -> Self2231     fn sqrt(&self) -> Self {
2232         assert!(!self.is_negative(), "square root is imaginary");
2233 
2234         BigInt::from_biguint(self.sign, self.data.sqrt())
2235     }
2236 
cbrt(&self) -> Self2237     fn cbrt(&self) -> Self {
2238         BigInt::from_biguint(self.sign, self.data.cbrt())
2239     }
2240 }
2241 
2242 impl ToPrimitive for BigInt {
2243     #[inline]
to_i64(&self) -> Option<i64>2244     fn to_i64(&self) -> Option<i64> {
2245         match self.sign {
2246             Plus => self.data.to_i64(),
2247             NoSign => Some(0),
2248             Minus => self.data.to_u64().and_then(|n| {
2249                 let m: u64 = 1 << 63;
2250                 if n < m {
2251                     Some(-(n as i64))
2252                 } else if n == m {
2253                     Some(i64::MIN)
2254                 } else {
2255                     None
2256                 }
2257             }),
2258         }
2259     }
2260 
2261     #[inline]
2262     #[cfg(has_i128)]
to_i128(&self) -> Option<i128>2263     fn to_i128(&self) -> Option<i128> {
2264         match self.sign {
2265             Plus => self.data.to_i128(),
2266             NoSign => Some(0),
2267             Minus => self.data.to_u128().and_then(|n| {
2268                 let m: u128 = 1 << 127;
2269                 if n < m {
2270                     Some(-(n as i128))
2271                 } else if n == m {
2272                     Some(i128::MIN)
2273                 } else {
2274                     None
2275                 }
2276             }),
2277         }
2278     }
2279 
2280     #[inline]
to_u64(&self) -> Option<u64>2281     fn to_u64(&self) -> Option<u64> {
2282         match self.sign {
2283             Plus => self.data.to_u64(),
2284             NoSign => Some(0),
2285             Minus => None,
2286         }
2287     }
2288 
2289     #[inline]
2290     #[cfg(has_i128)]
to_u128(&self) -> Option<u128>2291     fn to_u128(&self) -> Option<u128> {
2292         match self.sign {
2293             Plus => self.data.to_u128(),
2294             NoSign => Some(0),
2295             Minus => None,
2296         }
2297     }
2298 
2299     #[inline]
to_f32(&self) -> Option<f32>2300     fn to_f32(&self) -> Option<f32> {
2301         self.data
2302             .to_f32()
2303             .map(|n| if self.sign == Minus { -n } else { n })
2304     }
2305 
2306     #[inline]
to_f64(&self) -> Option<f64>2307     fn to_f64(&self) -> Option<f64> {
2308         self.data
2309             .to_f64()
2310             .map(|n| if self.sign == Minus { -n } else { n })
2311     }
2312 }
2313 
2314 impl FromPrimitive for BigInt {
2315     #[inline]
from_i64(n: i64) -> Option<BigInt>2316     fn from_i64(n: i64) -> Option<BigInt> {
2317         Some(BigInt::from(n))
2318     }
2319 
2320     #[inline]
2321     #[cfg(has_i128)]
from_i128(n: i128) -> Option<BigInt>2322     fn from_i128(n: i128) -> Option<BigInt> {
2323         Some(BigInt::from(n))
2324     }
2325 
2326     #[inline]
from_u64(n: u64) -> Option<BigInt>2327     fn from_u64(n: u64) -> Option<BigInt> {
2328         Some(BigInt::from(n))
2329     }
2330 
2331     #[inline]
2332     #[cfg(has_i128)]
from_u128(n: u128) -> Option<BigInt>2333     fn from_u128(n: u128) -> Option<BigInt> {
2334         Some(BigInt::from(n))
2335     }
2336 
2337     #[inline]
from_f64(n: f64) -> Option<BigInt>2338     fn from_f64(n: f64) -> Option<BigInt> {
2339         if n >= 0.0 {
2340             BigUint::from_f64(n).map(|x| BigInt::from_biguint(Plus, x))
2341         } else {
2342             BigUint::from_f64(-n).map(|x| BigInt::from_biguint(Minus, x))
2343         }
2344     }
2345 }
2346 
2347 impl From<i64> for BigInt {
2348     #[inline]
from(n: i64) -> Self2349     fn from(n: i64) -> Self {
2350         if n >= 0 {
2351             BigInt::from(n as u64)
2352         } else {
2353             let u = u64::MAX - (n as u64) + 1;
2354             BigInt {
2355                 sign: Minus,
2356                 data: BigUint::from(u),
2357             }
2358         }
2359     }
2360 }
2361 
2362 #[cfg(has_i128)]
2363 impl From<i128> for BigInt {
2364     #[inline]
from(n: i128) -> Self2365     fn from(n: i128) -> Self {
2366         if n >= 0 {
2367             BigInt::from(n as u128)
2368         } else {
2369             let u = u128::MAX - (n as u128) + 1;
2370             BigInt {
2371                 sign: Minus,
2372                 data: BigUint::from(u),
2373             }
2374         }
2375     }
2376 }
2377 
2378 macro_rules! impl_bigint_from_int {
2379     ($T:ty) => {
2380         impl From<$T> for BigInt {
2381             #[inline]
2382             fn from(n: $T) -> Self {
2383                 BigInt::from(n as i64)
2384             }
2385         }
2386     };
2387 }
2388 
2389 impl_bigint_from_int!(i8);
2390 impl_bigint_from_int!(i16);
2391 impl_bigint_from_int!(i32);
2392 impl_bigint_from_int!(isize);
2393 
2394 impl From<u64> for BigInt {
2395     #[inline]
from(n: u64) -> Self2396     fn from(n: u64) -> Self {
2397         if n > 0 {
2398             BigInt {
2399                 sign: Plus,
2400                 data: BigUint::from(n),
2401             }
2402         } else {
2403             BigInt::zero()
2404         }
2405     }
2406 }
2407 
2408 #[cfg(has_i128)]
2409 impl From<u128> for BigInt {
2410     #[inline]
from(n: u128) -> Self2411     fn from(n: u128) -> Self {
2412         if n > 0 {
2413             BigInt {
2414                 sign: Plus,
2415                 data: BigUint::from(n),
2416             }
2417         } else {
2418             BigInt::zero()
2419         }
2420     }
2421 }
2422 
2423 macro_rules! impl_bigint_from_uint {
2424     ($T:ty) => {
2425         impl From<$T> for BigInt {
2426             #[inline]
2427             fn from(n: $T) -> Self {
2428                 BigInt::from(n as u64)
2429             }
2430         }
2431     };
2432 }
2433 
2434 impl_bigint_from_uint!(u8);
2435 impl_bigint_from_uint!(u16);
2436 impl_bigint_from_uint!(u32);
2437 impl_bigint_from_uint!(usize);
2438 
2439 impl From<BigUint> for BigInt {
2440     #[inline]
from(n: BigUint) -> Self2441     fn from(n: BigUint) -> Self {
2442         if n.is_zero() {
2443             BigInt::zero()
2444         } else {
2445             BigInt {
2446                 sign: Plus,
2447                 data: n,
2448             }
2449         }
2450     }
2451 }
2452 
2453 impl IntDigits for BigInt {
2454     #[inline]
digits(&self) -> &[BigDigit]2455     fn digits(&self) -> &[BigDigit] {
2456         self.data.digits()
2457     }
2458     #[inline]
digits_mut(&mut self) -> &mut Vec<BigDigit>2459     fn digits_mut(&mut self) -> &mut Vec<BigDigit> {
2460         self.data.digits_mut()
2461     }
2462     #[inline]
normalize(&mut self)2463     fn normalize(&mut self) {
2464         self.data.normalize();
2465         if self.data.is_zero() {
2466             self.sign = NoSign;
2467         }
2468     }
2469     #[inline]
capacity(&self) -> usize2470     fn capacity(&self) -> usize {
2471         self.data.capacity()
2472     }
2473     #[inline]
len(&self) -> usize2474     fn len(&self) -> usize {
2475         self.data.len()
2476     }
2477 }
2478 
2479 #[cfg(feature = "serde")]
2480 impl serde::Serialize for BigInt {
serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer,2481     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2482     where
2483         S: serde::Serializer,
2484     {
2485         // Note: do not change the serialization format, or it may break
2486         // forward and backward compatibility of serialized data!
2487         (self.sign, &self.data).serialize(serializer)
2488     }
2489 }
2490 
2491 #[cfg(feature = "serde")]
2492 impl<'de> serde::Deserialize<'de> for BigInt {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>,2493     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2494     where
2495         D: serde::Deserializer<'de>,
2496     {
2497         let (sign, data) = serde::Deserialize::deserialize(deserializer)?;
2498         Ok(BigInt::from_biguint(sign, data))
2499     }
2500 }
2501 
2502 /// A generic trait for converting a value to a `BigInt`. This may return
2503 /// `None` when converting from `f32` or `f64`, and will always succeed
2504 /// when converting from any integer or unsigned primitive, or `BigUint`.
2505 pub trait ToBigInt {
2506     /// Converts the value of `self` to a `BigInt`.
to_bigint(&self) -> Option<BigInt>2507     fn to_bigint(&self) -> Option<BigInt>;
2508 }
2509 
2510 impl ToBigInt for BigInt {
2511     #[inline]
to_bigint(&self) -> Option<BigInt>2512     fn to_bigint(&self) -> Option<BigInt> {
2513         Some(self.clone())
2514     }
2515 }
2516 
2517 impl ToBigInt for BigUint {
2518     #[inline]
to_bigint(&self) -> Option<BigInt>2519     fn to_bigint(&self) -> Option<BigInt> {
2520         if self.is_zero() {
2521             Some(Zero::zero())
2522         } else {
2523             Some(BigInt {
2524                 sign: Plus,
2525                 data: self.clone(),
2526             })
2527         }
2528     }
2529 }
2530 
2531 impl biguint::ToBigUint for BigInt {
2532     #[inline]
to_biguint(&self) -> Option<BigUint>2533     fn to_biguint(&self) -> Option<BigUint> {
2534         match self.sign() {
2535             Plus => Some(self.data.clone()),
2536             NoSign => Some(Zero::zero()),
2537             Minus => None,
2538         }
2539     }
2540 }
2541 
2542 macro_rules! impl_to_bigint {
2543     ($T:ty, $from_ty:path) => {
2544         impl ToBigInt for $T {
2545             #[inline]
2546             fn to_bigint(&self) -> Option<BigInt> {
2547                 $from_ty(*self)
2548             }
2549         }
2550     };
2551 }
2552 
2553 impl_to_bigint!(isize, FromPrimitive::from_isize);
2554 impl_to_bigint!(i8, FromPrimitive::from_i8);
2555 impl_to_bigint!(i16, FromPrimitive::from_i16);
2556 impl_to_bigint!(i32, FromPrimitive::from_i32);
2557 impl_to_bigint!(i64, FromPrimitive::from_i64);
2558 #[cfg(has_i128)]
2559 impl_to_bigint!(i128, FromPrimitive::from_i128);
2560 
2561 impl_to_bigint!(usize, FromPrimitive::from_usize);
2562 impl_to_bigint!(u8, FromPrimitive::from_u8);
2563 impl_to_bigint!(u16, FromPrimitive::from_u16);
2564 impl_to_bigint!(u32, FromPrimitive::from_u32);
2565 impl_to_bigint!(u64, FromPrimitive::from_u64);
2566 #[cfg(has_i128)]
2567 impl_to_bigint!(u128, FromPrimitive::from_u128);
2568 
2569 impl_to_bigint!(f32, FromPrimitive::from_f32);
2570 impl_to_bigint!(f64, FromPrimitive::from_f64);
2571 
2572 impl BigInt {
2573     /// Creates and initializes a BigInt.
2574     ///
2575     /// The base 2<sup>32</sup> digits are ordered least significant digit first.
2576     #[inline]
new(sign: Sign, digits: Vec<u32>) -> BigInt2577     pub fn new(sign: Sign, digits: Vec<u32>) -> BigInt {
2578         BigInt::from_biguint(sign, BigUint::new(digits))
2579     }
2580 
2581     /// Creates and initializes a `BigInt`.
2582     ///
2583     /// The base 2<sup>32</sup> digits are ordered least significant digit first.
2584     #[inline]
from_biguint(mut sign: Sign, mut data: BigUint) -> BigInt2585     pub fn from_biguint(mut sign: Sign, mut data: BigUint) -> BigInt {
2586         if sign == NoSign {
2587             data.assign_from_slice(&[]);
2588         } else if data.is_zero() {
2589             sign = NoSign;
2590         }
2591 
2592         BigInt {
2593             sign: sign,
2594             data: data,
2595         }
2596     }
2597 
2598     /// Creates and initializes a `BigInt`.
2599     ///
2600     /// The base 2<sup>32</sup> digits are ordered least significant digit first.
2601     #[inline]
from_slice(sign: Sign, slice: &[u32]) -> BigInt2602     pub fn from_slice(sign: Sign, slice: &[u32]) -> BigInt {
2603         BigInt::from_biguint(sign, BigUint::from_slice(slice))
2604     }
2605 
2606     /// Reinitializes a `BigInt`.
2607     ///
2608     /// The base 2<sup>32</sup> digits are ordered least significant digit first.
2609     #[inline]
assign_from_slice(&mut self, sign: Sign, slice: &[u32])2610     pub fn assign_from_slice(&mut self, sign: Sign, slice: &[u32]) {
2611         if sign == NoSign {
2612             self.data.assign_from_slice(&[]);
2613             self.sign = NoSign;
2614         } else {
2615             self.data.assign_from_slice(slice);
2616             self.sign = match self.data.is_zero() {
2617                 true => NoSign,
2618                 false => sign,
2619             }
2620         }
2621     }
2622 
2623     /// Creates and initializes a `BigInt`.
2624     ///
2625     /// The bytes are in big-endian byte order.
2626     ///
2627     /// # Examples
2628     ///
2629     /// ```
2630     /// use num_bigint::{BigInt, Sign};
2631     ///
2632     /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"),
2633     ///            BigInt::parse_bytes(b"65", 10).unwrap());
2634     /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AA"),
2635     ///            BigInt::parse_bytes(b"16705", 10).unwrap());
2636     /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AB"),
2637     ///            BigInt::parse_bytes(b"16706", 10).unwrap());
2638     /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"),
2639     ///            BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
2640     /// ```
2641     #[inline]
from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt2642     pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt {
2643         BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes))
2644     }
2645 
2646     /// Creates and initializes a `BigInt`.
2647     ///
2648     /// The bytes are in little-endian byte order.
2649     #[inline]
from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt2650     pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt {
2651         BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes))
2652     }
2653 
2654     /// Creates and initializes a `BigInt` from an array of bytes in
2655     /// two's complement binary representation.
2656     ///
2657     /// The digits are in big-endian base 2<sup>8</sup>.
2658     #[inline]
from_signed_bytes_be(digits: &[u8]) -> BigInt2659     pub fn from_signed_bytes_be(digits: &[u8]) -> BigInt {
2660         let sign = match digits.first() {
2661             Some(v) if *v > 0x7f => Sign::Minus,
2662             Some(_) => Sign::Plus,
2663             None => return BigInt::zero(),
2664         };
2665 
2666         if sign == Sign::Minus {
2667             // two's-complement the content to retrieve the magnitude
2668             let mut digits = Vec::from(digits);
2669             twos_complement_be(&mut digits);
2670             BigInt::from_biguint(sign, BigUint::from_bytes_be(&*digits))
2671         } else {
2672             BigInt::from_biguint(sign, BigUint::from_bytes_be(digits))
2673         }
2674     }
2675 
2676     /// Creates and initializes a `BigInt` from an array of bytes in two's complement.
2677     ///
2678     /// The digits are in little-endian base 2<sup>8</sup>.
2679     #[inline]
from_signed_bytes_le(digits: &[u8]) -> BigInt2680     pub fn from_signed_bytes_le(digits: &[u8]) -> BigInt {
2681         let sign = match digits.last() {
2682             Some(v) if *v > 0x7f => Sign::Minus,
2683             Some(_) => Sign::Plus,
2684             None => return BigInt::zero(),
2685         };
2686 
2687         if sign == Sign::Minus {
2688             // two's-complement the content to retrieve the magnitude
2689             let mut digits = Vec::from(digits);
2690             twos_complement_le(&mut digits);
2691             BigInt::from_biguint(sign, BigUint::from_bytes_le(&*digits))
2692         } else {
2693             BigInt::from_biguint(sign, BigUint::from_bytes_le(digits))
2694         }
2695     }
2696 
2697     /// Creates and initializes a `BigInt`.
2698     ///
2699     /// # Examples
2700     ///
2701     /// ```
2702     /// use num_bigint::{BigInt, ToBigInt};
2703     ///
2704     /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234));
2705     /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD));
2706     /// assert_eq!(BigInt::parse_bytes(b"G", 16), None);
2707     /// ```
2708     #[inline]
parse_bytes(buf: &[u8], radix: u32) -> Option<BigInt>2709     pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigInt> {
2710         str::from_utf8(buf)
2711             .ok()
2712             .and_then(|s| BigInt::from_str_radix(s, radix).ok())
2713     }
2714 
2715     /// Creates and initializes a `BigInt`. Each u8 of the input slice is
2716     /// interpreted as one digit of the number
2717     /// and must therefore be less than `radix`.
2718     ///
2719     /// The bytes are in big-endian byte order.
2720     /// `radix` must be in the range `2...256`.
2721     ///
2722     /// # Examples
2723     ///
2724     /// ```
2725     /// use num_bigint::{BigInt, Sign};
2726     ///
2727     /// let inbase190 = vec![15, 33, 125, 12, 14];
2728     /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap();
2729     /// assert_eq!(a.to_radix_be(190), (Sign:: Minus, inbase190));
2730     /// ```
from_radix_be(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt>2731     pub fn from_radix_be(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt> {
2732         BigUint::from_radix_be(buf, radix).map(|u| BigInt::from_biguint(sign, u))
2733     }
2734 
2735     /// Creates and initializes a `BigInt`. Each u8 of the input slice is
2736     /// interpreted as one digit of the number
2737     /// and must therefore be less than `radix`.
2738     ///
2739     /// The bytes are in little-endian byte order.
2740     /// `radix` must be in the range `2...256`.
2741     ///
2742     /// # Examples
2743     ///
2744     /// ```
2745     /// use num_bigint::{BigInt, Sign};
2746     ///
2747     /// let inbase190 = vec![14, 12, 125, 33, 15];
2748     /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap();
2749     /// assert_eq!(a.to_radix_be(190), (Sign::Minus, inbase190));
2750     /// ```
from_radix_le(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt>2751     pub fn from_radix_le(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt> {
2752         BigUint::from_radix_le(buf, radix).map(|u| BigInt::from_biguint(sign, u))
2753     }
2754 
2755     /// Returns the sign and the byte representation of the `BigInt` in big-endian byte order.
2756     ///
2757     /// # Examples
2758     ///
2759     /// ```
2760     /// use num_bigint::{ToBigInt, Sign};
2761     ///
2762     /// let i = -1125.to_bigint().unwrap();
2763     /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101]));
2764     /// ```
2765     #[inline]
to_bytes_be(&self) -> (Sign, Vec<u8>)2766     pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) {
2767         (self.sign, self.data.to_bytes_be())
2768     }
2769 
2770     /// Returns the sign and the byte representation of the `BigInt` in little-endian byte order.
2771     ///
2772     /// # Examples
2773     ///
2774     /// ```
2775     /// use num_bigint::{ToBigInt, Sign};
2776     ///
2777     /// let i = -1125.to_bigint().unwrap();
2778     /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4]));
2779     /// ```
2780     #[inline]
to_bytes_le(&self) -> (Sign, Vec<u8>)2781     pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) {
2782         (self.sign, self.data.to_bytes_le())
2783     }
2784 
2785     /// Returns the sign and the `u32` digits representation of the `BigInt` ordered least
2786     /// significant digit first.
2787     ///
2788     /// # Examples
2789     ///
2790     /// ```
2791     /// use num_bigint::{BigInt, Sign};
2792     ///
2793     /// assert_eq!(BigInt::from(-1125).to_u32_digits(), (Sign::Minus, vec![1125]));
2794     /// assert_eq!(BigInt::from(4294967295u32).to_u32_digits(), (Sign::Plus, vec![4294967295]));
2795     /// assert_eq!(BigInt::from(4294967296u64).to_u32_digits(), (Sign::Plus, vec![0, 1]));
2796     /// assert_eq!(BigInt::from(-112500000000i64).to_u32_digits(), (Sign::Minus, vec![830850304, 26]));
2797     /// assert_eq!(BigInt::from(112500000000i64).to_u32_digits(), (Sign::Plus, vec![830850304, 26]));
2798     /// ```
2799     #[inline]
to_u32_digits(&self) -> (Sign, Vec<u32>)2800     pub fn to_u32_digits(&self) -> (Sign, Vec<u32>) {
2801         (self.sign, self.data.to_u32_digits())
2802     }
2803 
2804     /// Returns the two's-complement byte representation of the `BigInt` in big-endian byte order.
2805     ///
2806     /// # Examples
2807     ///
2808     /// ```
2809     /// use num_bigint::ToBigInt;
2810     ///
2811     /// let i = -1125.to_bigint().unwrap();
2812     /// assert_eq!(i.to_signed_bytes_be(), vec![251, 155]);
2813     /// ```
2814     #[inline]
to_signed_bytes_be(&self) -> Vec<u8>2815     pub fn to_signed_bytes_be(&self) -> Vec<u8> {
2816         let mut bytes = self.data.to_bytes_be();
2817         let first_byte = bytes.first().cloned().unwrap_or(0);
2818         if first_byte > 0x7f
2819             && !(first_byte == 0x80
2820                 && bytes.iter().skip(1).all(Zero::is_zero)
2821                 && self.sign == Sign::Minus)
2822         {
2823             // msb used by magnitude, extend by 1 byte
2824             bytes.insert(0, 0);
2825         }
2826         if self.sign == Sign::Minus {
2827             twos_complement_be(&mut bytes);
2828         }
2829         bytes
2830     }
2831 
2832     /// Returns the two's-complement byte representation of the `BigInt` in little-endian byte order.
2833     ///
2834     /// # Examples
2835     ///
2836     /// ```
2837     /// use num_bigint::ToBigInt;
2838     ///
2839     /// let i = -1125.to_bigint().unwrap();
2840     /// assert_eq!(i.to_signed_bytes_le(), vec![155, 251]);
2841     /// ```
2842     #[inline]
to_signed_bytes_le(&self) -> Vec<u8>2843     pub fn to_signed_bytes_le(&self) -> Vec<u8> {
2844         let mut bytes = self.data.to_bytes_le();
2845         let last_byte = bytes.last().cloned().unwrap_or(0);
2846         if last_byte > 0x7f
2847             && !(last_byte == 0x80
2848                 && bytes.iter().rev().skip(1).all(Zero::is_zero)
2849                 && self.sign == Sign::Minus)
2850         {
2851             // msb used by magnitude, extend by 1 byte
2852             bytes.push(0);
2853         }
2854         if self.sign == Sign::Minus {
2855             twos_complement_le(&mut bytes);
2856         }
2857         bytes
2858     }
2859 
2860     /// Returns the integer formatted as a string in the given radix.
2861     /// `radix` must be in the range `2...36`.
2862     ///
2863     /// # Examples
2864     ///
2865     /// ```
2866     /// use num_bigint::BigInt;
2867     ///
2868     /// let i = BigInt::parse_bytes(b"ff", 16).unwrap();
2869     /// assert_eq!(i.to_str_radix(16), "ff");
2870     /// ```
2871     #[inline]
to_str_radix(&self, radix: u32) -> String2872     pub fn to_str_radix(&self, radix: u32) -> String {
2873         let mut v = to_str_radix_reversed(&self.data, radix);
2874 
2875         if self.is_negative() {
2876             v.push(b'-');
2877         }
2878 
2879         v.reverse();
2880         unsafe { String::from_utf8_unchecked(v) }
2881     }
2882 
2883     /// Returns the integer in the requested base in big-endian digit order.
2884     /// The output is not given in a human readable alphabet but as a zero
2885     /// based u8 number.
2886     /// `radix` must be in the range `2...256`.
2887     ///
2888     /// # Examples
2889     ///
2890     /// ```
2891     /// use num_bigint::{BigInt, Sign};
2892     ///
2893     /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_be(159),
2894     ///            (Sign::Minus, vec![2, 94, 27]));
2895     /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27
2896     /// ```
2897     #[inline]
to_radix_be(&self, radix: u32) -> (Sign, Vec<u8>)2898     pub fn to_radix_be(&self, radix: u32) -> (Sign, Vec<u8>) {
2899         (self.sign, self.data.to_radix_be(radix))
2900     }
2901 
2902     /// Returns the integer in the requested base in little-endian digit order.
2903     /// The output is not given in a human readable alphabet but as a zero
2904     /// based u8 number.
2905     /// `radix` must be in the range `2...256`.
2906     ///
2907     /// # Examples
2908     ///
2909     /// ```
2910     /// use num_bigint::{BigInt, Sign};
2911     ///
2912     /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_le(159),
2913     ///            (Sign::Minus, vec![27, 94, 2]));
2914     /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2)
2915     /// ```
2916     #[inline]
to_radix_le(&self, radix: u32) -> (Sign, Vec<u8>)2917     pub fn to_radix_le(&self, radix: u32) -> (Sign, Vec<u8>) {
2918         (self.sign, self.data.to_radix_le(radix))
2919     }
2920 
2921     /// Returns the sign of the `BigInt` as a `Sign`.
2922     ///
2923     /// # Examples
2924     ///
2925     /// ```
2926     /// use num_bigint::{ToBigInt, Sign};
2927     ///
2928     /// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus);
2929     /// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus);
2930     /// assert_eq!(ToBigInt::to_bigint(&0).unwrap().sign(), Sign::NoSign);
2931     /// ```
2932     #[inline]
sign(&self) -> Sign2933     pub fn sign(&self) -> Sign {
2934         self.sign
2935     }
2936 
2937     /// Determines the fewest bits necessary to express the `BigInt`,
2938     /// not including the sign.
2939     #[inline]
bits(&self) -> usize2940     pub fn bits(&self) -> usize {
2941         self.data.bits()
2942     }
2943 
2944     /// Converts this `BigInt` into a `BigUint`, if it's not negative.
2945     #[inline]
to_biguint(&self) -> Option<BigUint>2946     pub fn to_biguint(&self) -> Option<BigUint> {
2947         match self.sign {
2948             Plus => Some(self.data.clone()),
2949             NoSign => Some(Zero::zero()),
2950             Minus => None,
2951         }
2952     }
2953 
2954     #[inline]
checked_add(&self, v: &BigInt) -> Option<BigInt>2955     pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
2956         Some(self.add(v))
2957     }
2958 
2959     #[inline]
checked_sub(&self, v: &BigInt) -> Option<BigInt>2960     pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
2961         Some(self.sub(v))
2962     }
2963 
2964     #[inline]
checked_mul(&self, v: &BigInt) -> Option<BigInt>2965     pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
2966         Some(self.mul(v))
2967     }
2968 
2969     #[inline]
checked_div(&self, v: &BigInt) -> Option<BigInt>2970     pub fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
2971         if v.is_zero() {
2972             return None;
2973         }
2974         Some(self.div(v))
2975     }
2976 
2977     /// Returns `(self ^ exponent) mod modulus`
2978     ///
2979     /// Note that this rounds like `mod_floor`, not like the `%` operator,
2980     /// which makes a difference when given a negative `self` or `modulus`.
2981     /// The result will be in the interval `[0, modulus)` for `modulus > 0`,
2982     /// or in the interval `(modulus, 0]` for `modulus < 0`
2983     ///
2984     /// Panics if the exponent is negative or the modulus is zero.
modpow(&self, exponent: &Self, modulus: &Self) -> Self2985     pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self {
2986         assert!(
2987             !exponent.is_negative(),
2988             "negative exponentiation is not supported!"
2989         );
2990         assert!(!modulus.is_zero(), "divide by zero!");
2991 
2992         let result = self.data.modpow(&exponent.data, &modulus.data);
2993         if result.is_zero() {
2994             return BigInt::zero();
2995         }
2996 
2997         // The sign of the result follows the modulus, like `mod_floor`.
2998         let (sign, mag) = match (
2999             self.is_negative() && exponent.is_odd(),
3000             modulus.is_negative(),
3001         ) {
3002             (false, false) => (Plus, result),
3003             (true, false) => (Plus, &modulus.data - result),
3004             (false, true) => (Minus, &modulus.data - result),
3005             (true, true) => (Minus, result),
3006         };
3007         BigInt::from_biguint(sign, mag)
3008     }
3009 
3010     /// Returns the truncated principal square root of `self` --
3011     /// see [Roots::sqrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.sqrt).
sqrt(&self) -> Self3012     pub fn sqrt(&self) -> Self {
3013         Roots::sqrt(self)
3014     }
3015 
3016     /// Returns the truncated principal cube root of `self` --
3017     /// see [Roots::cbrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.cbrt).
cbrt(&self) -> Self3018     pub fn cbrt(&self) -> Self {
3019         Roots::cbrt(self)
3020     }
3021 
3022     /// Returns the truncated principal `n`th root of `self` --
3023     /// See [Roots::nth_root](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#tymethod.nth_root).
nth_root(&self, n: u32) -> Self3024     pub fn nth_root(&self, n: u32) -> Self {
3025         Roots::nth_root(self, n)
3026     }
3027 }
3028 
3029 impl_sum_iter_type!(BigInt);
3030 impl_product_iter_type!(BigInt);
3031 
3032 /// Perform in-place two's complement of the given binary representation,
3033 /// in little-endian byte order.
3034 #[inline]
twos_complement_le(digits: &mut [u8])3035 fn twos_complement_le(digits: &mut [u8]) {
3036     twos_complement(digits)
3037 }
3038 
3039 /// Perform in-place two's complement of the given binary representation
3040 /// in big-endian byte order.
3041 #[inline]
twos_complement_be(digits: &mut [u8])3042 fn twos_complement_be(digits: &mut [u8]) {
3043     twos_complement(digits.iter_mut().rev())
3044 }
3045 
3046 /// Perform in-place two's complement of the given digit iterator
3047 /// starting from the least significant byte.
3048 #[inline]
twos_complement<'a, I>(digits: I) where I: IntoIterator<Item = &'a mut u8>,3049 fn twos_complement<'a, I>(digits: I)
3050 where
3051     I: IntoIterator<Item = &'a mut u8>,
3052 {
3053     let mut carry = true;
3054     for d in digits {
3055         *d = d.not();
3056         if carry {
3057             *d = d.wrapping_add(1);
3058             carry = d.is_zero();
3059         }
3060     }
3061 }
3062 
3063 #[test]
test_from_biguint()3064 fn test_from_biguint() {
3065     fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) {
3066         let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_usize(inp_n).unwrap());
3067         let ans = BigInt {
3068             sign: ans_s,
3069             data: FromPrimitive::from_usize(ans_n).unwrap(),
3070         };
3071         assert_eq!(inp, ans);
3072     }
3073     check(Plus, 1, Plus, 1);
3074     check(Plus, 0, NoSign, 0);
3075     check(Minus, 1, Minus, 1);
3076     check(NoSign, 1, NoSign, 0);
3077 }
3078 
3079 #[test]
test_from_slice()3080 fn test_from_slice() {
3081     fn check(inp_s: Sign, inp_n: u32, ans_s: Sign, ans_n: u32) {
3082         let inp = BigInt::from_slice(inp_s, &[inp_n]);
3083         let ans = BigInt {
3084             sign: ans_s,
3085             data: FromPrimitive::from_u32(ans_n).unwrap(),
3086         };
3087         assert_eq!(inp, ans);
3088     }
3089     check(Plus, 1, Plus, 1);
3090     check(Plus, 0, NoSign, 0);
3091     check(Minus, 1, Minus, 1);
3092     check(NoSign, 1, NoSign, 0);
3093 }
3094 
3095 #[test]
test_assign_from_slice()3096 fn test_assign_from_slice() {
3097     fn check(inp_s: Sign, inp_n: u32, ans_s: Sign, ans_n: u32) {
3098         let mut inp = BigInt::from_slice(Minus, &[2627_u32, 0_u32, 9182_u32, 42_u32]);
3099         inp.assign_from_slice(inp_s, &[inp_n]);
3100         let ans = BigInt {
3101             sign: ans_s,
3102             data: FromPrimitive::from_u32(ans_n).unwrap(),
3103         };
3104         assert_eq!(inp, ans);
3105     }
3106     check(Plus, 1, Plus, 1);
3107     check(Plus, 0, NoSign, 0);
3108     check(Minus, 1, Minus, 1);
3109     check(NoSign, 1, NoSign, 0);
3110 }
3111