amplify_num/
bigint.rs

1// Rust language amplification library providing multiple generic trait
2// implementations, type wrappers, derive macros and other language enhancements
3//
4// Written in 2014 by
5//     Andrew Poelstra <apoelstra@wpsoftware.net>
6// Refactored & fixed in 2021-2024 by
7//     Dr. Maxim Orlovsky <orlovsky@ubideco.org>
8//
9// To the extent possible under law, the author(s) have dedicated all
10// copyright and related and neighboring rights to this software to
11// the public domain worldwide. This software is distributed without
12// any warranty.
13//
14// You should have received a copy of the MIT License
15// along with this software.
16// If not, see <https://opensource.org/licenses/MIT>.
17
18use crate::error::{DivError, ParseLengthError};
19
20macro_rules! construct_bigint {
21    ($name:ident, $n_words:expr) => {
22        /// Large integer type
23        ///
24        /// The type is composed of little-endian ordered 64-bit words, which represents
25        /// its inner representation.
26        #[allow(non_camel_case_types)]
27        #[derive(Copy, Clone, PartialEq, Eq, Hash, Default)]
28        pub struct $name([u64; $n_words]);
29
30        impl $name {
31            #[inline]
32            /// Converts the object to a raw pointer
33            pub fn as_ptr(&self) -> *const u64 {
34                let &$name(ref dat) = self;
35                dat.as_ptr()
36            }
37
38            #[inline]
39            /// Converts the object to a mutable raw pointer
40            pub fn as_mut_ptr(&mut self) -> *mut u64 {
41                let &mut $name(ref mut dat) = self;
42                dat.as_mut_ptr()
43            }
44
45            #[inline]
46            /// Returns the underlying array of words constituting large integer
47            pub const fn as_inner(&self) -> &[u64; $n_words] { &self.0 }
48
49            #[inline]
50            /// Returns the underlying array of words constituting large integer
51            pub const fn into_inner(self) -> [u64; $n_words] { self.0 }
52
53            #[inline]
54            /// Constructs integer type from the underlying array of words.
55            pub const fn from_inner(array: [u64; $n_words]) -> Self { Self(array) }
56        }
57
58        impl $name {
59            /// Zero value
60            pub const ZERO: $name = $name([0u64; $n_words]);
61
62            /// Value for `1`
63            pub const ONE: $name = $name({
64                let mut one = [0u64; $n_words];
65                one[0] = 1u64;
66                one
67            });
68
69            /// Bit dimension
70            pub const BITS: u32 = $n_words * 64;
71
72            /// Length of the integer in bytes
73            pub const BYTES: u8 = $n_words * 8;
74
75            /// Length of the inner representation in 64-bit words
76            pub const INNER_LEN: u8 = $n_words;
77
78            /// Returns whether specific bit number is set to `1` or not
79            #[inline]
80            pub const fn bit(&self, index: usize) -> bool {
81                let &$name(ref arr) = self;
82                arr[index / 64] & (1 << (index % 64)) != 0
83            }
84
85            /// Returns lower 32 bits of the number as `u32`
86            #[inline]
87            pub const fn low_u32(&self) -> u32 {
88                let &$name(ref arr) = self;
89                (arr[0] & u32::MAX as u64) as u32
90            }
91
92            /// Returns lower 64 bits of the number as `u32`
93            #[inline]
94            pub const fn low_u64(&self) -> u64 {
95                let &$name(ref arr) = self;
96                arr[0] as u64
97            }
98
99            /// Returns the number of leading ones in the binary representation of
100            /// `self`.
101            #[inline]
102            pub fn leading_ones(&self) -> u32 {
103                for i in 0..$n_words {
104                    let leading_ones = (!self[$n_words - i - 1]).leading_zeros();
105                    if leading_ones != 64 {
106                        return 64 * i as u32 + leading_ones;
107                    }
108                }
109                64 * $n_words
110            }
111
112            /// Returns the number of leading zeros in the binary representation of
113            /// `self`.
114            #[inline]
115            pub fn leading_zeros(&self) -> u32 {
116                for i in 0..$n_words {
117                    let leading_zeros = self[$n_words - i - 1].leading_zeros();
118                    if leading_zeros != 64 {
119                        return 64 * i as u32 + leading_zeros;
120                    }
121                }
122                64 * $n_words
123            }
124
125            /// Returns the number of trailing ones in the binary representation of
126            /// `self`.
127            #[inline]
128            pub fn trailing_ones(&self) -> u32 {
129                for i in 0..$n_words {
130                    let trailing_ones = (!self[i]).trailing_zeros();
131                    if trailing_ones != 64 {
132                        return 64 * i as u32 + trailing_ones;
133                    }
134                }
135                64 * $n_words
136            }
137
138            /// Returns the number of trailing zeros in the binary representation of
139            /// `self`.
140            #[inline]
141            pub fn trailing_zeros(&self) -> u32 {
142                for i in 0..$n_words {
143                    let trailing_zeros = self[i].trailing_zeros();
144                    if trailing_zeros != 64 {
145                        return 64 * i as u32 + trailing_zeros;
146                    }
147                }
148                64 * $n_words
149            }
150
151            #[inline]
152            pub fn is_zero(&self) -> bool { self[..] == [0; $n_words] }
153
154            #[inline]
155            pub fn is_positive(&self) -> bool { !self.is_negative() && !self.is_zero() }
156
157            #[inline]
158            pub fn abs(self) -> $name {
159                if !self.is_negative() {
160                    return self;
161                }
162                (!self).wrapping_add($name::ONE)
163            }
164
165            /// Creates the integer value from a byte array using big-endian
166            /// encoding
167            pub fn from_be_bytes(bytes: [u8; $n_words * 8]) -> $name {
168                Self::_from_be_slice(&bytes)
169            }
170
171            /// Creates the integer value from a byte slice using big-endian
172            /// encoding
173            pub fn from_be_slice(bytes: &[u8]) -> Result<$name, ParseLengthError> {
174                if bytes.len() != $n_words * 8 {
175                    Err(ParseLengthError {
176                        actual: bytes.len(),
177                        expected: $n_words * 8,
178                    })
179                } else {
180                    Ok(Self::_from_be_slice(bytes))
181                }
182            }
183
184            /// Creates the integer value from a byte array using little-endian
185            /// encoding
186            pub fn from_le_bytes(bytes: [u8; $n_words * 8]) -> $name {
187                Self::_from_le_slice(&bytes)
188            }
189
190            /// Creates the integer value from a byte slice using little-endian
191            /// encoding
192            pub fn from_le_slice(bytes: &[u8]) -> Result<$name, ParseLengthError> {
193                if bytes.len() != $n_words * 8 {
194                    Err(ParseLengthError {
195                        actual: bytes.len(),
196                        expected: $n_words * 8,
197                    })
198                } else {
199                    Ok(Self::_from_le_slice(bytes))
200                }
201            }
202
203            fn _from_be_slice(bytes: &[u8]) -> $name {
204                let mut slice = [0u64; $n_words];
205                slice
206                    .iter_mut()
207                    .rev()
208                    .zip(bytes.chunks(8).into_iter().map(|s| {
209                        let mut b = [0u8; 8];
210                        b.copy_from_slice(s);
211                        b
212                    }))
213                    .for_each(|(word, bytes)| *word = u64::from_be_bytes(bytes));
214                $name(slice)
215            }
216
217            fn _from_le_slice(bytes: &[u8]) -> $name {
218                let mut slice = [0u64; $n_words];
219                slice
220                    .iter_mut()
221                    .zip(bytes.chunks(8).into_iter().map(|s| {
222                        let mut b = [0u8; 8];
223                        b.copy_from_slice(s);
224                        b
225                    }))
226                    .for_each(|(word, bytes)| *word = u64::from_le_bytes(bytes));
227                $name(slice)
228            }
229
230            /// Convert the integer into a byte array using big-endian encoding
231            pub fn to_be_bytes(self) -> [u8; $n_words * 8] {
232                let mut res = [0; $n_words * 8];
233                for i in 0..$n_words {
234                    let start = i * 8;
235                    res[start..start + 8]
236                        .copy_from_slice(&self.0[$n_words - (i + 1)].to_be_bytes());
237                }
238                res
239            }
240
241            /// Convert a integer into a byte array using little-endian encoding
242            pub fn to_le_bytes(self) -> [u8; $n_words * 8] {
243                let mut res = [0; $n_words * 8];
244                for i in 0..$n_words {
245                    let start = i * 8;
246                    res[start..start + 8].copy_from_slice(&self.0[i].to_le_bytes());
247                }
248                res
249            }
250
251            // divmod like operation, returns (quotient, remainder)
252            #[inline]
253            fn div_rem(self, other: Self) -> Result<(Self, Self), DivError> {
254                // Check for division by 0
255                if other.is_zero() {
256                    return Err(DivError::ZeroDiv);
257                }
258                if other.is_negative() && self == Self::MIN && other == Self::ONE.wrapping_neg() {
259                    return Err(DivError::Overflow);
260                }
261                let mut me = self.abs();
262                let mut you = other.abs();
263                let mut ret = [0u64; $n_words];
264                if self.is_negative() == other.is_negative() && me < you {
265                    return Ok(($name(ret), self));
266                }
267
268                let shift = me.bits_required() - you.bits_required();
269                you <<= shift;
270                for i in (0..=shift).rev() {
271                    if me >= you {
272                        ret[i / 64] |= 1 << (i % 64);
273                        me -= you;
274                    }
275                    you >>= 1;
276                }
277
278                Ok((
279                    if self.is_negative() == other.is_negative() {
280                        Self(ret)
281                    } else {
282                        -Self(ret)
283                    },
284                    if self.is_negative() { -me } else { me },
285                ))
286            }
287
288            #[inline]
289            fn div_rem_euclid(self, other: Self) -> Result<(Self, Self), DivError> {
290                self.div_rem(other).map(|(q, r)| {
291                    (
292                        match (r.is_negative(), other.is_positive()) {
293                            (true, true) => q.wrapping_sub(Self::ONE),
294                            (true, false) => q.wrapping_add(Self::ONE),
295                            _ => q,
296                        },
297                        match (r.is_negative(), other.is_positive()) {
298                            (true, true) => r.wrapping_add(other),
299                            (true, false) => r.wrapping_sub(other),
300                            _ => r,
301                        },
302                    )
303                })
304            }
305        }
306
307        impl From<bool> for $name {
308            fn from(init: bool) -> $name {
309                let mut ret = [0; $n_words];
310                if init {
311                    ret[0] = 1;
312                }
313                $name(ret)
314            }
315        }
316
317        impl From<u8> for $name {
318            fn from(init: u8) -> $name {
319                let mut ret = [0; $n_words];
320                ret[0] = init as u64;
321                $name(ret)
322            }
323        }
324
325        impl From<u16> for $name {
326            fn from(init: u16) -> $name {
327                let mut ret = [0; $n_words];
328                ret[0] = init as u64;
329                $name(ret)
330            }
331        }
332
333        impl From<u32> for $name {
334            fn from(init: u32) -> $name {
335                let mut ret = [0; $n_words];
336                ret[0] = init as u64;
337                $name(ret)
338            }
339        }
340
341        impl From<u64> for $name {
342            fn from(init: u64) -> $name {
343                let mut ret = [0; $n_words];
344                ret[0] = init;
345                $name(ret)
346            }
347        }
348
349        impl From<u128> for $name {
350            fn from(init: u128) -> $name {
351                let mut ret = [0; $n_words * 8];
352                for (pos, byte) in init.to_le_bytes().iter().enumerate() {
353                    ret[pos] = *byte;
354                }
355                $name::from_le_bytes(ret)
356            }
357        }
358
359        impl<'a> ::core::convert::TryFrom<&'a [u64]> for $name {
360            type Error = $crate::error::ParseLengthError;
361            fn try_from(data: &'a [u64]) -> Result<$name, Self::Error> {
362                if data.len() != $n_words {
363                    Err($crate::error::ParseLengthError {
364                        actual: data.len(),
365                        expected: $n_words,
366                    })
367                } else {
368                    let mut bytes = [0u64; $n_words];
369                    bytes.copy_from_slice(data);
370                    Ok(Self::from_inner(bytes))
371                }
372            }
373        }
374        impl ::core::ops::Index<usize> for $name {
375            type Output = u64;
376
377            #[inline]
378            fn index(&self, index: usize) -> &u64 { &self.0[index] }
379        }
380
381        impl ::core::ops::Index<::core::ops::Range<usize>> for $name {
382            type Output = [u64];
383
384            #[inline]
385            fn index(&self, index: ::core::ops::Range<usize>) -> &[u64] { &self.0[index] }
386        }
387
388        impl ::core::ops::Index<::core::ops::RangeTo<usize>> for $name {
389            type Output = [u64];
390
391            #[inline]
392            fn index(&self, index: ::core::ops::RangeTo<usize>) -> &[u64] { &self.0[index] }
393        }
394
395        impl ::core::ops::Index<::core::ops::RangeFrom<usize>> for $name {
396            type Output = [u64];
397
398            #[inline]
399            fn index(&self, index: ::core::ops::RangeFrom<usize>) -> &[u64] { &self.0[index] }
400        }
401
402        impl ::core::ops::Index<::core::ops::RangeFull> for $name {
403            type Output = [u64];
404
405            #[inline]
406            fn index(&self, _: ::core::ops::RangeFull) -> &[u64] { &self.0[..] }
407        }
408
409        impl PartialOrd for $name {
410            #[inline]
411            fn partial_cmp(&self, other: &$name) -> Option<::core::cmp::Ordering> {
412                Some(self.cmp(&other))
413            }
414        }
415
416        impl Ord for $name {
417            #[inline]
418            fn cmp(&self, other: &$name) -> ::core::cmp::Ordering {
419                // We need to manually implement ordering because the words in our array
420                // are in little-endian order, i.e. the most significant word is last in
421                // the array, and the auto derive for array Ord compares the elements
422                // from first to last.
423                for i in 0..$n_words {
424                    let self_word = self[$n_words - 1 - i];
425                    let other_word = other[$n_words - 1 - i];
426
427                    // If this is a signed type, start with signed comparison on the
428                    // most-significant word, then continue with unsigned comparisons on
429                    // the rest of the words.
430                    let res = if i == 0 && Self::IS_SIGNED_TYPE {
431                        (self_word as i64).cmp(&(other_word as i64))
432                    } else {
433                        self_word.cmp(&other_word)
434                    };
435
436                    if res != ::core::cmp::Ordering::Equal {
437                        return res;
438                    }
439                }
440                ::core::cmp::Ordering::Equal
441            }
442        }
443
444        impl ::core::ops::Neg for $name {
445            type Output = Self;
446            fn neg(self) -> Self::Output {
447                assert!(
448                    $name::MIN != $name([u64::MAX; $n_words]),
449                    "attempt to negate unsigned number"
450                );
451                assert!(
452                    self != $name::MIN,
453                    "attempt to negate the minimum value, which would overflow"
454                );
455                (!self).wrapping_add($name::ONE)
456            }
457        }
458
459        impl $name {
460            /// Checked integer addition. Computes `self + rhs`, returning `None` if
461            /// overflow occurred.
462            pub fn checked_add<T>(self, other: T) -> Option<$name>
463            where T: Into<$name> {
464                let (res, flag) = self.overflowing_add(other);
465                if flag { None } else { Some(res) }
466            }
467
468            /// Saturating integer addition. Computes `self + rhs`, saturating at the
469            /// numeric bounds instead of overflowing.
470            pub fn saturating_add<T>(self, other: T) -> $name
471            where T: Into<$name> {
472                let (res, flag) = self.overflowing_add(other);
473                if flag { Self::MAX } else { res }
474            }
475
476            /// Calculates `self + rhs`
477            ///
478            /// Returns a tuple of the addition along with a boolean indicating whether
479            /// an arithmetic overflow would occur. If an overflow would have occurred
480            /// then the wrapped value is returned.
481            pub fn overflowing_add<T>(self, other: T) -> ($name, bool)
482            where T: Into<$name> {
483                let $name(ref me) = self;
484                let other = other.into();
485                let $name(ref you) = other;
486                let mut ret = [0u64; $n_words];
487                let mut carry = 0u64;
488                for i in 0..$n_words {
489                    let (res, flag) = me[i].overflowing_add(carry);
490                    carry = flag as u64;
491                    let (res, flag) = res.overflowing_add(you[i]);
492                    carry += flag as u64;
493                    ret[i] = res;
494                }
495                let ret = Self(ret);
496                let overflow = if !Self::IS_SIGNED_TYPE {
497                    carry > 0
498                } else {
499                    self != Self::MIN &&
500                        other != Self::MIN &&
501                        (self.is_negative() == other.is_negative()) &&
502                        (self.is_negative() != ret.is_negative())
503                };
504                (ret, overflow)
505            }
506
507            /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at
508            /// the boundary of the type.
509            pub fn wrapping_add<T>(self, other: T) -> $name
510            where T: Into<$name> {
511                self.overflowing_add(other).0
512            }
513
514            /// Checked integer subtraction. Computes `self - rhs`, returning `None` if
515            /// overflow occurred.
516            pub fn checked_sub<T>(self, other: T) -> Option<$name>
517            where T: Into<$name> {
518                let (res, flag) = self.overflowing_sub(other);
519                if flag { None } else { Some(res) }
520            }
521
522            /// Saturating integer subtraction. Computes `self - rhs`, saturating at the
523            /// numeric bounds instead of overflowing.
524            pub fn saturating_sub<T>(self, other: T) -> $name
525            where T: Into<$name> {
526                let (res, flag) = self.overflowing_sub(other);
527                if flag { Self::MAX } else { res }
528            }
529
530            /// Calculates `self - rhs`
531            ///
532            /// Returns a tuple of the subtraction along with a boolean indicating
533            /// whether an arithmetic overflow would occur. If an overflow would
534            /// have occurred then the wrapped value is returned.
535            pub fn overflowing_sub<T>(self, other: T) -> ($name, bool)
536            where T: Into<$name> {
537                let other = other.into();
538                if !Self::IS_SIGNED_TYPE {
539                    (self.wrapping_add(!other).wrapping_add($name::ONE), self < other)
540                } else {
541                    self.overflowing_add((!other).wrapping_add($name::ONE))
542                }
543            }
544
545            /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around
546            /// at the boundary of the type.
547            pub fn wrapping_sub<T>(self, other: T) -> $name
548            where T: Into<$name> {
549                self.overflowing_sub(other).0
550            }
551
552            /// Checked integer multiplication. Computes `self * rhs`, returning `None`
553            /// if overflow occurred.
554            pub fn checked_mul<T>(self, other: T) -> Option<$name>
555            where T: Into<$name> {
556                let (res, flag) = self.overflowing_mul(other);
557                if flag { None } else { Some(res) }
558            }
559
560            /// Saturating integer multiplication. Computes `self * rhs`, saturating at
561            /// the numeric bounds instead of overflowing.
562            pub fn saturating_mul<T>(self, other: T) -> $name
563            where T: Into<$name> {
564                let (res, flag) = self.overflowing_mul(other);
565                if flag { Self::MAX } else { res }
566            }
567
568            /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping
569            /// around at the boundary of the type.
570            pub fn wrapping_mul<T>(self, other: T) -> $name
571            where T: Into<$name> {
572                self.overflowing_mul(other).0
573            }
574
575            /// Calculates `self / rhs`
576            ///
577            /// Returns a tuple of the divisor along with a boolean indicating
578            /// whether an arithmetic overflow would occur. If an overflow would
579            /// have occurred then the wrapped value is returned.
580            pub fn overflowing_div<T>(self, other: T) -> ($name, bool)
581            where T: Into<$name> {
582                let rhs = other.into();
583                match self.div_rem(rhs) {
584                    Err(DivError::Overflow) => (Self::MIN, true),
585                    res => (res.expect("Error occurred during bigint division").0, false),
586                }
587            }
588
589            /// Wrapping (modular) division. Calculates `self / rhs`,
590            /// wrapping around at the boundary of the type.
591            ///
592            /// The only case where such wrapping can occur is when one divides
593            /// `MIN / -1` on a signed type (where MIN is the negative minimal value for
594            /// the type); this is equivalent to -MIN, a positive value that is
595            /// too large to represent in the type.
596            /// In such a case, this function returns MIN itself.
597            pub fn wrapping_div<T>(self, other: T) -> $name
598            where T: Into<$name> {
599                self.overflowing_div(other.into()).0
600            }
601
602            /// Checked integer division. Computes `self / rhs`,
603            /// returning None if `rhs == 0` or the division results in overflow.
604            pub fn checked_div<T>(self, other: T) -> Option<$name>
605            where T: Into<$name> {
606                self.div_rem(other.into()).ok().map(|(q, _)| q)
607            }
608
609            /// Saturating integer division. Computes `self / rhs`,
610            /// saturating at the numeric bounds instead of overflowing.
611            pub fn saturating_div<T>(self, other: T) -> $name
612            where T: Into<$name> {
613                let rhs = other.into();
614                match self.div_rem(rhs) {
615                    Err(DivError::Overflow) => Self::MAX,
616                    res => res.expect("Error occurred during bigint division").0,
617                }
618            }
619
620            /// Calculates the remainder when `self` is divided by `rhs`.
621            ///
622            /// Returns a tuple of the remainder after dividing along with a boolean
623            /// indicating whether an arithmetic overflow would occur.
624            /// If an overflow would occur then 0 is returned.
625            pub fn overflowing_rem<T>(self, other: T) -> ($name, bool)
626            where T: Into<$name> {
627                let rhs = other.into();
628                match self.div_rem(rhs) {
629                    Err(DivError::Overflow) => (Self::ZERO, true),
630                    res => (res.expect("Error occurred during bigint division").1, false),
631                }
632            }
633
634            /// Wrapping (modular) remainder.
635            /// Computes self % rhs, wrapping around at the boundary of the type.
636            ///
637            /// Such wrap-around never actually occurs mathematically;
638            /// implementation artifacts make x % y invalid for MIN / -1
639            /// on a signed type (where MIN is the negative minimal value).
640            /// In such a case, this function returns 0.
641            pub fn wrapping_rem<T>(self, other: T) -> $name
642            where T: Into<$name> {
643                self.overflowing_rem(other.into()).0
644            }
645
646            /// Checked integer remainder. Computes `self % rhs`,
647            /// returning None if `rhs == 0` or the division results in overflow.
648            pub fn checked_rem<T>(self, other: T) -> Option<$name>
649            where T: Into<$name> {
650                self.div_rem(other.into()).ok().map(|(_, r)| r)
651            }
652
653            /// Calculates the quotient of Euclidean division of `self` by `rhs`.
654            ///
655            /// This computes the integer `q` such that `self = q * rhs + r`,
656            /// with `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
657            ///
658            /// In other words, the result is `self / rhs` rounded to the integer `q`
659            /// such that `self >= q * rhs`. If `self > 0`,
660            /// this is equal to round towards zero (the default in Rust);
661            /// if `self < 0`, this is equal to round towards +/- infinity.
662            pub fn div_euclid<T>(self, other: T) -> $name
663            where T: Into<$name> {
664                self.div_rem_euclid(other.into())
665                    .expect("Error occurred during bigint division")
666                    .0
667            }
668
669            /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
670            ///
671            /// Returns a tuple of the divisor along with a boolean indicating
672            /// whether an arithmetic overflow would occur.
673            /// If an overflow would occur then `self` is returned.
674            pub fn overflowing_div_euclid<T>(self, other: T) -> ($name, bool)
675            where T: Into<$name> {
676                match self.div_rem_euclid(other.into()) {
677                    Err(DivError::Overflow) => (Self::MIN, true),
678                    res => (res.expect("Error occurred during bigint division").0, false),
679                }
680            }
681
682            /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
683            /// wrapping around at the boundary of the type.
684            ///
685            /// Wrapping will only occur in `MIN / -1` on a signed type
686            /// (where MIN is the negative minimal value for the type).
687            /// This is equivalent to `-MIN`, a positive value
688            /// that is too large to represent in the type.
689            /// In this case, this method returns `MIN` itself.
690            pub fn wrapping_div_euclid<T>(self, other: T) -> $name
691            where T: Into<$name> {
692                self.overflowing_div_euclid(other.into()).0
693            }
694
695            /// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
696            /// returning None if `rhs == 0` or the division results in overflow.
697            pub fn checked_div_euclid<T>(self, other: T) -> Option<$name>
698            where T: Into<$name> {
699                self.div_rem_euclid(other.into()).ok().map(|(q, _)| q)
700            }
701
702            /// Calculates the least nonnegative remainder of `self (mod rhs)`.
703            ///
704            /// This is done as if by the Euclidean division algorithm –
705            /// given `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) +
706            /// r`, and `0 <= r < abs(rhs)`.
707            pub fn rem_euclid<T>(self, other: T) -> $name
708            where T: Into<$name> {
709                self.div_rem_euclid(other.into())
710                    .expect("Error occurred during bigint division")
711                    .1
712            }
713
714            /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
715            ///
716            /// Returns a tuple of the remainder after dividing along with a boolean
717            /// indicating whether an arithmetic overflow would occur.
718            /// If an overflow would occur then 0 is returned.
719            pub fn overflowing_rem_euclid<T>(self, other: T) -> ($name, bool)
720            where T: Into<$name> {
721                match self.div_rem_euclid(other.into()) {
722                    Err(DivError::Overflow) => (Self::ZERO, true),
723                    res => (res.expect("Error occurred during bigint division").1, false),
724                }
725            }
726
727            /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`,
728            /// wrapping around at the boundary of the type.
729            ///
730            /// Wrapping will only occur in `MIN % -1` on a signed type
731            /// (where `MIN` is the negative minimal value for the type).
732            /// In this case, this method returns 0.
733            pub fn wrapping_rem_euclid<T>(self, other: T) -> $name
734            where T: Into<$name> {
735                self.overflowing_rem_euclid(other.into()).0
736            }
737
738            /// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`,
739            /// returning None if `rhs == 0` or the division results in overflow.
740            pub fn checked_rem_euclid<T>(self, other: T) -> Option<$name>
741            where T: Into<$name> {
742                self.div_rem_euclid(other.into()).ok().map(|(_, r)| r)
743            }
744
745            /// Checked shift left. Computes self << rhs,
746            /// returning None if rhs is larger than or equal to the number of bits in
747            /// self.
748            pub fn checked_shl(self, rhs: u32) -> Option<$name> {
749                match rhs < Self::BITS {
750                    true => Some(self << (rhs as usize)),
751                    false => None,
752                }
753            }
754
755            /// Checked shift right. Computes self >> rhs,
756            /// returning None if rhs is larger than or equal to the number of bits in
757            /// self.
758            pub fn checked_shr(self, rhs: u32) -> Option<$name> {
759                match rhs < Self::BITS {
760                    true => Some(self >> (rhs as usize)),
761                    false => None,
762                }
763            }
764
765            /// Wrapping (modular) negation. Computes -self,
766            /// wrapping around at the boundary of the type.
767            /// Since unsigned types do not have negative equivalents
768            /// all applications of this function will wrap (except for -0).
769            /// For values smaller than the corresponding signed type's maximum
770            /// the result is the same as casting the corresponding signed value.
771            /// Any larger values are equivalent to MAX + 1 - (val - MAX - 1)
772            /// where MAX is the corresponding signed type's maximum.
773            pub fn wrapping_neg(self) -> $name { (!self).wrapping_add(Self::ONE) }
774        }
775
776        impl<T> ::core::ops::Add<T> for $name
777        where T: Into<$name>
778        {
779            type Output = $name;
780
781            fn add(self, other: T) -> $name {
782                let (res, flag) = self.overflowing_add(other);
783                assert!(!flag, "attempt to add with overflow");
784                res
785            }
786        }
787        impl<T> ::core::ops::AddAssign<T> for $name
788        where T: Into<$name>
789        {
790            #[inline]
791            fn add_assign(&mut self, rhs: T) { self.0 = (*self + rhs).0 }
792        }
793
794        impl<T> ::core::ops::Sub<T> for $name
795        where T: Into<$name>
796        {
797            type Output = $name;
798
799            #[inline]
800            fn sub(self, other: T) -> $name {
801                let (res, flag) = self.overflowing_sub(other);
802                assert!(!flag, "attempt to subtract with overflow");
803                res
804            }
805        }
806        impl<T> ::core::ops::SubAssign<T> for $name
807        where T: Into<$name>
808        {
809            #[inline]
810            fn sub_assign(&mut self, rhs: T) { self.0 = (*self - rhs).0 }
811        }
812
813        impl<T> ::core::ops::Mul<T> for $name
814        where T: Into<$name>
815        {
816            type Output = $name;
817
818            fn mul(self, other: T) -> $name {
819                let (res, flag) = self.overflowing_mul(other);
820                assert!(!flag, "attempt to mul with overflow");
821                res
822            }
823        }
824        impl<T> ::core::ops::MulAssign<T> for $name
825        where T: Into<$name>
826        {
827            #[inline]
828            fn mul_assign(&mut self, rhs: T) { self.0 = (*self * rhs).0 }
829        }
830
831        impl<T> ::core::ops::Div<T> for $name
832        where T: Into<$name>
833        {
834            type Output = $name;
835
836            fn div(self, other: T) -> $name {
837                self.div_rem(other.into())
838                    .expect("Error occurred during bigint division")
839                    .0
840            }
841        }
842        impl<T> ::core::ops::DivAssign<T> for $name
843        where T: Into<$name>
844        {
845            #[inline]
846            fn div_assign(&mut self, rhs: T) { self.0 = (*self / rhs).0 }
847        }
848
849        impl<T> ::core::ops::Rem<T> for $name
850        where T: Into<$name>
851        {
852            type Output = $name;
853
854            fn rem(self, other: T) -> $name {
855                self.div_rem(other.into())
856                    .expect("Error occurred during bigint division")
857                    .1
858            }
859        }
860        impl<T> ::core::ops::RemAssign<T> for $name
861        where T: Into<$name>
862        {
863            #[inline]
864            fn rem_assign(&mut self, rhs: T) { self.0 = (*self % rhs).0 }
865        }
866
867        impl<T> ::core::ops::BitAnd<T> for $name
868        where T: Into<$name>
869        {
870            type Output = $name;
871
872            #[inline]
873            fn bitand(self, other: T) -> $name {
874                let $name(ref arr1) = self;
875                let $name(ref arr2) = other.into();
876                let mut ret = [0u64; $n_words];
877                for i in 0..$n_words {
878                    ret[i] = arr1[i] & arr2[i];
879                }
880                $name(ret)
881            }
882        }
883        impl<T> ::core::ops::BitAndAssign<T> for $name
884        where T: Into<$name>
885        {
886            #[inline]
887            fn bitand_assign(&mut self, rhs: T) { self.0 = (*self & rhs).0 }
888        }
889
890        impl<T> ::core::ops::BitXor<T> for $name
891        where T: Into<$name>
892        {
893            type Output = $name;
894
895            #[inline]
896            fn bitxor(self, other: T) -> $name {
897                let $name(ref arr1) = self;
898                let $name(ref arr2) = other.into();
899                let mut ret = [0u64; $n_words];
900                for i in 0..$n_words {
901                    ret[i] = arr1[i] ^ arr2[i];
902                }
903                $name(ret)
904            }
905        }
906        impl<T> ::core::ops::BitXorAssign<T> for $name
907        where T: Into<$name>
908        {
909            #[inline]
910            fn bitxor_assign(&mut self, rhs: T) { self.0 = (*self ^ rhs).0 }
911        }
912
913        impl<T> ::core::ops::BitOr<T> for $name
914        where T: Into<$name>
915        {
916            type Output = $name;
917
918            #[inline]
919            fn bitor(self, other: T) -> $name {
920                let $name(ref arr1) = self;
921                let $name(ref arr2) = other.into();
922                let mut ret = [0u64; $n_words];
923                for i in 0..$n_words {
924                    ret[i] = arr1[i] | arr2[i];
925                }
926                $name(ret)
927            }
928        }
929        impl<T> ::core::ops::BitOrAssign<T> for $name
930        where T: Into<$name>
931        {
932            #[inline]
933            fn bitor_assign(&mut self, rhs: T) { self.0 = (*self | rhs).0 }
934        }
935
936        impl ::core::ops::Shl<usize> for $name {
937            type Output = $name;
938
939            fn shl(self, shift: usize) -> $name {
940                let $name(ref original) = self;
941                let mut ret = [0u64; $n_words];
942                let word_shift = shift / 64;
943                let bit_shift = shift % 64;
944                for i in 0..$n_words {
945                    // Shift
946                    if bit_shift < 64 && i + word_shift < $n_words {
947                        ret[i + word_shift] += original[i] << bit_shift;
948                    }
949                    // Carry
950                    if bit_shift > 0 && i + word_shift + 1 < $n_words {
951                        ret[i + word_shift + 1] += original[i] >> (64 - bit_shift);
952                    }
953                }
954                $name(ret)
955            }
956        }
957        impl ::core::ops::ShlAssign<usize> for $name {
958            #[inline]
959            fn shl_assign(&mut self, rhs: usize) { self.0 = (*self << rhs).0 }
960        }
961
962        impl ::core::ops::Shr<usize> for $name {
963            type Output = $name;
964
965            fn shr(self, shift: usize) -> $name {
966                let $name(ref original) = self;
967                let mut ret = [0u64; $n_words];
968                let word_shift = shift / 64;
969                let bit_shift = shift % 64;
970                for i in word_shift..$n_words {
971                    // Shift
972                    ret[i - word_shift] += original[i] >> bit_shift;
973                    // Carry
974                    if bit_shift > 0 && i < $n_words - 1 {
975                        ret[i - word_shift] += original[i + 1] << (64 - bit_shift);
976                    }
977                }
978                if self.is_negative() {
979                    ret[$n_words - 1] |= 0x8000_0000_0000_0000
980                }
981                $name(ret)
982            }
983        }
984
985        impl ::core::ops::ShrAssign<usize> for $name {
986            #[inline]
987            fn shr_assign(&mut self, rhs: usize) { self.0 = (*self >> rhs).0 }
988        }
989
990        impl ::core::ops::Not for $name {
991            type Output = $name;
992
993            #[inline]
994            fn not(self) -> $name {
995                let $name(ref arr) = self;
996                let mut ret = [0u64; $n_words];
997                for i in 0..$n_words {
998                    ret[i] = !arr[i];
999                }
1000                $name(ret)
1001            }
1002        }
1003
1004        impl ::core::fmt::Debug for $name {
1005            fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
1006                let &$name(ref data) = self;
1007                write!(f, "0x")?;
1008                for ch in data.iter().rev() {
1009                    write!(f, "{:016x}", ch)?;
1010                }
1011                Ok(())
1012            }
1013        }
1014
1015        impl ::core::fmt::Display for $name {
1016            fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
1017                ::core::fmt::Debug::fmt(self, f)
1018            }
1019        }
1020
1021        #[cfg(feature = "alloc")]
1022        impl ::core::fmt::UpperHex for $name {
1023            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> Result<(), ::core::fmt::Error> {
1024                use alloc::format;
1025                use alloc::string::String;
1026
1027                let mut hex = String::new();
1028                for chunk in self.0.iter().rev().skip_while(|x| **x == 0) {
1029                    if hex.is_empty() {
1030                        hex.push_str(&format!("{:X}", chunk));
1031                    } else {
1032                        hex.push_str(&format!("{:0>16X}", chunk));
1033                    }
1034                }
1035                if hex.is_empty() {
1036                    hex.push_str("0");
1037                }
1038
1039                let mut prefix = if f.alternate() {
1040                    String::from("0x")
1041                } else {
1042                    String::new()
1043                };
1044                if let Some(width) = f.width() {
1045                    if f.sign_aware_zero_pad() {
1046                        let missing_width =
1047                            width.saturating_sub(prefix.len()).saturating_sub(hex.len());
1048                        prefix.push_str(&"0".repeat(missing_width));
1049                    }
1050                }
1051
1052                prefix.push_str(&hex);
1053                f.pad(&prefix)
1054            }
1055        }
1056
1057        #[cfg(feature = "alloc")]
1058        impl ::core::fmt::LowerHex for $name {
1059            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> Result<(), ::core::fmt::Error> {
1060                use alloc::format;
1061                use alloc::string::String;
1062
1063                let mut hex = String::new();
1064                for chunk in self.0.iter().rev().skip_while(|x| **x == 0) {
1065                    if hex.is_empty() {
1066                        hex.push_str(&format!("{:x}", chunk));
1067                    } else {
1068                        hex.push_str(&format!("{:0>16x}", chunk));
1069                    }
1070                }
1071                if hex.is_empty() {
1072                    hex.push_str("0");
1073                }
1074
1075                let mut prefix = if f.alternate() {
1076                    String::from("0x")
1077                } else {
1078                    String::new()
1079                };
1080                if let Some(width) = f.width() {
1081                    if f.sign_aware_zero_pad() {
1082                        let missing_width =
1083                            width.saturating_sub(prefix.len()).saturating_sub(hex.len());
1084                        prefix.push_str(&"0".repeat(missing_width));
1085                    }
1086                }
1087
1088                prefix.push_str(&hex);
1089                f.pad(&prefix)
1090            }
1091        }
1092
1093        #[cfg(feature = "alloc")]
1094        impl ::core::fmt::Octal for $name {
1095            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> Result<(), ::core::fmt::Error> {
1096                use alloc::format;
1097                use alloc::string::String;
1098
1099                let mut octal = String::new();
1100                for chunk in self.0.iter().rev().skip_while(|x| **x == 0) {
1101                    if octal.is_empty() {
1102                        octal.push_str(&format!("{:o}", chunk));
1103                    } else {
1104                        octal.push_str(&format!("{:0>22o}", chunk));
1105                    }
1106                }
1107                if octal.is_empty() {
1108                    octal.push_str("0");
1109                }
1110
1111                let mut prefix = if f.alternate() {
1112                    String::from("0o")
1113                } else {
1114                    String::new()
1115                };
1116                if let Some(width) = f.width() {
1117                    if f.sign_aware_zero_pad() {
1118                        let missing_width = width
1119                            .saturating_sub(prefix.len())
1120                            .saturating_sub(octal.len());
1121                        prefix.push_str(&"0".repeat(missing_width));
1122                    }
1123                }
1124
1125                prefix.push_str(&octal);
1126                f.pad(&prefix)
1127            }
1128        }
1129
1130        #[cfg(feature = "alloc")]
1131        impl ::core::fmt::Binary for $name {
1132            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> Result<(), ::core::fmt::Error> {
1133                use alloc::format;
1134                use alloc::string::String;
1135
1136                let mut binary = String::new();
1137                for chunk in self.0.iter().rev().skip_while(|x| **x == 0) {
1138                    if binary.is_empty() {
1139                        binary.push_str(&format!("{:b}", chunk));
1140                    } else {
1141                        binary.push_str(&format!("{:0>64b}", chunk));
1142                    }
1143                }
1144                if binary.is_empty() {
1145                    binary.push_str("0");
1146                }
1147
1148                let mut prefix = if f.alternate() {
1149                    String::from("0b")
1150                } else {
1151                    String::new()
1152                };
1153                if let Some(width) = f.width() {
1154                    if f.sign_aware_zero_pad() {
1155                        let missing_width = width
1156                            .saturating_sub(prefix.len())
1157                            .saturating_sub(binary.len());
1158                        prefix.push_str(&"0".repeat(missing_width));
1159                    }
1160                }
1161
1162                prefix.push_str(&binary);
1163                f.pad(&prefix)
1164            }
1165        }
1166
1167        #[cfg(feature = "serde")]
1168        impl $crate::serde::Serialize for $name {
1169            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1170            where S: $crate::serde::Serializer {
1171                use $crate::hex::ToHex;
1172                let bytes = self.to_be_bytes();
1173                if serializer.is_human_readable() {
1174                    serializer.serialize_str(&bytes.to_hex())
1175                } else {
1176                    serializer.serialize_bytes(&bytes)
1177                }
1178            }
1179        }
1180
1181        #[cfg(feature = "serde")]
1182        impl<'de> $crate::serde::Deserialize<'de> for $name {
1183            fn deserialize<D: $crate::serde::Deserializer<'de>>(
1184                deserializer: D,
1185            ) -> Result<Self, D::Error> {
1186                use ::std::fmt;
1187                use $crate::hex::FromHex;
1188                use $crate::serde::de;
1189                struct Visitor;
1190                impl<'de> de::Visitor<'de> for Visitor {
1191                    type Value = $name;
1192
1193                    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
1194                        write!(
1195                            f,
1196                            "{} bytes or a hex string with {} characters",
1197                            $n_words * 8,
1198                            $n_words * 8 * 2
1199                        )
1200                    }
1201
1202                    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
1203                    where E: de::Error {
1204                        let bytes = Vec::from_hex(s)
1205                            .map_err(|_| de::Error::invalid_value(de::Unexpected::Str(s), &self))?;
1206                        $name::from_be_slice(&bytes)
1207                            .map_err(|_| de::Error::invalid_length(bytes.len() * 2, &self))
1208                    }
1209
1210                    fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E>
1211                    where E: de::Error {
1212                        $name::from_be_slice(bytes)
1213                            .map_err(|_| de::Error::invalid_length(bytes.len(), &self))
1214                    }
1215                }
1216
1217                if deserializer.is_human_readable() {
1218                    deserializer.deserialize_str(Visitor)
1219                } else {
1220                    deserializer.deserialize_bytes(Visitor)
1221                }
1222            }
1223        }
1224    };
1225}
1226
1227macro_rules! construct_signed_bigint_methods {
1228    ($name:ident, $n_words:expr) => {
1229        impl From<i8> for $name {
1230            fn from(init: i8) -> $name {
1231                let bytes = init.to_le_bytes();
1232                let mut ret = [if init.is_negative() { u8::MAX } else { 0 }; $n_words * 8];
1233                for i in 0..bytes.len() {
1234                    ret[i] = bytes[i]
1235                }
1236                $name::from_le_bytes(ret)
1237            }
1238        }
1239
1240        impl From<i16> for $name {
1241            fn from(init: i16) -> $name {
1242                let bytes = init.to_le_bytes();
1243                let mut ret = [if init.is_negative() { u8::MAX } else { 0 }; $n_words * 8];
1244                for i in 0..bytes.len() {
1245                    ret[i] = bytes[i]
1246                }
1247                $name::from_le_bytes(ret)
1248            }
1249        }
1250
1251        impl From<i32> for $name {
1252            fn from(init: i32) -> $name {
1253                let bytes = init.to_le_bytes();
1254                let mut ret = [if init.is_negative() { u8::MAX } else { 0 }; $n_words * 8];
1255                for i in 0..bytes.len() {
1256                    ret[i] = bytes[i]
1257                }
1258                $name::from_le_bytes(ret)
1259            }
1260        }
1261
1262        impl From<i64> for $name {
1263            fn from(init: i64) -> $name {
1264                let bytes = init.to_le_bytes();
1265                let mut ret = [if init.is_negative() { u8::MAX } else { 0 }; $n_words * 8];
1266                for i in 0..bytes.len() {
1267                    ret[i] = bytes[i]
1268                }
1269                $name::from_le_bytes(ret)
1270            }
1271        }
1272
1273        impl From<i128> for $name {
1274            fn from(init: i128) -> $name {
1275                let bytes = init.to_le_bytes();
1276                let mut ret = [if init.is_negative() { u8::MAX } else { 0 }; $n_words * 8];
1277                for i in 0..bytes.len() {
1278                    ret[i] = bytes[i]
1279                }
1280                $name::from_le_bytes(ret)
1281            }
1282        }
1283
1284        impl $name {
1285            const IS_SIGNED_TYPE: bool = true;
1286
1287            /// Minimum value
1288            pub const MIN: $name = {
1289                let mut min = [0u64; $n_words];
1290                min[$n_words - 1] = 0x8000_0000_0000_0000;
1291                $name(min)
1292            };
1293
1294            /// Maximum value
1295            pub const MAX: $name = {
1296                let mut max = [u64::MAX; $n_words];
1297                max[$n_words - 1] = u64::MAX >> 1;
1298                $name(max)
1299            };
1300
1301            #[inline]
1302            pub fn is_negative(&self) -> bool {
1303                self[($name::INNER_LEN - 1) as usize] & 0x8000_0000_0000_0000 != 0
1304            }
1305
1306            /// Return the least number of bits needed to represent the number
1307            #[inline]
1308            pub fn bits_required(&self) -> usize {
1309                let &$name(ref arr) = self;
1310                let iter = arr.iter().rev().take($n_words - 1);
1311                if self.is_negative() {
1312                    let ctr = iter.take_while(|&&b| b == u64::MAX).count();
1313                    (0x40 * ($n_words - ctr)) + 1 -
1314                        (!arr[$n_words - ctr - 1]).leading_zeros() as usize
1315                } else {
1316                    let ctr = iter.take_while(|&&b| b == u64::MIN).count();
1317                    (0x40 * ($n_words - ctr)) + 1 - arr[$n_words - ctr - 1].leading_zeros() as usize
1318                }
1319            }
1320
1321            /// Calculates `self * rhs`
1322            ///
1323            /// Returns a tuple of the multiplication along with a boolean indicating
1324            /// whether an arithmetic overflow would occur. If an overflow would
1325            /// have occurred then the wrapped value is returned.
1326            pub fn overflowing_mul<T>(self, other: T) -> ($name, bool)
1327            where T: Into<$name> {
1328                let sub = if self != $name::MIN { -self } else { self };
1329                let mut p_high = $name::ZERO;
1330                let mut p_low = other.into();
1331                let mut prev = false;
1332                for _i in 0..$name::BITS {
1333                    let p_low_trailing_bit = (p_low[0] & 1) != 0;
1334                    p_high = match (p_low_trailing_bit, prev) {
1335                        (false, true) => p_high.wrapping_add(self),
1336                        (true, false) => p_high.wrapping_add(sub),
1337                        _ => p_high,
1338                    };
1339                    prev = p_low_trailing_bit;
1340                    p_low >>= 1;
1341                    p_low = match p_high[0] & 1 {
1342                        0 => p_low & $name::MAX,
1343                        _ => p_low | $name::MIN,
1344                    };
1345                    p_high >>= 1;
1346                }
1347                let negative_overflow =
1348                    p_low.is_negative() && p_high != $name([u64::MAX; $n_words]);
1349                let positive_overflow = !p_low.is_negative() && p_high != $name::ZERO;
1350                (p_low, negative_overflow || positive_overflow)
1351            }
1352        }
1353    };
1354}
1355
1356macro_rules! construct_unsigned_bigint_methods {
1357    ($name:ident, $n_words:expr) => {
1358        impl $name {
1359            const IS_SIGNED_TYPE: bool = false;
1360
1361            /// Minimum value
1362            pub const MIN: $name = $name([0u64; $n_words]);
1363
1364            /// Maximum value
1365            pub const MAX: $name = $name([u64::MAX; $n_words]);
1366
1367            #[inline]
1368            pub const fn is_negative(&self) -> bool { false }
1369
1370            /// Return the least number of bits needed to represent the number
1371            #[inline]
1372            pub fn bits_required(&self) -> usize {
1373                let &$name(ref arr) = self;
1374                let iter = arr.iter().rev().take($n_words - 1);
1375                let ctr = iter.take_while(|&&b| b == u64::MIN).count();
1376                (0x40 * ($n_words - ctr)) - arr[$n_words - ctr - 1].leading_zeros() as usize
1377            }
1378
1379            /// Calculates `self * rhs`
1380            ///
1381            /// Returns a tuple of the multiplication along with a boolean indicating
1382            /// whether an arithmetic overflow would occur. If an overflow would
1383            /// have occurred then the wrapped value is returned.
1384            pub fn overflowing_mul<T>(self, other: T) -> ($name, bool)
1385            where T: Into<$name> {
1386                let $name(ref me) = self;
1387                let $name(ref you) = other.into();
1388                let mut ret = [0u64; $n_words];
1389                let mut overflow = false;
1390                for i in 0..$n_words {
1391                    let mut carry = 0u64;
1392                    for j in 0..$n_words {
1393                        if i + j >= $n_words {
1394                            if me[i] > 0 && you[j] > 0 {
1395                                overflow = true
1396                            }
1397                            continue;
1398                        }
1399                        let prev_carry = carry;
1400                        let res = me[i] as u128 * you[j] as u128;
1401                        carry = (res >> 64) as u64;
1402                        let mul = (res & u64::MAX as u128) as u64;
1403                        let (res, flag) = ret[i + j].overflowing_add(mul);
1404                        carry += flag as u64;
1405                        ret[i + j] = res;
1406                        let (res, flag) = ret[i + j].overflowing_add(prev_carry);
1407                        carry += flag as u64;
1408                        ret[i + j] = res;
1409                    }
1410                    if carry > 0 {
1411                        overflow = true
1412                    }
1413                }
1414                (Self(ret), overflow)
1415            }
1416        }
1417    };
1418}
1419
1420macro_rules! impl_from {
1421    ($from:ident, $n_words_from:expr, $to:ident, $n_words_to:expr) => {
1422        impl From<$from> for $to {
1423            fn from(init: $from) -> $to {
1424                let mut ret = [0u64; $n_words_to];
1425                for i in 0..$n_words_from {
1426                    ret[i] = init.0[i]
1427                }
1428                $to(ret)
1429            }
1430        }
1431    };
1432}
1433
1434construct_bigint!(i256, 4);
1435construct_bigint!(i512, 8);
1436construct_bigint!(i1024, 16);
1437construct_bigint!(u256, 4);
1438construct_bigint!(u512, 8);
1439construct_bigint!(u1024, 16);
1440
1441construct_unsigned_bigint_methods!(u256, 4);
1442construct_unsigned_bigint_methods!(u512, 8);
1443construct_unsigned_bigint_methods!(u1024, 16);
1444construct_signed_bigint_methods!(i256, 4);
1445construct_signed_bigint_methods!(i512, 8);
1446construct_signed_bigint_methods!(i1024, 16);
1447
1448impl_from!(u256, 4, u512, 8);
1449impl_from!(u256, 4, u1024, 16);
1450impl_from!(u512, 8, u1024, 16);
1451
1452#[cfg(test)]
1453mod tests {
1454    #![allow(unused)]
1455
1456    use super::*;
1457
1458    construct_bigint!(Uint128, 2);
1459    construct_unsigned_bigint_methods!(Uint128, 2);
1460
1461    #[test]
1462    fn u256_bits_test() {
1463        assert_eq!(u256::from(255u64).bits_required(), 8);
1464        assert_eq!(u256::from(256u64).bits_required(), 9);
1465        assert_eq!(u256::from(300u64).bits_required(), 9);
1466        assert_eq!(u256::from(60000u64).bits_required(), 16);
1467        assert_eq!(u256::from(70000u64).bits_required(), 17);
1468
1469        // Try to read the following lines out loud quickly
1470        let mut shl = u256::from(70000u64);
1471        shl <<= 100;
1472        assert_eq!(shl.bits_required(), 117);
1473        shl <<= 100;
1474        assert_eq!(shl.bits_required(), 217);
1475        shl <<= 100;
1476        assert_eq!(shl.bits_required(), 0);
1477
1478        // Bit set check
1479        assert!(!u256::from(10u64).bit(0));
1480        assert!(u256::from(10u64).bit(1));
1481        assert!(!u256::from(10u64).bit(2));
1482        assert!(u256::from(10u64).bit(3));
1483        assert!(!u256::from(10u64).bit(4));
1484    }
1485
1486    #[test]
1487    fn u256_display_test() {
1488        assert_eq!(
1489            format!("{}", u256::from(0xDEADBEEFu64)),
1490            "0x00000000000000000000000000000000000000000000000000000000deadbeef"
1491        );
1492        assert_eq!(
1493            format!("{}", u256::from(u64::MAX)),
1494            "0x000000000000000000000000000000000000000000000000ffffffffffffffff"
1495        );
1496
1497        let max_val =
1498            u256([0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF]);
1499        assert_eq!(
1500            format!("{}", max_val),
1501            "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
1502        );
1503    }
1504
1505    #[cfg(feature = "alloc")]
1506    #[test]
1507    fn fmt_hex() {
1508        let one = u256::ONE;
1509        let u_256 =
1510            u256([0x0000000000000000, 0xAAAAAAAABBBBBBBB, 0x0000000111122222, 0x0000000000000000]);
1511
1512        // UpperHex
1513        assert_eq!(format!("{:X}", u_256), "111122222AAAAAAAABBBBBBBB0000000000000000");
1514        assert_eq!(format!("{:#X}", u_256), "0x111122222AAAAAAAABBBBBBBB0000000000000000");
1515        assert_eq!(format!("{:X}", u256::ZERO), "0");
1516        assert_eq!(format!("{:05X}", one), "00001");
1517        assert_eq!(format!("{:#05X}", one), "0x001");
1518        assert_eq!(format!("{:5X}", one), "1    ");
1519        assert_eq!(format!("{:#5X}", one), "0x1  ");
1520        assert_eq!(format!("{:w^#7X}", one), "ww0x1ww");
1521
1522        // LowerHex
1523        assert_eq!(format!("{:x}", u_256), "111122222aaaaaaaabbbbbbbb0000000000000000");
1524        assert_eq!(format!("{:#x}", u_256), "0x111122222aaaaaaaabbbbbbbb0000000000000000");
1525        assert_eq!(format!("{:x}", u256::ZERO), "0");
1526        assert_eq!(format!("{:05x}", one), "00001");
1527        assert_eq!(format!("{:#05x}", one), "0x001");
1528        assert_eq!(format!("{:5x}", one), "1    ");
1529        assert_eq!(format!("{:#5x}", one), "0x1  ");
1530        assert_eq!(format!("{:w^#7x}", one), "ww0x1ww");
1531    }
1532
1533    #[cfg(feature = "alloc")]
1534    #[test]
1535    fn fmt_octal() {
1536        let one = u256::ONE;
1537        let u_256 = u256([
1538            0o0000000000000000000000,
1539            0o0011222222222222222222,
1540            0o0000000001111111111111,
1541            0o0000000000000000000000,
1542        ]);
1543
1544        assert_eq!(
1545            format!("{:o}", u_256),
1546            "111111111111100112222222222222222220000000000000000000000"
1547        );
1548        assert_eq!(
1549            format!("{:#o}", u_256),
1550            "0o111111111111100112222222222222222220000000000000000000000"
1551        );
1552        assert_eq!(format!("{:o}", u256::ZERO), "0");
1553        assert_eq!(format!("{:05o}", one), "00001");
1554        assert_eq!(format!("{:#05o}", one), "0o001");
1555        assert_eq!(format!("{:5o}", one), "1    ");
1556        assert_eq!(format!("{:#5o}", one), "0o1  ");
1557        assert_eq!(format!("{:w^#7o}", one), "ww0o1ww");
1558    }
1559
1560    #[cfg(feature = "alloc")]
1561    #[test]
1562    fn fmt_binary() {
1563        let one = u256::ONE;
1564        let u_256 = u256([
1565            0b0000000000000000000000000000000000000000000000000000000000000000,
1566            0b0001111000011110001111000011110001111000011110001111000011110000,
1567            0b0000000000000000000000000000001111111111111111111111111111111111,
1568            0b0000000000000000000000000000000000000000000000000000000000000000,
1569        ]);
1570
1571        assert_eq!(
1572            format!("{:b}", u_256),
1573            "111111111111111111111111111111111100011110000111100011110000111100011110000111100011110000111100000000000000000000000000000000000000000000000000000000000000000000"
1574        );
1575        assert_eq!(
1576            format!("{:#b}", u_256),
1577            "0b111111111111111111111111111111111100011110000111100011110000111100011110000111100011110000111100000000000000000000000000000000000000000000000000000000000000000000"
1578        );
1579        assert_eq!(format!("{:b}", u256::ZERO), "0");
1580        assert_eq!(format!("{:05b}", one), "00001");
1581        assert_eq!(format!("{:#05b}", one), "0b001");
1582        assert_eq!(format!("{:5b}", one), "1    ");
1583        assert_eq!(format!("{:#5b}", one), "0b1  ");
1584        assert_eq!(format!("{:w^#7b}", one), "ww0b1ww");
1585    }
1586
1587    #[test]
1588    fn u256_comp_test() {
1589        let small = u256([10u64, 0, 0, 0]);
1590        let big = u256([0x8C8C3EE70C644118u64, 0x0209E7378231E632, 0, 0]);
1591        let bigger = u256([0x9C8C3EE70C644118u64, 0x0209E7378231E632, 0, 0]);
1592        let biggest = u256([0x5C8C3EE70C644118u64, 0x0209E7378231E632, 0, 1]);
1593
1594        assert!(small < big);
1595        assert!(big < bigger);
1596        assert!(bigger < biggest);
1597        assert!(bigger <= biggest);
1598        assert!(biggest <= biggest);
1599        assert!(bigger >= big);
1600        assert!(bigger >= small);
1601        assert!(small <= small);
1602    }
1603
1604    #[test]
1605    fn uint_from_be_bytes() {
1606        assert_eq!(
1607            Uint128::from_be_bytes([
1608                0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed,
1609                0xfe, 0xed
1610            ]),
1611            Uint128([0xdeafbabe2bedfeed, 0x1badcafedeadbeef])
1612        );
1613
1614        assert_eq!(
1615            u256::from_be_bytes([
1616                0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed,
1617                0xfe, 0xed, 0xba, 0xad, 0xf0, 0x0d, 0xde, 0xfa, 0xce, 0xda, 0x11, 0xfe, 0xd2, 0xba,
1618                0xd1, 0xc0, 0xff, 0xe0
1619            ]),
1620            u256([0x11fed2bad1c0ffe0, 0xbaadf00ddefaceda, 0xdeafbabe2bedfeed, 0x1badcafedeadbeef])
1621        );
1622    }
1623
1624    #[test]
1625    fn uint_from_le_bytes() {
1626        let mut be = [
1627            0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed,
1628            0xfe, 0xed,
1629        ];
1630        be.reverse();
1631        assert_eq!(Uint128::from_le_bytes(be), Uint128([0xdeafbabe2bedfeed, 0x1badcafedeadbeef]));
1632
1633        let mut be = [
1634            0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed,
1635            0xfe, 0xed, 0xba, 0xad, 0xf0, 0x0d, 0xde, 0xfa, 0xce, 0xda, 0x11, 0xfe, 0xd2, 0xba,
1636            0xd1, 0xc0, 0xff, 0xe0,
1637        ];
1638        be.reverse();
1639        assert_eq!(
1640            u256::from_le_bytes(be),
1641            u256([0x11fed2bad1c0ffe0, 0xbaadf00ddefaceda, 0xdeafbabe2bedfeed, 0x1badcafedeadbeef])
1642        );
1643    }
1644
1645    #[test]
1646    fn uint_to_be_bytes() {
1647        assert_eq!(Uint128([0xdeafbabe2bedfeed, 0x1badcafedeadbeef]).to_be_bytes(), [
1648            0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed,
1649            0xfe, 0xed
1650        ]);
1651
1652        assert_eq!(
1653            u256([0x11fed2bad1c0ffe0, 0xbaadf00ddefaceda, 0xdeafbabe2bedfeed, 0x1badcafedeadbeef])
1654                .to_be_bytes(),
1655            [
1656                0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed,
1657                0xfe, 0xed, 0xba, 0xad, 0xf0, 0x0d, 0xde, 0xfa, 0xce, 0xda, 0x11, 0xfe, 0xd2, 0xba,
1658                0xd1, 0xc0, 0xff, 0xe0
1659            ]
1660        );
1661    }
1662
1663    #[test]
1664    fn uint_to_le_bytes() {
1665        assert_eq!(Uint128([0xdeafbabe2bedfeed, 0x1badcafedeadbeef]).to_le_bytes(), [
1666            0xed, 0xfe, 0xed, 0x2b, 0xbe, 0xba, 0xaf, 0xde, 0xef, 0xbe, 0xad, 0xde, 0xfe, 0xca,
1667            0xad, 0x1b
1668        ]);
1669
1670        assert_eq!(
1671            u256([0x11fed2bad1c0ffe0, 0xbaadf00ddefaceda, 0xdeafbabe2bedfeed, 0x1badcafedeadbeef])
1672                .to_le_bytes(),
1673            [
1674                0xe0, 0xff, 0xc0, 0xd1, 0xba, 0xd2, 0xfe, 0x11, 0xda, 0xce, 0xfa, 0xde, 0x0d, 0xf0,
1675                0xad, 0xba, 0xed, 0xfe, 0xed, 0x2b, 0xbe, 0xba, 0xaf, 0xde, 0xef, 0xbe, 0xad, 0xde,
1676                0xfe, 0xca, 0xad, 0x1b,
1677            ]
1678        );
1679    }
1680
1681    #[test]
1682    fn u256_div_rem_0() {
1683        let zero = u256::ZERO;
1684        let number_one = u256::from(0xDEADBEEFu64);
1685        let number_two = u256::from(u64::MAX);
1686        let one_div_rem_two =
1687            (u256::from(u64::MAX / 0xDEADBEEFu64), u256::from(u64::MAX % 0xDEADBEEFu64));
1688        let max = u256::MAX;
1689
1690        // Division by zero gets not panic and gets None
1691        assert_eq!(u256::div_rem(max, zero), Err(DivError::ZeroDiv));
1692        assert_eq!(u256::div_rem(number_two, zero), Err(DivError::ZeroDiv));
1693        assert_eq!(u256::div_rem(number_one, zero), Err(DivError::ZeroDiv));
1694
1695        // Division of zero gets Zero
1696        assert_eq!(u256::div_rem(zero, max), Ok((zero, zero)));
1697        assert_eq!(u256::div_rem(zero, number_two), Ok((zero, zero)));
1698        assert_eq!(u256::div_rem(zero, number_one), Ok((zero, zero)));
1699
1700        // Division by another than zero not gets None
1701        assert!(u256::div_rem(max, number_one).is_ok());
1702        assert!(u256::div_rem(number_two, number_one).is_ok());
1703
1704        // In u256 division gets the same as in u64
1705        assert_eq!(u256::div_rem(number_two, number_one), Ok(one_div_rem_two));
1706    }
1707
1708    #[test]
1709    fn u256_div_rem_1() {
1710        let zero = u256::ZERO;
1711        let number_one = u256::from(0xDEADBEEFu64);
1712        let number_two = u256::from(u64::MAX);
1713        let max = u256::MAX;
1714
1715        assert!(u256::div_rem(max, zero).is_err());
1716        assert!(u256::div_rem(number_one, zero).is_err());
1717        assert!(u256::div_rem(number_two, zero).is_err());
1718
1719        assert_eq!(u256::MAX / u256::ONE, u256::MAX);
1720        assert_eq!(u256::from(12u8) / u256::from(4u8), u256::from(3u8));
1721        assert!(std::panic::catch_unwind(|| number_one / zero).is_err());
1722        assert!(std::panic::catch_unwind(|| i256::MIN / (-i256::ONE)).is_err());
1723    }
1724
1725    #[test]
1726    fn bigint_min_max() {
1727        assert_eq!(u256::MIN.as_inner(), &[0u64; 4]);
1728        assert_eq!(u512::MIN.as_inner(), &[0u64; 8]);
1729        assert_eq!(u1024::MIN.as_inner(), &[0u64; 16]);
1730        assert_eq!(u256::MAX.as_inner(), &[u64::MAX; 4]);
1731        assert_eq!(u512::MAX.as_inner(), &[u64::MAX; 8]);
1732        assert_eq!(u1024::MAX.as_inner(), &[u64::MAX; 16]);
1733        assert_eq!(u256::BITS, 4 * 64);
1734        assert_eq!(u512::BITS, 8 * 64);
1735        assert_eq!(u1024::BITS, 16 * 64);
1736    }
1737
1738    #[test]
1739    fn u256_arithmetic_test() {
1740        let init = u256::from(0xDEADBEEFDEADBEEFu64);
1741        let copy = init;
1742
1743        let add = init + copy;
1744        assert_eq!(add, u256([0xBD5B7DDFBD5B7DDEu64, 1, 0, 0]));
1745        // Bitshifts
1746        let shl = add << 88;
1747        assert_eq!(shl, u256([0u64, 0xDFBD5B7DDE000000, 0x1BD5B7D, 0]));
1748        let shr = shl >> 40;
1749        assert_eq!(shr, u256([0x7DDE000000000000u64, 0x0001BD5B7DDFBD5B, 0, 0]));
1750        // Increment
1751        let mut incr = shr;
1752        incr += 1u32;
1753        assert_eq!(incr, u256([0x7DDE000000000001u64, 0x0001BD5B7DDFBD5B, 0, 0]));
1754        // Subtraction
1755        let sub = incr - init;
1756        assert_eq!(sub, u256([0x9F30411021524112u64, 0x0001BD5B7DDFBD5A, 0, 0]));
1757        // Multiplication
1758        let mult = sub * 300u32;
1759        assert_eq!(mult, u256([0x8C8C3EE70C644118u64, 0x0209E7378231E632, 0, 0]));
1760        // Division
1761        assert_eq!(u256::from(105u64) / u256::from(5u64), u256::from(21u64));
1762        let div = mult / u256::from(300u64);
1763        assert_eq!(div, u256([0x9F30411021524112u64, 0x0001BD5B7DDFBD5A, 0, 0]));
1764
1765        assert_eq!(u256::from(105u64) % u256::from(5u64), u256::from(0u64));
1766        assert_eq!(u256::from(35498456u64) % u256::from(3435u64), u256::from(1166u64));
1767        let rem_src = mult * u256::from(39842u64) + u256::from(9054u64);
1768        assert_eq!(rem_src % u256::from(39842u64), u256::from(9054u64));
1769        // TODO: bit inversion
1770    }
1771
1772    #[test]
1773    fn mul_u32_test() {
1774        let u64_val = u256::from(0xDEADBEEFDEADBEEFu64);
1775
1776        let u96_res = u64_val * 0xFFFFFFFFu32;
1777        let u128_res = u96_res * 0xFFFFFFFFu32;
1778        let u160_res = u128_res * 0xFFFFFFFFu32;
1779        let u192_res = u160_res * 0xFFFFFFFFu32;
1780        let u224_res = u192_res * 0xFFFFFFFFu32;
1781        let u256_res = u224_res * 0xFFFFFFFFu32;
1782
1783        assert_eq!(u96_res, u256([0xffffffff21524111u64, 0xDEADBEEE, 0, 0]));
1784        assert_eq!(u128_res, u256([0x21524111DEADBEEFu64, 0xDEADBEEE21524110, 0, 0]));
1785        assert_eq!(u160_res, u256([0xBD5B7DDD21524111u64, 0x42A4822200000001, 0xDEADBEED, 0]));
1786        assert_eq!(
1787            u192_res,
1788            u256([0x63F6C333DEADBEEFu64, 0xBD5B7DDFBD5B7DDB, 0xDEADBEEC63F6C334, 0])
1789        );
1790        assert_eq!(
1791            u224_res,
1792            u256([0x7AB6FBBB21524111u64, 0xFFFFFFFBA69B4558, 0x854904485964BAAA, 0xDEADBEEB])
1793        );
1794        assert_eq!(
1795            u256_res,
1796            u256([
1797                0xA69B4555DEADBEEFu64,
1798                0xA69B455CD41BB662,
1799                0xD41BB662A69B4550,
1800                0xDEADBEEAA69B455C
1801            ])
1802        );
1803    }
1804
1805    #[test]
1806    fn multiplication_test() {
1807        let u64_val = u256::from(0xDEADBEEFDEADBEEFu64);
1808
1809        let u128_res = u64_val * u64_val;
1810
1811        assert_eq!(u128_res, u256([0x048D1354216DA321u64, 0xC1B1CD13A4D13D46, 0, 0]));
1812
1813        let u256_res = u128_res * u128_res;
1814
1815        assert_eq!(
1816            u256_res,
1817            u256([
1818                0xF4E166AAD40D0A41u64,
1819                0xF5CF7F3618C2C886u64,
1820                0x4AFCFF6F0375C608u64,
1821                0x928D92B4D7F5DF33u64
1822            ])
1823        );
1824    }
1825
1826    #[test]
1827    fn u256_extreme_bitshift_test() {
1828        // Shifting a u64 by 64 bits gives an undefined value, so make sure that
1829        // we're doing the Right Thing here
1830        let init = u256::from(0xDEADBEEFDEADBEEFu64);
1831
1832        assert_eq!(init << 64, u256([0, 0xDEADBEEFDEADBEEF, 0, 0]));
1833        let add = (init << 64) + init;
1834        assert_eq!(add, u256([0xDEADBEEFDEADBEEF, 0xDEADBEEFDEADBEEF, 0, 0]));
1835        assert_eq!(add >> 0, u256([0xDEADBEEFDEADBEEF, 0xDEADBEEFDEADBEEF, 0, 0]));
1836        assert_eq!(add << 0, u256([0xDEADBEEFDEADBEEF, 0xDEADBEEFDEADBEEF, 0, 0]));
1837        assert_eq!(add >> 64, u256([0xDEADBEEFDEADBEEF, 0, 0, 0]));
1838        assert_eq!(add << 64, u256([0, 0xDEADBEEFDEADBEEF, 0xDEADBEEFDEADBEEF, 0]));
1839    }
1840
1841    #[cfg(feature = "serde")]
1842    #[test]
1843    fn u256_serde_test() {
1844        let check = |uint, hex| {
1845            let json = format!("\"{}\"", hex);
1846            assert_eq!(::serde_json::to_string(&uint).unwrap(), json);
1847            assert_eq!(::serde_json::from_str::<u256>(&json).unwrap(), uint);
1848        };
1849
1850        check(u256::from(0u64), "0000000000000000000000000000000000000000000000000000000000000000");
1851        check(
1852            u256::from(0xDEADBEEFu64),
1853            "00000000000000000000000000000000000000000000000000000000deadbeef",
1854        );
1855        check(
1856            u256([0xaa11, 0xbb22, 0xcc33, 0xdd44]),
1857            "000000000000dd44000000000000cc33000000000000bb22000000000000aa11",
1858        );
1859        check(
1860            u256([u64::MAX, u64::MAX, u64::MAX, u64::MAX]),
1861            "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1862        );
1863        check(
1864            u256([0xA69B4555DEADBEEF, 0xA69B455CD41BB662, 0xD41BB662A69B4550, 0xDEADBEEAA69B455C]),
1865            "deadbeeaa69b455cd41bb662a69b4550a69b455cd41bb662a69b4555deadbeef",
1866        );
1867
1868        assert!(
1869            ::serde_json::from_str::<u256>(
1870                "\"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffg\""
1871            )
1872            .is_err()
1873        ); // invalid char
1874        assert!(
1875            ::serde_json::from_str::<u256>(
1876                "\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
1877            )
1878            .is_err()
1879        ); // invalid length
1880        assert!(
1881            ::serde_json::from_str::<u256>(
1882                "\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
1883            )
1884            .is_err()
1885        ); // invalid length
1886    }
1887
1888    #[test]
1889    fn i256_test() {
1890        let x = i256::from(1);
1891        let y = i256::from(1);
1892        assert_eq!(x.checked_add(y), Some(i256::from(2)));
1893    }
1894
1895    #[test]
1896    fn i256_is_positive_test() {
1897        assert!(i256::from(1).is_positive());
1898        assert!(!i256::from(-1).is_positive());
1899        assert!(!i256::from(0).is_positive());
1900        assert!(i256::MAX.is_positive());
1901        assert!(!i256::MIN.is_positive());
1902        assert!(i256::MIN.is_negative());
1903    }
1904
1905    #[test]
1906    fn u256_add_test() {
1907        assert_eq!((u256::MAX - u256::ONE, true), u256::MAX.overflowing_add(u256::MAX));
1908    }
1909
1910    #[test]
1911    fn i256_add_test() {
1912        assert_eq!((i256::from(3), false), i256::from(1).overflowing_add(i256::from(2)));
1913        assert_eq!((i256::from(1), false), i256::from(-1).overflowing_add(i256::from(2)));
1914        assert_eq!((i256::from(-2), false), i256::from(-1).overflowing_add(i256::from(-1)));
1915        assert_eq!((i256::from(0), false), i256::from(0).overflowing_add(i256::from(0)));
1916        assert_eq!((i256::MIN, true), i256::from(1).overflowing_add(i256::MAX));
1917    }
1918
1919    #[test]
1920    fn i256_sub_test() {
1921        assert_eq!((i256::from(-1), false), i256::from(1).overflowing_sub(i256::from(2)));
1922        assert_eq!((i256::from(1), false), i256::from(3).overflowing_sub(i256::from(2)));
1923        assert_eq!((i256::from(-3), false), i256::from(-4).overflowing_sub(i256::from(-1)));
1924        assert_eq!((i256::from(0), false), i256::from(0).overflowing_add(i256::from(0)));
1925        assert_eq!((i256::MIN, false), i256::from(0).overflowing_sub(i256::MIN));
1926        assert_eq!((i256::ZERO, false), i256::MIN.overflowing_sub(i256::MIN));
1927        assert_eq!((-i256::ONE, false), i256::MAX.overflowing_sub(i256::MIN));
1928        assert_eq!((i256::MAX, true), (-i256::from(2)).overflowing_sub(i256::MAX));
1929    }
1930
1931    #[test]
1932    fn i256_neg_test() {
1933        assert_eq!(i256::from(1), -i256::from(-1));
1934        assert_eq!(i256::from(-1), -i256::from(1));
1935        assert_eq!(i256::from(0), -i256::from(0));
1936        assert_eq!(i256::MIN + 1, -i256::MAX);
1937    }
1938
1939    #[test]
1940    #[should_panic]
1941    fn i256_neg_min_test() {
1942        assert_eq!(-i256::MIN, -i256::MIN);
1943    }
1944
1945    #[test]
1946    fn i256_mul_test() {
1947        assert_eq!((i256::from(-12), false), i256::from(3).overflowing_mul(i256::from(-4)));
1948        assert_eq!((i256::from(6), false), i256::from(2).overflowing_mul(i256::from(3)));
1949        assert_eq!((i256::from(30), false), i256::from(-6).overflowing_mul(i256::from(-5)));
1950        assert_eq!((i256::from(-2), true), i256::MAX.overflowing_mul(i256::from(2)));
1951        assert_eq!((i256::ZERO, true), i256::MIN.overflowing_mul(i256::from(2)));
1952        assert_eq!((i256::ONE, true), i256::MAX.overflowing_mul(i256::MAX));
1953    }
1954
1955    #[test]
1956    fn i256_arithmetic_shr_test() {
1957        assert_eq!(i256::from(-1), i256::from(-1) >> 1);
1958        assert_eq!(i256::from(-1), i256::from(-2) >> 1);
1959        assert_eq!(i256::from(1), i256::from(2) >> 1);
1960        assert_eq!(i256::from(1), i256::from(2) >> 1);
1961        assert_eq!(i256::from(0), i256::from(1) >> 1);
1962    }
1963
1964    #[test]
1965    fn i256_bits_required_test() {
1966        assert_eq!(i256::from(255).bits_required(), 9);
1967        assert_eq!(i256::from(256).bits_required(), 10);
1968        assert_eq!(i256::from(300).bits_required(), 10);
1969        assert_eq!(i256::from(60000).bits_required(), 17);
1970        assert_eq!(i256::from(70000).bits_required(), 18);
1971        assert_eq!(i256::from(-128).bits_required(), 8);
1972        assert_eq!(i256::from(-129).bits_required(), 9);
1973        assert_eq!(i256::from(0).bits_required(), 1);
1974        assert_eq!(i256::from(-1).bits_required(), 1);
1975        assert_eq!(i256::from(-2).bits_required(), 2);
1976        assert_eq!(i256::MIN.bits_required(), 256);
1977        assert_eq!(i256::MAX.bits_required(), 256);
1978    }
1979
1980    #[test]
1981    fn i256_div_test() {
1982        assert_eq!(Ok((i256::from(3), i256::from(1))), i256::from(7).div_rem(i256::from(2i32)));
1983        assert_eq!(Ok((i256::from(-3), i256::from(1))), i256::from(7).div_rem(i256::from(-2i128)));
1984        assert_eq!(Ok((i256::from(-3), i256::from(-1))), i256::from(-7).div_rem(i256::from(2)));
1985        assert_eq!(Ok((i256::from(3), i256::from(-1))), i256::from(-7).div_rem(i256::from(-2)));
1986        assert!(i256::div_rem(i256::MAX, i256::ZERO).is_err());
1987    }
1988
1989    #[test]
1990    fn overflowing_div_est() {
1991        assert_eq!((i256::from(3), false), i256::from(7).overflowing_div(i256::from(2i32)));
1992        assert_eq!((i256::MIN, true), i256::MIN.overflowing_div(i256::from(-1)));
1993        let res = std::panic::catch_unwind(|| i256::overflowing_div(i256::MAX, i256::ZERO));
1994        assert!(res.is_err());
1995    }
1996
1997    #[test]
1998    fn wrapping_div_est() {
1999        assert_eq!(i1024::from(3), i1024::from(7).wrapping_div(2));
2000        assert_eq!(i512::MIN, i512::MIN.wrapping_div(-1));
2001        let res = std::panic::catch_unwind(|| i256::wrapping_div(i256::MAX, i256::ZERO));
2002        assert!(res.is_err());
2003    }
2004
2005    #[test]
2006    fn checked_div_est() {
2007        assert_eq!(Some(i1024::from(3)), i1024::from(7).checked_div(2));
2008        assert_eq!(Some(i512::MAX), i512::MAX.checked_div(1));
2009        assert_eq!(Some(i512::MIN + 1), i512::MAX.checked_div(-1));
2010        assert_eq!(None, i512::MIN.checked_div(-1));
2011        assert_eq!(None, i512::MAX.checked_div(0));
2012    }
2013
2014    #[test]
2015    fn saturating_div_test() {
2016        assert_eq!(i256::from(5).saturating_div(2), i256::from(2));
2017        assert_eq!(i256::MAX.saturating_div(-i256::ONE), i256::MIN + 1);
2018        assert_eq!(i256::MIN.saturating_div(-1), i256::MAX);
2019    }
2020
2021    #[test]
2022    fn overflowing_rem_est() {
2023        assert_eq!((i256::from(1), false), i256::from(7).overflowing_rem(i256::from(2i32)));
2024        assert_eq!((i256::ZERO, true), i256::MIN.overflowing_rem(i256::from(-1)));
2025        let res = std::panic::catch_unwind(|| i256::overflowing_rem(i256::MAX, i256::ZERO));
2026        assert!(res.is_err());
2027    }
2028
2029    #[test]
2030    fn wrapping_rem_test() {
2031        assert_eq!(i1024::from(1), i1024::from(7).wrapping_rem(2));
2032        assert_eq!(i512::ZERO, i512::MIN.wrapping_rem(-1));
2033        let res = std::panic::catch_unwind(|| i256::wrapping_rem(i256::MAX, i256::ZERO));
2034        assert!(res.is_err());
2035    }
2036
2037    #[test]
2038    fn checked_rem_test() {
2039        assert_eq!(Some(i1024::from(1)), i1024::from(7).checked_rem(2));
2040        assert_eq!(None, i512::MIN.checked_rem(-1));
2041        assert_eq!(None, i512::MAX.checked_rem(0));
2042    }
2043
2044    #[test]
2045    fn div_euclid_test() {
2046        assert_eq!(i1024::from(1), i1024::from(7).div_euclid(4));
2047        assert_eq!(i1024::from(-1), i1024::from(7).div_euclid(-4));
2048        assert_eq!(i1024::from(-2), i1024::from(-7).div_euclid(4));
2049        assert_eq!(i1024::from(2), i1024::from(-7).div_euclid(-4));
2050    }
2051
2052    #[test]
2053    fn overflowing_div_euclid_test() {
2054        assert_eq!((u512::from(2u8), false), u512::from(5u8).overflowing_div_euclid(2u8));
2055        assert_eq!((i1024::MIN, true), i1024::MIN.overflowing_div_euclid(-1));
2056    }
2057
2058    #[test]
2059    fn wrapping_div_euclid_test() {
2060        assert_eq!(u256::from(10u8), u256::from(100u8).wrapping_div_euclid(10u8));
2061        assert_eq!(i1024::MIN, i1024::MIN.wrapping_div_euclid(-1));
2062    }
2063
2064    #[test]
2065    fn checked_div_euclid_test() {
2066        assert_eq!(None, u256::from(100u8).checked_div_euclid(0u8));
2067        assert_eq!(None, i1024::MIN.checked_div_euclid(-1));
2068        assert_eq!(Some(i1024::from(-3)), i1024::from(6).checked_div_euclid(-2));
2069    }
2070
2071    #[test]
2072    fn rem_euclid_test() {
2073        assert_eq!(i1024::from(3), i1024::from(7).rem_euclid(4));
2074        assert_eq!(i1024::from(1), i1024::from(-7).rem_euclid(4));
2075        assert_eq!(i1024::from(3), i1024::from(7).rem_euclid(-4));
2076        assert_eq!(i1024::from(1), i1024::from(-7).rem_euclid(-4));
2077    }
2078
2079    #[test]
2080    fn overflowing_rem_euclid_test() {
2081        assert_eq!((u512::from(1u8), false), u512::from(5u8).overflowing_rem_euclid(2u8));
2082        assert_eq!((i1024::ZERO, true), i1024::MIN.overflowing_rem_euclid(-1));
2083    }
2084
2085    #[test]
2086    fn wrapping_rem_euclid_test() {
2087        assert_eq!(u256::ZERO, u256::from(100u8).wrapping_rem_euclid(10u8));
2088        assert_eq!(i1024::ZERO, i1024::MIN.wrapping_rem_euclid(-1));
2089    }
2090
2091    #[test]
2092    fn checked_rem_euclid_test() {
2093        assert_eq!(None, u256::from(100u8).checked_rem_euclid(0u8));
2094        assert_eq!(None, i1024::MIN.checked_rem_euclid(-1));
2095        assert_eq!(Some(i1024::from(1)), i1024::from(5).checked_rem_euclid(2));
2096    }
2097
2098    #[test]
2099    fn i256_cmp_test() {
2100        assert!(i256::ZERO < i256::ONE);
2101        assert!(-i256::ONE < i256::ZERO);
2102        assert!(i256::MIN < i256::MAX);
2103        assert!(i256::MIN < i256::ZERO);
2104        assert!(i256::from(200) < i256::from(10000000));
2105        assert!(i256::from(-3) < i256::from(87));
2106    }
2107
2108    #[test]
2109    fn u256_to_u512_test() {
2110        assert_eq!(u512::from(u256::from(30u8)), u512::from(30u8));
2111    }
2112
2113    #[test]
2114    fn leading_zeros_test() {
2115        assert_eq!(u512::ZERO.leading_zeros(), 512);
2116        assert_eq!(u512::ZERO.leading_ones(), 0);
2117        assert_eq!(u512::ZERO.trailing_zeros(), 512);
2118        assert_eq!(u512::ZERO.trailing_ones(), 0);
2119        assert_eq!(u512::MAX.leading_zeros(), 0);
2120        assert_eq!(u512::MAX.leading_ones(), 512);
2121        assert_eq!(u512::MAX.trailing_zeros(), 0);
2122        assert_eq!(u512::MAX.trailing_ones(), 512);
2123        assert_eq!(u256::from(32u8).leading_zeros(), 256 - 6);
2124        assert_eq!(u256::from(32u8).leading_ones(), 0);
2125        assert_eq!(u256::from(32u8).trailing_zeros(), 5);
2126        assert_eq!(u256::from(32u8).trailing_ones(), 0);
2127        assert_eq!(i256::from(-2).leading_zeros(), 0);
2128        assert_eq!(i256::from(-2).leading_ones(), 255);
2129        assert_eq!(i256::from(-2).trailing_zeros(), 1);
2130        assert_eq!(i256::from(-2).trailing_ones(), 0);
2131    }
2132
2133    #[test]
2134    fn checked_shl_test() {
2135        assert_eq!(i256::from(4).checked_shl(0), Some(i256::from(4)));
2136        assert_eq!(i256::from(4).checked_shl(1), Some(i256::from(8)));
2137        assert_eq!(i256::from(1).checked_shl(255), Some(i256::MIN));
2138        assert_eq!(i256::from(4).checked_shl(255), Some(i256::from(0)));
2139        assert_eq!(i256::from(4).checked_shl(256), None);
2140        assert_eq!(u256::from(4u8).checked_shl(0), Some(u256::from(4u8)));
2141        assert_eq!(u256::from(4u8).checked_shl(1), Some(u256::from(8u8)));
2142        assert_eq!(u256::from(4u8).checked_shl(255), Some(u256::from(0u8)));
2143        assert_eq!(u256::from(4u8).checked_shl(256), None);
2144    }
2145
2146    #[test]
2147    fn checked_shr_test() {
2148        assert_eq!(i256::from(4).checked_shr(0), Some(i256::from(4)));
2149        assert_eq!(i256::from(4).checked_shr(1), Some(i256::from(2)));
2150        assert_eq!(i256::from(4).checked_shr(255), Some(i256::from(0)));
2151        assert_eq!(i256::from(4).checked_shr(256), None);
2152        assert_eq!(u256::from(4u8).checked_shr(0), Some(u256::from(4u8)));
2153        assert_eq!(u256::from(4u8).checked_shr(1), Some(u256::from(2u8)));
2154        assert_eq!(u256::from(4u8).checked_shr(255), Some(u256::from(0u8)));
2155        assert_eq!(u256::from(4u8).checked_shr(256), None);
2156    }
2157
2158    #[test]
2159    fn wrapping_neg_test() {
2160        assert_eq!(i256::from(2).wrapping_neg(), i256::from(-2));
2161        assert_eq!(i256::MIN.wrapping_neg(), i256::MIN);
2162        assert_eq!(i256::from(0).wrapping_neg(), i256::from(0));
2163        assert_eq!(u256::from(1u8).wrapping_neg(), u256::MAX);
2164    }
2165}