num_bigint/
bigint.rs

1#[allow(deprecated, unused_imports)]
2use std::ascii::AsciiExt;
3use std::cmp::Ordering::{self, Equal, Greater, Less};
4use std::default::Default;
5use std::fmt;
6use std::iter::{Product, Sum};
7use std::mem;
8use 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};
12use std::str::{self, FromStr};
13#[cfg(has_i128)]
14use std::{i128, u128};
15use std::{i64, u64};
16
17#[cfg(feature = "serde")]
18use serde;
19
20use integer::{Integer, Roots};
21use traits::{
22    CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, FromPrimitive, Num, One, Pow, Signed,
23    ToPrimitive, Zero,
24};
25
26use self::Sign::{Minus, NoSign, Plus};
27
28use super::ParseBigIntError;
29use big_digit::{self, BigDigit, DoubleBigDigit};
30use biguint;
31use biguint::to_str_radix_reversed;
32use biguint::{BigUint, IntDigits};
33
34use IsizePromotion;
35use UsizePromotion;
36
37#[cfg(feature = "quickcheck")]
38use quickcheck::{Arbitrary, Gen};
39
40/// A Sign is a `BigInt`'s composing element.
41#[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, Hash)]
42pub enum Sign {
43    Minus,
44    NoSign,
45    Plus,
46}
47
48impl Neg for Sign {
49    type Output = Sign;
50
51    /// Negate Sign value.
52    #[inline]
53    fn neg(self) -> Sign {
54        match self {
55            Minus => Plus,
56            NoSign => NoSign,
57            Plus => Minus,
58        }
59    }
60}
61
62impl Mul<Sign> for Sign {
63    type Output = Sign;
64
65    #[inline]
66    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")]
76impl serde::Serialize for Sign {
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")]
92impl<'de> serde::Deserialize<'de> for Sign {
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)]
115pub struct BigInt {
116    sign: Sign,
117    data: BigUint,
118}
119
120#[cfg(feature = "quickcheck")]
121impl Arbitrary for BigInt {
122    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
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")]
140pub 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")]
148pub fn into_magnitude(i: BigInt) -> BigUint {
149    i.data
150}
151
152impl PartialEq for BigInt {
153    #[inline]
154    fn eq(&self, other: &BigInt) -> bool {
155        self.cmp(other) == Equal
156    }
157}
158
159impl Eq for BigInt {}
160
161impl PartialOrd for BigInt {
162    #[inline]
163    fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
164        Some(self.cmp(other))
165    }
166}
167
168impl Ord for BigInt {
169    #[inline]
170    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
184impl Default for BigInt {
185    #[inline]
186    fn default() -> BigInt {
187        Zero::zero()
188    }
189}
190
191impl fmt::Display for BigInt {
192    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
197impl fmt::Binary for BigInt {
198    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
203impl fmt::Octal for BigInt {
204    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
209impl fmt::LowerHex for BigInt {
210    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
215impl fmt::UpperHex for BigInt {
216    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]
240fn 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
251impl Not for BigInt {
252    type Output = BigInt;
253
254    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
269impl<'a> Not for &'a BigInt {
270    type Output = BigInt;
271
272    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
283fn 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
295fn 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
314fn 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
344forward_val_val_binop!(impl BitAnd for BigInt, bitand);
345forward_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
349impl<'a, 'b> BitAnd<&'b BigInt> for &'a BigInt {
350    type Output = BigInt;
351
352    #[inline]
353    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
371impl<'a> BitAnd<&'a BigInt> for BigInt {
372    type Output = BigInt;
373
374    #[inline]
375    fn bitand(mut self, other: &BigInt) -> BigInt {
376        self &= other;
377        self
378    }
379}
380
381forward_val_assign!(impl BitAndAssign for BigInt, bitand_assign);
382
383impl<'a> BitAndAssign<&'a BigInt> for 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
414fn 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
439fn 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
461fn 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
479forward_val_val_binop!(impl BitOr for BigInt, bitor);
480forward_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
484impl<'a, 'b> BitOr<&'b BigInt> for &'a BigInt {
485    type Output = BigInt;
486
487    #[inline]
488    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
507impl<'a> BitOr<&'a BigInt> for BigInt {
508    type Output = BigInt;
509
510    #[inline]
511    fn bitor(mut self, other: &BigInt) -> BigInt {
512        self |= other;
513        self
514    }
515}
516
517forward_val_assign!(impl BitOrAssign for BigInt, bitor_assign);
518
519impl<'a> BitOrAssign<&'a BigInt> for 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
545fn 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
574fn 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
603fn 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
631forward_all_binop_to_val_ref_commutative!(impl BitXor for BigInt, bitxor);
632
633impl<'a> BitXor<&'a BigInt> for BigInt {
634    type Output = BigInt;
635
636    #[inline]
637    fn bitxor(mut self, other: &BigInt) -> BigInt {
638        self ^= other;
639        self
640    }
641}
642
643forward_val_assign!(impl BitXorAssign for BigInt, bitxor_assign);
644
645impl<'a> BitXorAssign<&'a BigInt> for 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
674impl FromStr for BigInt {
675    type Err = ParseBigIntError;
676
677    #[inline]
678    fn from_str(s: &str) -> Result<BigInt, ParseBigIntError> {
679        BigInt::from_str_radix(s, 10)
680    }
681}
682
683impl Num for BigInt {
684    type FromStrRadixErr = ParseBigIntError;
685
686    /// Creates and initializes a BigInt.
687    #[inline]
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
703impl Shl<usize> for BigInt {
704    type Output = BigInt;
705
706    #[inline]
707    fn shl(mut self, rhs: usize) -> BigInt {
708        self <<= rhs;
709        self
710    }
711}
712
713impl<'a> Shl<usize> for &'a BigInt {
714    type Output = BigInt;
715
716    #[inline]
717    fn shl(self, rhs: usize) -> BigInt {
718        BigInt::from_biguint(self.sign, &self.data << rhs)
719    }
720}
721
722impl ShlAssign<usize> for BigInt {
723    #[inline]
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.
731fn 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
738impl Shr<usize> for BigInt {
739    type Output = BigInt;
740
741    #[inline]
742    fn shr(mut self, rhs: usize) -> BigInt {
743        self >>= rhs;
744        self
745    }
746}
747
748impl<'a> Shr<usize> for &'a BigInt {
749    type Output = BigInt;
750
751    #[inline]
752    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
759impl ShrAssign<usize> for BigInt {
760    #[inline]
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
772impl Zero for BigInt {
773    #[inline]
774    fn zero() -> BigInt {
775        BigInt::from_biguint(NoSign, Zero::zero())
776    }
777
778    #[inline]
779    fn set_zero(&mut self) {
780        self.data.set_zero();
781        self.sign = NoSign;
782    }
783
784    #[inline]
785    fn is_zero(&self) -> bool {
786        self.sign == NoSign
787    }
788}
789
790impl One for BigInt {
791    #[inline]
792    fn one() -> BigInt {
793        BigInt::from_biguint(Plus, One::one())
794    }
795
796    #[inline]
797    fn set_one(&mut self) {
798        self.data.set_one();
799        self.sign = Plus;
800    }
801
802    #[inline]
803    fn is_one(&self) -> bool {
804        self.sign == Plus && self.data.is_one()
805    }
806}
807
808impl Signed for BigInt {
809    #[inline]
810    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]
818    fn abs_sub(&self, other: &BigInt) -> BigInt {
819        if *self <= *other {
820            Zero::zero()
821        } else {
822            self - other
823        }
824    }
825
826    #[inline]
827    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]
836    fn is_positive(&self) -> bool {
837        self.sign == Plus
838    }
839
840    #[inline]
841    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]
850fn 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
862macro_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
884pow_impl!(u8);
885pow_impl!(u16);
886pow_impl!(u32);
887pow_impl!(u64);
888pow_impl!(usize);
889#[cfg(has_i128)]
890pow_impl!(u128);
891pow_impl!(BigUint);
892
893// A convenience method for getting the absolute value of an i32 in a u32.
894#[inline]
895fn 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]
905fn 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]
916fn 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.
927macro_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
944impl<'a, 'b> Add<&'b BigInt> for &'a BigInt {
945    type Output = BigInt;
946
947    #[inline]
948    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
960impl<'a> Add<BigInt> for &'a BigInt {
961    type Output = BigInt;
962
963    #[inline]
964    fn add(self, other: BigInt) -> BigInt {
965        bigint_add!(self, self.clone(), &self.data, other, other, other.data)
966    }
967}
968
969impl<'a> Add<&'a BigInt> for BigInt {
970    type Output = BigInt;
971
972    #[inline]
973    fn add(self, other: &BigInt) -> BigInt {
974        bigint_add!(self, self, self.data, other, other.clone(), &other.data)
975    }
976}
977
978impl Add<BigInt> for BigInt {
979    type Output = BigInt;
980
981    #[inline]
982    fn add(self, other: BigInt) -> BigInt {
983        bigint_add!(self, self, self.data, other, other, other.data)
984    }
985}
986
987impl<'a> AddAssign<&'a BigInt> for BigInt {
988    #[inline]
989    fn add_assign(&mut self, other: &BigInt) {
990        let n = mem::replace(self, BigInt::zero());
991        *self = n + other;
992    }
993}
994forward_val_assign!(impl AddAssign for BigInt, add_assign);
995
996promote_all_scalars!(impl Add for BigInt, add);
997promote_all_scalars_assign!(impl AddAssign for BigInt, add_assign);
998forward_all_scalar_binop_to_val_val_commutative!(impl Add<u32> for BigInt, add);
999forward_all_scalar_binop_to_val_val_commutative!(impl Add<u64> for BigInt, add);
1000#[cfg(has_i128)]
1001forward_all_scalar_binop_to_val_val_commutative!(impl Add<u128> for BigInt, add);
1002
1003impl Add<u32> for BigInt {
1004    type Output = BigInt;
1005
1006    #[inline]
1007    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}
1019impl AddAssign<u32> for BigInt {
1020    #[inline]
1021    fn add_assign(&mut self, other: u32) {
1022        let n = mem::replace(self, BigInt::zero());
1023        *self = n + other;
1024    }
1025}
1026
1027impl Add<u64> for BigInt {
1028    type Output = BigInt;
1029
1030    #[inline]
1031    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}
1043impl AddAssign<u64> for BigInt {
1044    #[inline]
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)]
1052impl Add<u128> for BigInt {
1053    type Output = BigInt;
1054
1055    #[inline]
1056    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)]
1069impl AddAssign<u128> for BigInt {
1070    #[inline]
1071    fn add_assign(&mut self, other: u128) {
1072        let n = mem::replace(self, BigInt::zero());
1073        *self = n + other;
1074    }
1075}
1076
1077forward_all_scalar_binop_to_val_val_commutative!(impl Add<i32> for BigInt, add);
1078forward_all_scalar_binop_to_val_val_commutative!(impl Add<i64> for BigInt, add);
1079#[cfg(has_i128)]
1080forward_all_scalar_binop_to_val_val_commutative!(impl Add<i128> for BigInt, add);
1081
1082impl Add<i32> for BigInt {
1083    type Output = BigInt;
1084
1085    #[inline]
1086    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}
1094impl AddAssign<i32> for BigInt {
1095    #[inline]
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
1105impl Add<i64> for BigInt {
1106    type Output = BigInt;
1107
1108    #[inline]
1109    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}
1117impl AddAssign<i64> for BigInt {
1118    #[inline]
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)]
1129impl Add<i128> for BigInt {
1130    type Output = BigInt;
1131
1132    #[inline]
1133    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)]
1142impl AddAssign<i128> for BigInt {
1143    #[inline]
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.
1156macro_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
1173impl<'a, 'b> Sub<&'b BigInt> for &'a BigInt {
1174    type Output = BigInt;
1175
1176    #[inline]
1177    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
1189impl<'a> Sub<BigInt> for &'a BigInt {
1190    type Output = BigInt;
1191
1192    #[inline]
1193    fn sub(self, other: BigInt) -> BigInt {
1194        bigint_sub!(self, self.clone(), &self.data, other, other, other.data)
1195    }
1196}
1197
1198impl<'a> Sub<&'a BigInt> for BigInt {
1199    type Output = BigInt;
1200
1201    #[inline]
1202    fn sub(self, other: &BigInt) -> BigInt {
1203        bigint_sub!(self, self, self.data, other, other.clone(), &other.data)
1204    }
1205}
1206
1207impl Sub<BigInt> for BigInt {
1208    type Output = BigInt;
1209
1210    #[inline]
1211    fn sub(self, other: BigInt) -> BigInt {
1212        bigint_sub!(self, self, self.data, other, other, other.data)
1213    }
1214}
1215
1216impl<'a> SubAssign<&'a BigInt> for BigInt {
1217    #[inline]
1218    fn sub_assign(&mut self, other: &BigInt) {
1219        let n = mem::replace(self, BigInt::zero());
1220        *self = n - other;
1221    }
1222}
1223forward_val_assign!(impl SubAssign for BigInt, sub_assign);
1224
1225promote_all_scalars!(impl Sub for BigInt, sub);
1226promote_all_scalars_assign!(impl SubAssign for BigInt, sub_assign);
1227forward_all_scalar_binop_to_val_val!(impl Sub<u32> for BigInt, sub);
1228forward_all_scalar_binop_to_val_val!(impl Sub<u64> for BigInt, sub);
1229#[cfg(has_i128)]
1230forward_all_scalar_binop_to_val_val!(impl Sub<u128> for BigInt, sub);
1231
1232impl Sub<u32> for BigInt {
1233    type Output = BigInt;
1234
1235    #[inline]
1236    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}
1248impl SubAssign<u32> for BigInt {
1249    #[inline]
1250    fn sub_assign(&mut self, other: u32) {
1251        let n = mem::replace(self, BigInt::zero());
1252        *self = n - other;
1253    }
1254}
1255
1256impl Sub<BigInt> for u32 {
1257    type Output = BigInt;
1258
1259    #[inline]
1260    fn sub(self, other: BigInt) -> BigInt {
1261        -(other - self)
1262    }
1263}
1264
1265impl Sub<BigInt> for u64 {
1266    type Output = BigInt;
1267
1268    #[inline]
1269    fn sub(self, other: BigInt) -> BigInt {
1270        -(other - self)
1271    }
1272}
1273#[cfg(has_i128)]
1274impl Sub<BigInt> for u128 {
1275    type Output = BigInt;
1276
1277    #[inline]
1278    fn sub(self, other: BigInt) -> BigInt {
1279        -(other - self)
1280    }
1281}
1282
1283impl Sub<u64> for BigInt {
1284    type Output = BigInt;
1285
1286    #[inline]
1287    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}
1299impl SubAssign<u64> for BigInt {
1300    #[inline]
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)]
1308impl Sub<u128> for BigInt {
1309    type Output = BigInt;
1310
1311    #[inline]
1312    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)]
1325impl SubAssign<u128> for BigInt {
1326    #[inline]
1327    fn sub_assign(&mut self, other: u128) {
1328        let n = mem::replace(self, BigInt::zero());
1329        *self = n - other;
1330    }
1331}
1332
1333forward_all_scalar_binop_to_val_val!(impl Sub<i32> for BigInt, sub);
1334forward_all_scalar_binop_to_val_val!(impl Sub<i64> for BigInt, sub);
1335#[cfg(has_i128)]
1336forward_all_scalar_binop_to_val_val!(impl Sub<i128> for BigInt, sub);
1337
1338impl Sub<i32> for BigInt {
1339    type Output = BigInt;
1340
1341    #[inline]
1342    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}
1350impl SubAssign<i32> for BigInt {
1351    #[inline]
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
1361impl Sub<BigInt> for i32 {
1362    type Output = BigInt;
1363
1364    #[inline]
1365    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
1374impl Sub<i64> for BigInt {
1375    type Output = BigInt;
1376
1377    #[inline]
1378    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}
1386impl SubAssign<i64> for BigInt {
1387    #[inline]
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
1397impl Sub<BigInt> for i64 {
1398    type Output = BigInt;
1399
1400    #[inline]
1401    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)]
1411impl Sub<i128> for BigInt {
1412    type Output = BigInt;
1413
1414    #[inline]
1415    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)]
1424impl SubAssign<i128> for BigInt {
1425    #[inline]
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)]
1435impl Sub<BigInt> for i128 {
1436    type Output = BigInt;
1437
1438    #[inline]
1439    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
1448forward_all_binop_to_ref_ref!(impl Mul for BigInt, mul);
1449
1450impl<'a, 'b> Mul<&'b BigInt> for &'a BigInt {
1451    type Output = BigInt;
1452
1453    #[inline]
1454    fn mul(self, other: &BigInt) -> BigInt {
1455        BigInt::from_biguint(self.sign * other.sign, &self.data * &other.data)
1456    }
1457}
1458
1459impl<'a> MulAssign<&'a BigInt> for BigInt {
1460    #[inline]
1461    fn mul_assign(&mut self, other: &BigInt) {
1462        *self = &*self * other;
1463    }
1464}
1465forward_val_assign!(impl MulAssign for BigInt, mul_assign);
1466
1467promote_all_scalars!(impl Mul for BigInt, mul);
1468promote_all_scalars_assign!(impl MulAssign for BigInt, mul_assign);
1469forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u32> for BigInt, mul);
1470forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u64> for BigInt, mul);
1471#[cfg(has_i128)]
1472forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u128> for BigInt, mul);
1473
1474impl Mul<u32> for BigInt {
1475    type Output = BigInt;
1476
1477    #[inline]
1478    fn mul(self, other: u32) -> BigInt {
1479        BigInt::from_biguint(self.sign, self.data * other)
1480    }
1481}
1482
1483impl MulAssign<u32> for BigInt {
1484    #[inline]
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
1493impl Mul<u64> for BigInt {
1494    type Output = BigInt;
1495
1496    #[inline]
1497    fn mul(self, other: u64) -> BigInt {
1498        BigInt::from_biguint(self.sign, self.data * other)
1499    }
1500}
1501
1502impl MulAssign<u64> for BigInt {
1503    #[inline]
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)]
1512impl Mul<u128> for BigInt {
1513    type Output = BigInt;
1514
1515    #[inline]
1516    fn mul(self, other: u128) -> BigInt {
1517        BigInt::from_biguint(self.sign, self.data * other)
1518    }
1519}
1520#[cfg(has_i128)]
1521impl MulAssign<u128> for BigInt {
1522    #[inline]
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
1531forward_all_scalar_binop_to_val_val_commutative!(impl Mul<i32> for BigInt, mul);
1532forward_all_scalar_binop_to_val_val_commutative!(impl Mul<i64> for BigInt, mul);
1533#[cfg(has_i128)]
1534forward_all_scalar_binop_to_val_val_commutative!(impl Mul<i128> for BigInt, mul);
1535
1536impl Mul<i32> for BigInt {
1537    type Output = BigInt;
1538
1539    #[inline]
1540    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
1549impl MulAssign<i32> for BigInt {
1550    #[inline]
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
1561impl Mul<i64> for BigInt {
1562    type Output = BigInt;
1563
1564    #[inline]
1565    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
1574impl MulAssign<i64> for BigInt {
1575    #[inline]
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)]
1586impl Mul<i128> for BigInt {
1587    type Output = BigInt;
1588
1589    #[inline]
1590    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)]
1599impl MulAssign<i128> for BigInt {
1600    #[inline]
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
1611forward_all_binop_to_ref_ref!(impl Div for BigInt, div);
1612
1613impl<'a, 'b> Div<&'b BigInt> for &'a BigInt {
1614    type Output = BigInt;
1615
1616    #[inline]
1617    fn div(self, other: &BigInt) -> BigInt {
1618        let (q, _) = self.div_rem(other);
1619        q
1620    }
1621}
1622
1623impl<'a> DivAssign<&'a BigInt> for BigInt {
1624    #[inline]
1625    fn div_assign(&mut self, other: &BigInt) {
1626        *self = &*self / other;
1627    }
1628}
1629forward_val_assign!(impl DivAssign for BigInt, div_assign);
1630
1631promote_all_scalars!(impl Div for BigInt, div);
1632promote_all_scalars_assign!(impl DivAssign for BigInt, div_assign);
1633forward_all_scalar_binop_to_val_val!(impl Div<u32> for BigInt, div);
1634forward_all_scalar_binop_to_val_val!(impl Div<u64> for BigInt, div);
1635#[cfg(has_i128)]
1636forward_all_scalar_binop_to_val_val!(impl Div<u128> for BigInt, div);
1637
1638impl Div<u32> for BigInt {
1639    type Output = BigInt;
1640
1641    #[inline]
1642    fn div(self, other: u32) -> BigInt {
1643        BigInt::from_biguint(self.sign, self.data / other)
1644    }
1645}
1646
1647impl DivAssign<u32> for BigInt {
1648    #[inline]
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
1657impl Div<BigInt> for u32 {
1658    type Output = BigInt;
1659
1660    #[inline]
1661    fn div(self, other: BigInt) -> BigInt {
1662        BigInt::from_biguint(other.sign, self / other.data)
1663    }
1664}
1665
1666impl Div<u64> for BigInt {
1667    type Output = BigInt;
1668
1669    #[inline]
1670    fn div(self, other: u64) -> BigInt {
1671        BigInt::from_biguint(self.sign, self.data / other)
1672    }
1673}
1674
1675impl DivAssign<u64> for BigInt {
1676    #[inline]
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
1685impl Div<BigInt> for u64 {
1686    type Output = BigInt;
1687
1688    #[inline]
1689    fn div(self, other: BigInt) -> BigInt {
1690        BigInt::from_biguint(other.sign, self / other.data)
1691    }
1692}
1693
1694#[cfg(has_i128)]
1695impl Div<u128> for BigInt {
1696    type Output = BigInt;
1697
1698    #[inline]
1699    fn div(self, other: u128) -> BigInt {
1700        BigInt::from_biguint(self.sign, self.data / other)
1701    }
1702}
1703
1704#[cfg(has_i128)]
1705impl DivAssign<u128> for BigInt {
1706    #[inline]
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)]
1716impl Div<BigInt> for u128 {
1717    type Output = BigInt;
1718
1719    #[inline]
1720    fn div(self, other: BigInt) -> BigInt {
1721        BigInt::from_biguint(other.sign, self / other.data)
1722    }
1723}
1724
1725forward_all_scalar_binop_to_val_val!(impl Div<i32> for BigInt, div);
1726forward_all_scalar_binop_to_val_val!(impl Div<i64> for BigInt, div);
1727#[cfg(has_i128)]
1728forward_all_scalar_binop_to_val_val!(impl Div<i128> for BigInt, div);
1729
1730impl Div<i32> for BigInt {
1731    type Output = BigInt;
1732
1733    #[inline]
1734    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
1743impl DivAssign<i32> for BigInt {
1744    #[inline]
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
1755impl Div<BigInt> for i32 {
1756    type Output = BigInt;
1757
1758    #[inline]
1759    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
1768impl Div<i64> for BigInt {
1769    type Output = BigInt;
1770
1771    #[inline]
1772    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
1781impl DivAssign<i64> for BigInt {
1782    #[inline]
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
1793impl Div<BigInt> for i64 {
1794    type Output = BigInt;
1795
1796    #[inline]
1797    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)]
1807impl Div<i128> for BigInt {
1808    type Output = BigInt;
1809
1810    #[inline]
1811    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)]
1821impl DivAssign<i128> for BigInt {
1822    #[inline]
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)]
1834impl Div<BigInt> for i128 {
1835    type Output = BigInt;
1836
1837    #[inline]
1838    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
1847forward_all_binop_to_ref_ref!(impl Rem for BigInt, rem);
1848
1849impl<'a, 'b> Rem<&'b BigInt> for &'a BigInt {
1850    type Output = BigInt;
1851
1852    #[inline]
1853    fn rem(self, other: &BigInt) -> BigInt {
1854        let (_, r) = self.div_rem(other);
1855        r
1856    }
1857}
1858
1859impl<'a> RemAssign<&'a BigInt> for BigInt {
1860    #[inline]
1861    fn rem_assign(&mut self, other: &BigInt) {
1862        *self = &*self % other;
1863    }
1864}
1865forward_val_assign!(impl RemAssign for BigInt, rem_assign);
1866
1867promote_all_scalars!(impl Rem for BigInt, rem);
1868promote_all_scalars_assign!(impl RemAssign for BigInt, rem_assign);
1869forward_all_scalar_binop_to_val_val!(impl Rem<u32> for BigInt, rem);
1870forward_all_scalar_binop_to_val_val!(impl Rem<u64> for BigInt, rem);
1871#[cfg(has_i128)]
1872forward_all_scalar_binop_to_val_val!(impl Rem<u128> for BigInt, rem);
1873
1874impl Rem<u32> for BigInt {
1875    type Output = BigInt;
1876
1877    #[inline]
1878    fn rem(self, other: u32) -> BigInt {
1879        BigInt::from_biguint(self.sign, self.data % other)
1880    }
1881}
1882
1883impl RemAssign<u32> for BigInt {
1884    #[inline]
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
1893impl Rem<BigInt> for u32 {
1894    type Output = BigInt;
1895
1896    #[inline]
1897    fn rem(self, other: BigInt) -> BigInt {
1898        BigInt::from_biguint(Plus, self % other.data)
1899    }
1900}
1901
1902impl Rem<u64> for BigInt {
1903    type Output = BigInt;
1904
1905    #[inline]
1906    fn rem(self, other: u64) -> BigInt {
1907        BigInt::from_biguint(self.sign, self.data % other)
1908    }
1909}
1910
1911impl RemAssign<u64> for BigInt {
1912    #[inline]
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
1921impl Rem<BigInt> for u64 {
1922    type Output = BigInt;
1923
1924    #[inline]
1925    fn rem(self, other: BigInt) -> BigInt {
1926        BigInt::from_biguint(Plus, self % other.data)
1927    }
1928}
1929
1930#[cfg(has_i128)]
1931impl Rem<u128> for BigInt {
1932    type Output = BigInt;
1933
1934    #[inline]
1935    fn rem(self, other: u128) -> BigInt {
1936        BigInt::from_biguint(self.sign, self.data % other)
1937    }
1938}
1939
1940#[cfg(has_i128)]
1941impl RemAssign<u128> for BigInt {
1942    #[inline]
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)]
1952impl Rem<BigInt> for u128 {
1953    type Output = BigInt;
1954
1955    #[inline]
1956    fn rem(self, other: BigInt) -> BigInt {
1957        BigInt::from_biguint(Plus, self % other.data)
1958    }
1959}
1960
1961forward_all_scalar_binop_to_val_val!(impl Rem<i32> for BigInt, rem);
1962forward_all_scalar_binop_to_val_val!(impl Rem<i64> for BigInt, rem);
1963#[cfg(has_i128)]
1964forward_all_scalar_binop_to_val_val!(impl Rem<i128> for BigInt, rem);
1965
1966impl Rem<i32> for BigInt {
1967    type Output = BigInt;
1968
1969    #[inline]
1970    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
1979impl RemAssign<i32> for BigInt {
1980    #[inline]
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
1990impl Rem<BigInt> for i32 {
1991    type Output = BigInt;
1992
1993    #[inline]
1994    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
2003impl Rem<i64> for BigInt {
2004    type Output = BigInt;
2005
2006    #[inline]
2007    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
2016impl RemAssign<i64> for BigInt {
2017    #[inline]
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
2027impl Rem<BigInt> for i64 {
2028    type Output = BigInt;
2029
2030    #[inline]
2031    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)]
2041impl Rem<i128> for BigInt {
2042    type Output = BigInt;
2043
2044    #[inline]
2045    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)]
2054impl RemAssign<i128> for BigInt {
2055    #[inline]
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)]
2065impl Rem<BigInt> for i128 {
2066    type Output = BigInt;
2067
2068    #[inline]
2069    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
2078impl Neg for BigInt {
2079    type Output = BigInt;
2080
2081    #[inline]
2082    fn neg(mut self) -> BigInt {
2083        self.sign = -self.sign;
2084        self
2085    }
2086}
2087
2088impl<'a> Neg for &'a BigInt {
2089    type Output = BigInt;
2090
2091    #[inline]
2092    fn neg(self) -> BigInt {
2093        -self.clone()
2094    }
2095}
2096
2097impl CheckedAdd for BigInt {
2098    #[inline]
2099    fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
2100        Some(self.add(v))
2101    }
2102}
2103
2104impl CheckedSub for BigInt {
2105    #[inline]
2106    fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
2107        Some(self.sub(v))
2108    }
2109}
2110
2111impl CheckedMul for BigInt {
2112    #[inline]
2113    fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
2114        Some(self.mul(v))
2115    }
2116}
2117
2118impl CheckedDiv for BigInt {
2119    #[inline]
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
2128impl Integer for BigInt {
2129    #[inline]
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]
2143    fn div_floor(&self, other: &BigInt) -> BigInt {
2144        let (d, _) = self.div_mod_floor(other);
2145        d
2146    }
2147
2148    #[inline]
2149    fn mod_floor(&self, other: &BigInt) -> BigInt {
2150        let (_, m) = self.div_mod_floor(other);
2151        m
2152    }
2153
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]
2185    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]
2191    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]
2197    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]
2203    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]
2209    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]
2215    fn is_odd(&self) -> bool {
2216        self.data.is_odd()
2217    }
2218}
2219
2220impl Roots for BigInt {
2221    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
2231    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
2237    fn cbrt(&self) -> Self {
2238        BigInt::from_biguint(self.sign, self.data.cbrt())
2239    }
2240}
2241
2242impl ToPrimitive for BigInt {
2243    #[inline]
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)]
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]
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)]
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]
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]
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
2314impl FromPrimitive for BigInt {
2315    #[inline]
2316    fn from_i64(n: i64) -> Option<BigInt> {
2317        Some(BigInt::from(n))
2318    }
2319
2320    #[inline]
2321    #[cfg(has_i128)]
2322    fn from_i128(n: i128) -> Option<BigInt> {
2323        Some(BigInt::from(n))
2324    }
2325
2326    #[inline]
2327    fn from_u64(n: u64) -> Option<BigInt> {
2328        Some(BigInt::from(n))
2329    }
2330
2331    #[inline]
2332    #[cfg(has_i128)]
2333    fn from_u128(n: u128) -> Option<BigInt> {
2334        Some(BigInt::from(n))
2335    }
2336
2337    #[inline]
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
2347impl From<i64> for BigInt {
2348    #[inline]
2349    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)]
2363impl From<i128> for BigInt {
2364    #[inline]
2365    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
2378macro_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
2389impl_bigint_from_int!(i8);
2390impl_bigint_from_int!(i16);
2391impl_bigint_from_int!(i32);
2392impl_bigint_from_int!(isize);
2393
2394impl From<u64> for BigInt {
2395    #[inline]
2396    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)]
2409impl From<u128> for BigInt {
2410    #[inline]
2411    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
2423macro_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
2434impl_bigint_from_uint!(u8);
2435impl_bigint_from_uint!(u16);
2436impl_bigint_from_uint!(u32);
2437impl_bigint_from_uint!(usize);
2438
2439impl From<BigUint> for BigInt {
2440    #[inline]
2441    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
2453impl IntDigits for BigInt {
2454    #[inline]
2455    fn digits(&self) -> &[BigDigit] {
2456        self.data.digits()
2457    }
2458    #[inline]
2459    fn digits_mut(&mut self) -> &mut Vec<BigDigit> {
2460        self.data.digits_mut()
2461    }
2462    #[inline]
2463    fn normalize(&mut self) {
2464        self.data.normalize();
2465        if self.data.is_zero() {
2466            self.sign = NoSign;
2467        }
2468    }
2469    #[inline]
2470    fn capacity(&self) -> usize {
2471        self.data.capacity()
2472    }
2473    #[inline]
2474    fn len(&self) -> usize {
2475        self.data.len()
2476    }
2477}
2478
2479#[cfg(feature = "serde")]
2480impl serde::Serialize for BigInt {
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")]
2492impl<'de> serde::Deserialize<'de> for BigInt {
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`.
2505pub trait ToBigInt {
2506    /// Converts the value of `self` to a `BigInt`.
2507    fn to_bigint(&self) -> Option<BigInt>;
2508}
2509
2510impl ToBigInt for BigInt {
2511    #[inline]
2512    fn to_bigint(&self) -> Option<BigInt> {
2513        Some(self.clone())
2514    }
2515}
2516
2517impl ToBigInt for BigUint {
2518    #[inline]
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
2531impl biguint::ToBigUint for BigInt {
2532    #[inline]
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
2542macro_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
2553impl_to_bigint!(isize, FromPrimitive::from_isize);
2554impl_to_bigint!(i8, FromPrimitive::from_i8);
2555impl_to_bigint!(i16, FromPrimitive::from_i16);
2556impl_to_bigint!(i32, FromPrimitive::from_i32);
2557impl_to_bigint!(i64, FromPrimitive::from_i64);
2558#[cfg(has_i128)]
2559impl_to_bigint!(i128, FromPrimitive::from_i128);
2560
2561impl_to_bigint!(usize, FromPrimitive::from_usize);
2562impl_to_bigint!(u8, FromPrimitive::from_u8);
2563impl_to_bigint!(u16, FromPrimitive::from_u16);
2564impl_to_bigint!(u32, FromPrimitive::from_u32);
2565impl_to_bigint!(u64, FromPrimitive::from_u64);
2566#[cfg(has_i128)]
2567impl_to_bigint!(u128, FromPrimitive::from_u128);
2568
2569impl_to_bigint!(f32, FromPrimitive::from_f32);
2570impl_to_bigint!(f64, FromPrimitive::from_f64);
2571
2572impl BigInt {
2573    /// Creates and initializes a BigInt.
2574    ///
2575    /// The base 2<sup>32</sup> digits are ordered least significant digit first.
2576    #[inline]
2577    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]
2585    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]
2602    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]
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]
2642    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]
2650    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]
2659    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]
2680    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]
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    /// ```
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    /// ```
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]
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]
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]
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]
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]
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]
2872    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]
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]
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]
2933    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]
2940    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]
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]
2955    pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
2956        Some(self.add(v))
2957    }
2958
2959    #[inline]
2960    pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
2961        Some(self.sub(v))
2962    }
2963
2964    #[inline]
2965    pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
2966        Some(self.mul(v))
2967    }
2968
2969    #[inline]
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.
2985    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).
3012    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).
3018    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).
3024    pub fn nth_root(&self, n: u32) -> Self {
3025        Roots::nth_root(self, n)
3026    }
3027}
3028
3029impl_sum_iter_type!(BigInt);
3030impl_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]
3035fn 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]
3042fn 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]
3049fn twos_complement<'a, I>(digits: I)
3050where
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]
3064fn 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]
3080fn 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]
3096fn 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}