num_bigint_dig/
bigint.rs

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