bigint: Break out into multiple files

This commit is contained in:
Kent Overstreet 2016-07-18 15:56:03 -08:00
parent 78bad13948
commit 279522316c
7 changed files with 5230 additions and 5174 deletions

586
bigint/src/algorithms.rs Normal file
View File

@ -0,0 +1,586 @@
use std::borrow::Cow;
use std::cmp;
use std::cmp::Ordering::{self, Less, Greater, Equal};
use std::iter::repeat;
use std::mem;
use traits;
use traits::{Zero, One};
use biguint::BigUint;
use bigint::Sign;
use bigint::Sign::{Minus, NoSign, Plus};
#[allow(non_snake_case)]
pub mod big_digit {
/// A `BigDigit` is a `BigUint`'s composing element.
pub type BigDigit = u32;
/// A `DoubleBigDigit` is the internal type used to do the computations. Its
/// size is the double of the size of `BigDigit`.
pub type DoubleBigDigit = u64;
pub const ZERO_BIG_DIGIT: BigDigit = 0;
// `DoubleBigDigit` size dependent
pub const BITS: usize = 32;
pub const BASE: DoubleBigDigit = 1 << BITS;
const LO_MASK: DoubleBigDigit = (-1i32 as DoubleBigDigit) >> BITS;
#[inline]
fn get_hi(n: DoubleBigDigit) -> BigDigit {
(n >> BITS) as BigDigit
}
#[inline]
fn get_lo(n: DoubleBigDigit) -> BigDigit {
(n & LO_MASK) as BigDigit
}
/// Split one `DoubleBigDigit` into two `BigDigit`s.
#[inline]
pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) {
(get_hi(n), get_lo(n))
}
/// Join two `BigDigit`s into one `DoubleBigDigit`
#[inline]
pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit {
(lo as DoubleBigDigit) | ((hi as DoubleBigDigit) << BITS)
}
}
use big_digit::{BigDigit, DoubleBigDigit};
// Generic functions for add/subtract/multiply with carry/borrow:
// Add with carry:
#[inline]
fn adc(a: BigDigit, b: BigDigit, carry: &mut BigDigit) -> BigDigit {
let (hi, lo) = big_digit::from_doublebigdigit((a as DoubleBigDigit) + (b as DoubleBigDigit) +
(*carry as DoubleBigDigit));
*carry = hi;
lo
}
// Subtract with borrow:
#[inline]
fn sbb(a: BigDigit, b: BigDigit, borrow: &mut BigDigit) -> BigDigit {
let (hi, lo) = big_digit::from_doublebigdigit(big_digit::BASE + (a as DoubleBigDigit) -
(b as DoubleBigDigit) -
(*borrow as DoubleBigDigit));
// hi * (base) + lo == 1*(base) + ai - bi - borrow
// => ai - bi - borrow < 0 <=> hi == 0
*borrow = (hi == 0) as BigDigit;
lo
}
#[inline]
pub fn mac_with_carry(a: BigDigit, b: BigDigit, c: BigDigit, carry: &mut BigDigit) -> BigDigit {
let (hi, lo) = big_digit::from_doublebigdigit((a as DoubleBigDigit) +
(b as DoubleBigDigit) * (c as DoubleBigDigit) +
(*carry as DoubleBigDigit));
*carry = hi;
lo
}
/// Divide a two digit numerator by a one digit divisor, returns quotient and remainder:
///
/// Note: the caller must ensure that both the quotient and remainder will fit into a single digit.
/// This is _not_ true for an arbitrary numerator/denominator.
///
/// (This function also matches what the x86 divide instruction does).
#[inline]
fn div_wide(hi: BigDigit, lo: BigDigit, divisor: BigDigit) -> (BigDigit, BigDigit) {
debug_assert!(hi < divisor);
let lhs = big_digit::to_doublebigdigit(hi, lo);
let rhs = divisor as DoubleBigDigit;
((lhs / rhs) as BigDigit, (lhs % rhs) as BigDigit)
}
pub fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) {
let mut rem = 0;
for d in a.data.iter_mut().rev() {
let (q, r) = div_wide(rem, *d, b);
*d = q;
rem = r;
}
(a.normalize(), rem)
}
// Only for the Add impl:
#[must_use]
#[inline]
pub fn __add2(a: &mut [BigDigit], b: &[BigDigit]) -> BigDigit {
debug_assert!(a.len() >= b.len());
let mut carry = 0;
let (a_lo, a_hi) = a.split_at_mut(b.len());
for (a, b) in a_lo.iter_mut().zip(b) {
*a = adc(*a, *b, &mut carry);
}
if carry != 0 {
for a in a_hi {
*a = adc(*a, 0, &mut carry);
if carry == 0 { break }
}
}
carry
}
/// /Two argument addition of raw slices:
/// a += b
///
/// The caller _must_ ensure that a is big enough to store the result - typically this means
/// resizing a to max(a.len(), b.len()) + 1, to fit a possible carry.
pub fn add2(a: &mut [BigDigit], b: &[BigDigit]) {
let carry = __add2(a, b);
debug_assert!(carry == 0);
}
pub fn sub2(a: &mut [BigDigit], b: &[BigDigit]) {
let mut borrow = 0;
let len = cmp::min(a.len(), b.len());
let (a_lo, a_hi) = a.split_at_mut(len);
let (b_lo, b_hi) = b.split_at(len);
for (a, b) in a_lo.iter_mut().zip(b_lo) {
*a = sbb(*a, *b, &mut borrow);
}
if borrow != 0 {
for a in a_hi {
*a = sbb(*a, 0, &mut borrow);
if borrow == 0 { break }
}
}
// note: we're _required_ to fail on underflow
assert!(borrow == 0 && b_hi.iter().all(|x| *x == 0),
"Cannot subtract b from a because b is larger than a.");
}
pub fn sub2rev(a: &[BigDigit], b: &mut [BigDigit]) {
debug_assert!(b.len() >= a.len());
let mut borrow = 0;
let len = cmp::min(a.len(), b.len());
let (a_lo, a_hi) = a.split_at(len);
let (b_lo, b_hi) = b.split_at_mut(len);
for (a, b) in a_lo.iter().zip(b_lo) {
*b = sbb(*a, *b, &mut borrow);
}
assert!(a_hi.is_empty());
// note: we're _required_ to fail on underflow
assert!(borrow == 0 && b_hi.iter().all(|x| *x == 0),
"Cannot subtract b from a because b is larger than a.");
}
pub fn sub_sign(a: &[BigDigit], b: &[BigDigit]) -> (Sign, BigUint) {
// Normalize:
let a = &a[..a.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
let b = &b[..b.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
match cmp_slice(a, b) {
Greater => {
let mut a = a.to_vec();
sub2(&mut a, b);
(Plus, BigUint::new(a))
}
Less => {
let mut b = b.to_vec();
sub2(&mut b, a);
(Minus, BigUint::new(b))
}
_ => (NoSign, Zero::zero()),
}
}
/// Three argument multiply accumulate:
/// acc += b * c
fn mac_digit(acc: &mut [BigDigit], b: &[BigDigit], c: BigDigit) {
if c == 0 {
return;
}
let mut b_iter = b.iter();
let mut carry = 0;
for ai in acc.iter_mut() {
if let Some(bi) = b_iter.next() {
*ai = mac_with_carry(*ai, *bi, c, &mut carry);
} else if carry != 0 {
*ai = mac_with_carry(*ai, 0, c, &mut carry);
} else {
break;
}
}
assert!(carry == 0);
}
/// Three argument multiply accumulate:
/// acc += b * c
fn mac3(acc: &mut [BigDigit], b: &[BigDigit], c: &[BigDigit]) {
let (x, y) = if b.len() < c.len() {
(b, c)
} else {
(c, b)
};
// Karatsuba multiplication is slower than long multiplication for small x and y:
//
if x.len() <= 4 {
for (i, xi) in x.iter().enumerate() {
mac_digit(&mut acc[i..], y, *xi);
}
} else {
/*
* Karatsuba multiplication:
*
* The idea is that we break x and y up into two smaller numbers that each have about half
* as many digits, like so (note that multiplying by b is just a shift):
*
* x = x0 + x1 * b
* y = y0 + y1 * b
*
* With some algebra, we can compute x * y with three smaller products, where the inputs to
* each of the smaller products have only about half as many digits as x and y:
*
* x * y = (x0 + x1 * b) * (y0 + y1 * b)
*
* x * y = x0 * y0
* + x0 * y1 * b
* + x1 * y0 * b
* + x1 * y1 * b^2
*
* Let p0 = x0 * y0 and p2 = x1 * y1:
*
* x * y = p0
* + (x0 * y1 + x1 * p0) * b
* + p2 * b^2
*
* The real trick is that middle term:
*
* x0 * y1 + x1 * y0
*
* = x0 * y1 + x1 * y0 - p0 + p0 - p2 + p2
*
* = x0 * y1 + x1 * y0 - x0 * y0 - x1 * y1 + p0 + p2
*
* Now we complete the square:
*
* = -(x0 * y0 - x0 * y1 - x1 * y0 + x1 * y1) + p0 + p2
*
* = -((x1 - x0) * (y1 - y0)) + p0 + p2
*
* Let p1 = (x1 - x0) * (y1 - y0), and substitute back into our original formula:
*
* x * y = p0
* + (p0 + p2 - p1) * b
* + p2 * b^2
*
* Where the three intermediate products are:
*
* p0 = x0 * y0
* p1 = (x1 - x0) * (y1 - y0)
* p2 = x1 * y1
*
* In doing the computation, we take great care to avoid unnecessary temporary variables
* (since creating a BigUint requires a heap allocation): thus, we rearrange the formula a
* bit so we can use the same temporary variable for all the intermediate products:
*
* x * y = p2 * b^2 + p2 * b
* + p0 * b + p0
* - p1 * b
*
* The other trick we use is instead of doing explicit shifts, we slice acc at the
* appropriate offset when doing the add.
*/
/*
* When x is smaller than y, it's significantly faster to pick b such that x is split in
* half, not y:
*/
let b = x.len() / 2;
let (x0, x1) = x.split_at(b);
let (y0, y1) = y.split_at(b);
/*
* We reuse the same BigUint for all the intermediate multiplies and have to size p
* appropriately here: x1.len() >= x0.len and y1.len() >= y0.len():
*/
let len = x1.len() + y1.len() + 1;
let mut p = BigUint { data: vec![0; len] };
// p2 = x1 * y1
mac3(&mut p.data[..], x1, y1);
// Not required, but the adds go faster if we drop any unneeded 0s from the end:
p = p.normalize();
add2(&mut acc[b..], &p.data[..]);
add2(&mut acc[b * 2..], &p.data[..]);
// Zero out p before the next multiply:
p.data.truncate(0);
p.data.extend(repeat(0).take(len));
// p0 = x0 * y0
mac3(&mut p.data[..], x0, y0);
p = p.normalize();
add2(&mut acc[..], &p.data[..]);
add2(&mut acc[b..], &p.data[..]);
// p1 = (x1 - x0) * (y1 - y0)
// We do this one last, since it may be negative and acc can't ever be negative:
let (j0_sign, j0) = sub_sign(x1, x0);
let (j1_sign, j1) = sub_sign(y1, y0);
match j0_sign * j1_sign {
Plus => {
p.data.truncate(0);
p.data.extend(repeat(0).take(len));
mac3(&mut p.data[..], &j0.data[..], &j1.data[..]);
p = p.normalize();
sub2(&mut acc[b..], &p.data[..]);
},
Minus => {
mac3(&mut acc[b..], &j0.data[..], &j1.data[..]);
},
NoSign => (),
}
}
}
pub fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint {
let len = x.len() + y.len() + 1;
let mut prod = BigUint { data: vec![0; len] };
mac3(&mut prod.data[..], x, y);
prod.normalize()
}
pub fn div_rem(u: &BigUint, d: &BigUint) -> (BigUint, BigUint) {
if d.is_zero() {
panic!()
}
if u.is_zero() {
return (Zero::zero(), Zero::zero());
}
if *d == One::one() {
return (u.clone(), Zero::zero());
}
// Required or the q_len calculation below can underflow:
match u.cmp(d) {
Less => return (Zero::zero(), u.clone()),
Equal => return (One::one(), Zero::zero()),
Greater => {} // Do nothing
}
// This algorithm is from Knuth, TAOCP vol 2 section 4.3, algorithm D:
//
// First, normalize the arguments so the highest bit in the highest digit of the divisor is
// set: the main loop uses the highest digit of the divisor for generating guesses, so we
// want it to be the largest number we can efficiently divide by.
//
let shift = d.data.last().unwrap().leading_zeros() as usize;
let mut a = u << shift;
let b = d << shift;
// The algorithm works by incrementally calculating "guesses", q0, for part of the
// remainder. Once we have any number q0 such that q0 * b <= a, we can set
//
// q += q0
// a -= q0 * b
//
// and then iterate until a < b. Then, (q, a) will be our desired quotient and remainder.
//
// q0, our guess, is calculated by dividing the last few digits of a by the last digit of b
// - this should give us a guess that is "close" to the actual quotient, but is possibly
// greater than the actual quotient. If q0 * b > a, we simply use iterated subtraction
// until we have a guess such that q0 & b <= a.
//
let bn = *b.data.last().unwrap();
let q_len = a.data.len() - b.data.len() + 1;
let mut q = BigUint { data: vec![0; q_len] };
// We reuse the same temporary to avoid hitting the allocator in our inner loop - this is
// sized to hold a0 (in the common case; if a particular digit of the quotient is zero a0
// can be bigger).
//
let mut tmp = BigUint { data: Vec::with_capacity(2) };
for j in (0..q_len).rev() {
/*
* When calculating our next guess q0, we don't need to consider the digits below j
* + b.data.len() - 1: we're guessing digit j of the quotient (i.e. q0 << j) from
* digit bn of the divisor (i.e. bn << (b.data.len() - 1) - so the product of those
* two numbers will be zero in all digits up to (j + b.data.len() - 1).
*/
let offset = j + b.data.len() - 1;
if offset >= a.data.len() {
continue;
}
/* just avoiding a heap allocation: */
let mut a0 = tmp;
a0.data.truncate(0);
a0.data.extend(a.data[offset..].iter().cloned());
/*
* q0 << j * big_digit::BITS is our actual quotient estimate - we do the shifts
* implicitly at the end, when adding and subtracting to a and q. Not only do we
* save the cost of the shifts, the rest of the arithmetic gets to work with
* smaller numbers.
*/
let (mut q0, _) = div_rem_digit(a0, bn);
let mut prod = &b * &q0;
while cmp_slice(&prod.data[..], &a.data[j..]) == Greater {
let one: BigUint = One::one();
q0 = q0 - one;
prod = prod - &b;
}
add2(&mut q.data[j..], &q0.data[..]);
sub2(&mut a.data[j..], &prod.data[..]);
a = a.normalize();
tmp = q0;
}
debug_assert!(a < b);
(q.normalize(), a >> shift)
}
/// Find last set bit
/// fls(0) == 0, fls(u32::MAX) == 32
pub fn fls<T: traits::PrimInt>(v: T) -> usize {
mem::size_of::<T>() * 8 - v.leading_zeros() as usize
}
pub fn ilog2<T: traits::PrimInt>(v: T) -> usize {
fls(v) - 1
}
#[inline]
pub fn biguint_shl(n: Cow<BigUint>, bits: usize) -> BigUint {
let n_unit = bits / big_digit::BITS;
let mut data = match n_unit {
0 => n.into_owned().data,
_ => {
let len = n_unit + n.data.len() + 1;
let mut data = Vec::with_capacity(len);
data.extend(repeat(0).take(n_unit));
data.extend(n.data.iter().cloned());
data
}
};
let n_bits = bits % big_digit::BITS;
if n_bits > 0 {
let mut carry = 0;
for elem in data[n_unit..].iter_mut() {
let new_carry = *elem >> (big_digit::BITS - n_bits);
*elem = (*elem << n_bits) | carry;
carry = new_carry;
}
if carry != 0 {
data.push(carry);
}
}
BigUint::new(data)
}
#[inline]
pub fn biguint_shr(n: Cow<BigUint>, bits: usize) -> BigUint {
let n_unit = bits / big_digit::BITS;
if n_unit >= n.data.len() {
return Zero::zero();
}
let mut data = match n_unit {
0 => n.into_owned().data,
_ => n.data[n_unit..].to_vec(),
};
let n_bits = bits % big_digit::BITS;
if n_bits > 0 {
let mut borrow = 0;
for elem in data.iter_mut().rev() {
let new_borrow = *elem << (big_digit::BITS - n_bits);
*elem = (*elem >> n_bits) | borrow;
borrow = new_borrow;
}
}
BigUint::new(data)
}
pub fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering {
debug_assert!(a.last() != Some(&0));
debug_assert!(b.last() != Some(&0));
let (a_len, b_len) = (a.len(), b.len());
if a_len < b_len {
return Less;
}
if a_len > b_len {
return Greater;
}
for (&ai, &bi) in a.iter().rev().zip(b.iter().rev()) {
if ai < bi {
return Less;
}
if ai > bi {
return Greater;
}
}
return Equal;
}
#[cfg(test)]
mod algorithm_tests {
use {BigDigit, BigUint, BigInt};
use Sign::Plus;
use traits::Num;
#[test]
fn test_sub_sign() {
use super::sub_sign;
fn sub_sign_i(a: &[BigDigit], b: &[BigDigit]) -> BigInt {
let (sign, val) = sub_sign(a, b);
BigInt::from_biguint(sign, val)
}
let a = BigUint::from_str_radix("265252859812191058636308480000000", 10).unwrap();
let b = BigUint::from_str_radix("26525285981219105863630848000000", 10).unwrap();
let a_i = BigInt::from_biguint(Plus, a.clone());
let b_i = BigInt::from_biguint(Plus, b.clone());
assert_eq!(sub_sign_i(&a.data[..], &b.data[..]), &a_i - &b_i);
assert_eq!(sub_sign_i(&b.data[..], &a.data[..]), &b_i - &a_i);
}
}

1107
bigint/src/bigint.rs Normal file

File diff suppressed because it is too large Load Diff

1199
bigint/src/biguint.rs Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

133
bigint/src/macros.rs Normal file
View File

@ -0,0 +1,133 @@
macro_rules! forward_val_val_binop {
(impl $imp:ident for $res:ty, $method:ident) => {
impl $imp<$res> for $res {
type Output = $res;
#[inline]
fn $method(self, other: $res) -> $res {
// forward to val-ref
$imp::$method(self, &other)
}
}
}
}
macro_rules! forward_val_val_binop_commutative {
(impl $imp:ident for $res:ty, $method:ident) => {
impl $imp<$res> for $res {
type Output = $res;
#[inline]
fn $method(self, other: $res) -> $res {
// forward to val-ref, with the larger capacity as val
if self.data.capacity() >= other.data.capacity() {
$imp::$method(self, &other)
} else {
$imp::$method(other, &self)
}
}
}
}
}
macro_rules! forward_ref_val_binop {
(impl $imp:ident for $res:ty, $method:ident) => {
impl<'a> $imp<$res> for &'a $res {
type Output = $res;
#[inline]
fn $method(self, other: $res) -> $res {
// forward to ref-ref
$imp::$method(self, &other)
}
}
}
}
macro_rules! forward_ref_val_binop_commutative {
(impl $imp:ident for $res:ty, $method:ident) => {
impl<'a> $imp<$res> for &'a $res {
type Output = $res;
#[inline]
fn $method(self, other: $res) -> $res {
// reverse, forward to val-ref
$imp::$method(other, self)
}
}
}
}
macro_rules! forward_val_ref_binop {
(impl $imp:ident for $res:ty, $method:ident) => {
impl<'a> $imp<&'a $res> for $res {
type Output = $res;
#[inline]
fn $method(self, other: &$res) -> $res {
// forward to ref-ref
$imp::$method(&self, other)
}
}
}
}
macro_rules! forward_ref_ref_binop {
(impl $imp:ident for $res:ty, $method:ident) => {
impl<'a, 'b> $imp<&'b $res> for &'a $res {
type Output = $res;
#[inline]
fn $method(self, other: &$res) -> $res {
// forward to val-ref
$imp::$method(self.clone(), other)
}
}
}
}
macro_rules! forward_ref_ref_binop_commutative {
(impl $imp:ident for $res:ty, $method:ident) => {
impl<'a, 'b> $imp<&'b $res> for &'a $res {
type Output = $res;
#[inline]
fn $method(self, other: &$res) -> $res {
// forward to val-ref, choosing the larger to clone
if self.data.len() >= other.data.len() {
$imp::$method(self.clone(), other)
} else {
$imp::$method(other.clone(), self)
}
}
}
}
}
// Forward everything to ref-ref, when reusing storage is not helpful
macro_rules! forward_all_binop_to_ref_ref {
(impl $imp:ident for $res:ty, $method:ident) => {
forward_val_val_binop!(impl $imp for $res, $method);
forward_val_ref_binop!(impl $imp for $res, $method);
forward_ref_val_binop!(impl $imp for $res, $method);
};
}
// Forward everything to val-ref, so LHS storage can be reused
macro_rules! forward_all_binop_to_val_ref {
(impl $imp:ident for $res:ty, $method:ident) => {
forward_val_val_binop!(impl $imp for $res, $method);
forward_ref_val_binop!(impl $imp for $res, $method);
forward_ref_ref_binop!(impl $imp for $res, $method);
};
}
// Forward everything to val-ref, commutatively, so either LHS or RHS storage can be reused
macro_rules! forward_all_binop_to_val_ref_commutative {
(impl $imp:ident for $res:ty, $method:ident) => {
forward_val_val_binop_commutative!(impl $imp for $res, $method);
forward_ref_val_binop_commutative!(impl $imp for $res, $method);
forward_ref_ref_binop_commutative!(impl $imp for $res, $method);
};
}

954
bigint/src/tests/bigint.rs Normal file
View File

@ -0,0 +1,954 @@
use {BigDigit, BigUint, big_digit};
use {Sign, BigInt, RandBigInt, ToBigInt};
use Sign::{Minus, NoSign, Plus};
use std::cmp::Ordering::{Less, Equal, Greater};
use std::{f32, f64};
use std::{i8, i16, i32, i64, isize};
use std::iter::repeat;
use std::{u8, u16, u32, u64, usize};
use std::ops::Neg;
use rand::thread_rng;
use integer::Integer;
use traits::{Zero, One, Signed, ToPrimitive, FromPrimitive, Num, Float};
/// Assert that an op works for all val/ref combinations
macro_rules! assert_op {
($left:ident $op:tt $right:ident == $expected:expr) => {
assert_eq!((&$left) $op (&$right), $expected);
assert_eq!((&$left) $op $right.clone(), $expected);
assert_eq!($left.clone() $op (&$right), $expected);
assert_eq!($left.clone() $op $right.clone(), $expected);
};
}
#[test]
fn test_from_biguint() {
fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) {
let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_usize(inp_n).unwrap());
let ans = BigInt {
sign: ans_s,
data: FromPrimitive::from_usize(ans_n).unwrap(),
};
assert_eq!(inp, ans);
}
check(Plus, 1, Plus, 1);
check(Plus, 0, NoSign, 0);
check(Minus, 1, Minus, 1);
check(NoSign, 1, NoSign, 0);
}
#[test]
fn test_from_bytes_be() {
fn check(s: &str, result: &str) {
assert_eq!(BigInt::from_bytes_be(Plus, s.as_bytes()),
BigInt::parse_bytes(result.as_bytes(), 10).unwrap());
}
check("A", "65");
check("AA", "16705");
check("AB", "16706");
check("Hello world!", "22405534230753963835153736737");
assert_eq!(BigInt::from_bytes_be(Plus, &[]), Zero::zero());
assert_eq!(BigInt::from_bytes_be(Minus, &[]), Zero::zero());
}
#[test]
fn test_to_bytes_be() {
fn check(s: &str, result: &str) {
let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap();
let (sign, v) = b.to_bytes_be();
assert_eq!((Plus, s.as_bytes()), (sign, &*v));
}
check("A", "65");
check("AA", "16705");
check("AB", "16706");
check("Hello world!", "22405534230753963835153736737");
let b: BigInt = Zero::zero();
assert_eq!(b.to_bytes_be(), (NoSign, vec![0]));
// Test with leading/trailing zero bytes and a full BigDigit of value 0
let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap();
assert_eq!(b.to_bytes_be(), (Plus, vec![1, 0, 0, 0, 0, 0, 0, 2, 0]));
}
#[test]
fn test_from_bytes_le() {
fn check(s: &str, result: &str) {
assert_eq!(BigInt::from_bytes_le(Plus, s.as_bytes()),
BigInt::parse_bytes(result.as_bytes(), 10).unwrap());
}
check("A", "65");
check("AA", "16705");
check("BA", "16706");
check("!dlrow olleH", "22405534230753963835153736737");
assert_eq!(BigInt::from_bytes_le(Plus, &[]), Zero::zero());
assert_eq!(BigInt::from_bytes_le(Minus, &[]), Zero::zero());
}
#[test]
fn test_to_bytes_le() {
fn check(s: &str, result: &str) {
let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap();
let (sign, v) = b.to_bytes_le();
assert_eq!((Plus, s.as_bytes()), (sign, &*v));
}
check("A", "65");
check("AA", "16705");
check("BA", "16706");
check("!dlrow olleH", "22405534230753963835153736737");
let b: BigInt = Zero::zero();
assert_eq!(b.to_bytes_le(), (NoSign, vec![0]));
// Test with leading/trailing zero bytes and a full BigDigit of value 0
let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap();
assert_eq!(b.to_bytes_le(), (Plus, vec![0, 2, 0, 0, 0, 0, 0, 0, 1]));
}
#[test]
fn test_cmp() {
let vs: [&[BigDigit]; 4] = [&[2 as BigDigit], &[1, 1], &[2, 1], &[1, 1, 1]];
let mut nums = Vec::new();
for s in vs.iter().rev() {
nums.push(BigInt::from_slice(Minus, *s));
}
nums.push(Zero::zero());
nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s)));
for (i, ni) in nums.iter().enumerate() {
for (j0, nj) in nums[i..].iter().enumerate() {
let j = i + j0;
if i == j {
assert_eq!(ni.cmp(nj), Equal);
assert_eq!(nj.cmp(ni), Equal);
assert_eq!(ni, nj);
assert!(!(ni != nj));
assert!(ni <= nj);
assert!(ni >= nj);
assert!(!(ni < nj));
assert!(!(ni > nj));
} else {
assert_eq!(ni.cmp(nj), Less);
assert_eq!(nj.cmp(ni), Greater);
assert!(!(ni == nj));
assert!(ni != nj);
assert!(ni <= nj);
assert!(!(ni >= nj));
assert!(ni < nj);
assert!(!(ni > nj));
assert!(!(nj <= ni));
assert!(nj >= ni);
assert!(!(nj < ni));
assert!(nj > ni);
}
}
}
}
#[test]
fn test_hash() {
use hash;
let a = BigInt::new(NoSign, vec![]);
let b = BigInt::new(NoSign, vec![0]);
let c = BigInt::new(Plus, vec![1]);
let d = BigInt::new(Plus, vec![1, 0, 0, 0, 0, 0]);
let e = BigInt::new(Plus, vec![0, 0, 0, 0, 0, 1]);
let f = BigInt::new(Minus, vec![1]);
assert!(hash(&a) == hash(&b));
assert!(hash(&b) != hash(&c));
assert!(hash(&c) == hash(&d));
assert!(hash(&d) != hash(&e));
assert!(hash(&c) != hash(&f));
}
#[test]
fn test_convert_i64() {
fn check(b1: BigInt, i: i64) {
let b2: BigInt = FromPrimitive::from_i64(i).unwrap();
assert!(b1 == b2);
assert!(b1.to_i64().unwrap() == i);
}
check(Zero::zero(), 0);
check(One::one(), 1);
check(i64::MIN.to_bigint().unwrap(), i64::MIN);
check(i64::MAX.to_bigint().unwrap(), i64::MAX);
assert_eq!((i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(), None);
assert_eq!(BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i64(),
None);
assert_eq!(BigInt::from_biguint(Minus,
BigUint::new(vec![1, 0, 0, 1 << (big_digit::BITS - 1)]))
.to_i64(),
None);
assert_eq!(BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i64(),
None);
}
#[test]
fn test_convert_u64() {
fn check(b1: BigInt, u: u64) {
let b2: BigInt = FromPrimitive::from_u64(u).unwrap();
assert!(b1 == b2);
assert!(b1.to_u64().unwrap() == u);
}
check(Zero::zero(), 0);
check(One::one(), 1);
check(u64::MIN.to_bigint().unwrap(), u64::MIN);
check(u64::MAX.to_bigint().unwrap(), u64::MAX);
assert_eq!(BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u64(),
None);
let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap();
assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None);
assert_eq!(BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u64(),
None);
}
#[test]
fn test_convert_f32() {
fn check(b1: &BigInt, f: f32) {
let b2 = BigInt::from_f32(f).unwrap();
assert_eq!(b1, &b2);
assert_eq!(b1.to_f32().unwrap(), f);
let neg_b1 = -b1;
let neg_b2 = BigInt::from_f32(-f).unwrap();
assert_eq!(neg_b1, neg_b2);
assert_eq!(neg_b1.to_f32().unwrap(), -f);
}
check(&BigInt::zero(), 0.0);
check(&BigInt::one(), 1.0);
check(&BigInt::from(u16::MAX), 2.0.powi(16) - 1.0);
check(&BigInt::from(1u64 << 32), 2.0.powi(32));
check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64));
check(&((BigInt::one() << 100) + (BigInt::one() << 123)),
2.0.powi(100) + 2.0.powi(123));
check(&(BigInt::one() << 127), 2.0.powi(127));
check(&(BigInt::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX);
// keeping all 24 digits with the bits at different offsets to the BigDigits
let x: u32 = 0b00000000101111011111011011011101;
let mut f = x as f32;
let mut b = BigInt::from(x);
for _ in 0..64 {
check(&b, f);
f *= 2.0;
b = b << 1;
}
// this number when rounded to f64 then f32 isn't the same as when rounded straight to f32
let mut n: i64 = 0b0000000000111111111111111111111111011111111111111111111111111111;
assert!((n as f64) as f32 != n as f32);
assert_eq!(BigInt::from(n).to_f32(), Some(n as f32));
n = -n;
assert!((n as f64) as f32 != n as f32);
assert_eq!(BigInt::from(n).to_f32(), Some(n as f32));
// test rounding up with the bits at different offsets to the BigDigits
let mut f = ((1u64 << 25) - 1) as f32;
let mut b = BigInt::from(1u64 << 25);
for _ in 0..64 {
assert_eq!(b.to_f32(), Some(f));
f *= 2.0;
b = b << 1;
}
// rounding
assert_eq!(BigInt::from_f32(-f32::consts::PI),
Some(BigInt::from(-3i32)));
assert_eq!(BigInt::from_f32(-f32::consts::E), Some(BigInt::from(-2i32)));
assert_eq!(BigInt::from_f32(-0.99999), Some(BigInt::zero()));
assert_eq!(BigInt::from_f32(-0.5), Some(BigInt::zero()));
assert_eq!(BigInt::from_f32(-0.0), Some(BigInt::zero()));
assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE / 2.0),
Some(BigInt::zero()));
assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE), Some(BigInt::zero()));
assert_eq!(BigInt::from_f32(0.5), Some(BigInt::zero()));
assert_eq!(BigInt::from_f32(0.99999), Some(BigInt::zero()));
assert_eq!(BigInt::from_f32(f32::consts::E), Some(BigInt::from(2u32)));
assert_eq!(BigInt::from_f32(f32::consts::PI), Some(BigInt::from(3u32)));
// special float values
assert_eq!(BigInt::from_f32(f32::NAN), None);
assert_eq!(BigInt::from_f32(f32::INFINITY), None);
assert_eq!(BigInt::from_f32(f32::NEG_INFINITY), None);
// largest BigInt that will round to a finite f32 value
let big_num = (BigInt::one() << 128) - BigInt::one() - (BigInt::one() << (128 - 25));
assert_eq!(big_num.to_f32(), Some(f32::MAX));
assert_eq!((&big_num + BigInt::one()).to_f32(), None);
assert_eq!((-&big_num).to_f32(), Some(f32::MIN));
assert_eq!(((-&big_num) - BigInt::one()).to_f32(), None);
assert_eq!(((BigInt::one() << 128) - BigInt::one()).to_f32(), None);
assert_eq!((BigInt::one() << 128).to_f32(), None);
assert_eq!((-((BigInt::one() << 128) - BigInt::one())).to_f32(), None);
assert_eq!((-(BigInt::one() << 128)).to_f32(), None);
}
#[test]
fn test_convert_f64() {
fn check(b1: &BigInt, f: f64) {
let b2 = BigInt::from_f64(f).unwrap();
assert_eq!(b1, &b2);
assert_eq!(b1.to_f64().unwrap(), f);
let neg_b1 = -b1;
let neg_b2 = BigInt::from_f64(-f).unwrap();
assert_eq!(neg_b1, neg_b2);
assert_eq!(neg_b1.to_f64().unwrap(), -f);
}
check(&BigInt::zero(), 0.0);
check(&BigInt::one(), 1.0);
check(&BigInt::from(u32::MAX), 2.0.powi(32) - 1.0);
check(&BigInt::from(1u64 << 32), 2.0.powi(32));
check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64));
check(&((BigInt::one() << 100) + (BigInt::one() << 152)),
2.0.powi(100) + 2.0.powi(152));
check(&(BigInt::one() << 1023), 2.0.powi(1023));
check(&(BigInt::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX);
// keeping all 53 digits with the bits at different offsets to the BigDigits
let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101;
let mut f = x as f64;
let mut b = BigInt::from(x);
for _ in 0..128 {
check(&b, f);
f *= 2.0;
b = b << 1;
}
// test rounding up with the bits at different offsets to the BigDigits
let mut f = ((1u64 << 54) - 1) as f64;
let mut b = BigInt::from(1u64 << 54);
for _ in 0..128 {
assert_eq!(b.to_f64(), Some(f));
f *= 2.0;
b = b << 1;
}
// rounding
assert_eq!(BigInt::from_f64(-f64::consts::PI),
Some(BigInt::from(-3i32)));
assert_eq!(BigInt::from_f64(-f64::consts::E), Some(BigInt::from(-2i32)));
assert_eq!(BigInt::from_f64(-0.99999), Some(BigInt::zero()));
assert_eq!(BigInt::from_f64(-0.5), Some(BigInt::zero()));
assert_eq!(BigInt::from_f64(-0.0), Some(BigInt::zero()));
assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE / 2.0),
Some(BigInt::zero()));
assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE), Some(BigInt::zero()));
assert_eq!(BigInt::from_f64(0.5), Some(BigInt::zero()));
assert_eq!(BigInt::from_f64(0.99999), Some(BigInt::zero()));
assert_eq!(BigInt::from_f64(f64::consts::E), Some(BigInt::from(2u32)));
assert_eq!(BigInt::from_f64(f64::consts::PI), Some(BigInt::from(3u32)));
// special float values
assert_eq!(BigInt::from_f64(f64::NAN), None);
assert_eq!(BigInt::from_f64(f64::INFINITY), None);
assert_eq!(BigInt::from_f64(f64::NEG_INFINITY), None);
// largest BigInt that will round to a finite f64 value
let big_num = (BigInt::one() << 1024) - BigInt::one() - (BigInt::one() << (1024 - 54));
assert_eq!(big_num.to_f64(), Some(f64::MAX));
assert_eq!((&big_num + BigInt::one()).to_f64(), None);
assert_eq!((-&big_num).to_f64(), Some(f64::MIN));
assert_eq!(((-&big_num) - BigInt::one()).to_f64(), None);
assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None);
assert_eq!((BigInt::one() << 1024).to_f64(), None);
assert_eq!((-((BigInt::one() << 1024) - BigInt::one())).to_f64(), None);
assert_eq!((-(BigInt::one() << 1024)).to_f64(), None);
}
#[test]
fn test_convert_to_biguint() {
fn check(n: BigInt, ans_1: BigUint) {
assert_eq!(n.to_biguint().unwrap(), ans_1);
assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n);
}
let zero: BigInt = Zero::zero();
let unsigned_zero: BigUint = Zero::zero();
let positive = BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3]));
let negative = -&positive;
check(zero, unsigned_zero);
check(positive, BigUint::new(vec![1, 2, 3]));
assert_eq!(negative.to_biguint(), None);
}
#[test]
fn test_convert_from_uint() {
macro_rules! check {
($ty:ident, $max:expr) => {
assert_eq!(BigInt::from($ty::zero()), BigInt::zero());
assert_eq!(BigInt::from($ty::one()), BigInt::one());
assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one());
assert_eq!(BigInt::from($ty::MAX), $max);
}
}
check!(u8, BigInt::from_slice(Plus, &[u8::MAX as BigDigit]));
check!(u16, BigInt::from_slice(Plus, &[u16::MAX as BigDigit]));
check!(u32, BigInt::from_slice(Plus, &[u32::MAX as BigDigit]));
check!(u64,
BigInt::from_slice(Plus, &[u32::MAX as BigDigit, u32::MAX as BigDigit]));
check!(usize, BigInt::from(usize::MAX as u64));
}
#[test]
fn test_convert_from_int() {
macro_rules! check {
($ty:ident, $min:expr, $max:expr) => {
assert_eq!(BigInt::from($ty::MIN), $min);
assert_eq!(BigInt::from($ty::MIN + $ty::one()), $min + BigInt::one());
assert_eq!(BigInt::from(-$ty::one()), -BigInt::one());
assert_eq!(BigInt::from($ty::zero()), BigInt::zero());
assert_eq!(BigInt::from($ty::one()), BigInt::one());
assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one());
assert_eq!(BigInt::from($ty::MAX), $max);
}
}
check!(i8,
BigInt::from_slice(Minus, &[1 << 7]),
BigInt::from_slice(Plus, &[i8::MAX as BigDigit]));
check!(i16,
BigInt::from_slice(Minus, &[1 << 15]),
BigInt::from_slice(Plus, &[i16::MAX as BigDigit]));
check!(i32,
BigInt::from_slice(Minus, &[1 << 31]),
BigInt::from_slice(Plus, &[i32::MAX as BigDigit]));
check!(i64,
BigInt::from_slice(Minus, &[0, 1 << 31]),
BigInt::from_slice(Plus, &[u32::MAX as BigDigit, i32::MAX as BigDigit]));
check!(isize,
BigInt::from(isize::MIN as i64),
BigInt::from(isize::MAX as i64));
}
#[test]
fn test_convert_from_biguint() {
assert_eq!(BigInt::from(BigUint::zero()), BigInt::zero());
assert_eq!(BigInt::from(BigUint::one()), BigInt::one());
assert_eq!(BigInt::from(BigUint::from_slice(&[1, 2, 3])),
BigInt::from_slice(Plus, &[1, 2, 3]));
}
const N1: BigDigit = -1i32 as BigDigit;
const N2: BigDigit = -2i32 as BigDigit;
const SUM_TRIPLES: &'static [(&'static [BigDigit],
&'static [BigDigit],
&'static [BigDigit])] = &[(&[], &[], &[]),
(&[], &[1], &[1]),
(&[1], &[1], &[2]),
(&[1], &[1, 1], &[2, 1]),
(&[1], &[N1], &[0, 1]),
(&[1], &[N1, N1], &[0, 0, 1]),
(&[N1, N1], &[N1, N1], &[N2, N1, 1]),
(&[1, 1, 1], &[N1, N1], &[0, 1, 2]),
(&[2, 2, 1], &[N1, N2], &[1, 1, 2])];
#[test]
fn test_add() {
for elm in SUM_TRIPLES.iter() {
let (a_vec, b_vec, c_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
let (na, nb, nc) = (-&a, -&b, -&c);
assert_op!(a + b == c);
assert_op!(b + a == c);
assert_op!(c + na == b);
assert_op!(c + nb == a);
assert_op!(a + nc == nb);
assert_op!(b + nc == na);
assert_op!(na + nb == nc);
assert_op!(a + na == Zero::zero());
}
}
#[test]
fn test_sub() {
for elm in SUM_TRIPLES.iter() {
let (a_vec, b_vec, c_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
let (na, nb, nc) = (-&a, -&b, -&c);
assert_op!(c - a == b);
assert_op!(c - b == a);
assert_op!(nb - a == nc);
assert_op!(na - b == nc);
assert_op!(b - na == c);
assert_op!(a - nb == c);
assert_op!(nc - na == nb);
assert_op!(a - a == Zero::zero());
}
}
const M: u32 = ::std::u32::MAX;
static MUL_TRIPLES: &'static [(&'static [BigDigit],
&'static [BigDigit],
&'static [BigDigit])] = &[(&[], &[], &[]),
(&[], &[1], &[]),
(&[2], &[], &[]),
(&[1], &[1], &[1]),
(&[2], &[3], &[6]),
(&[1], &[1, 1, 1], &[1, 1, 1]),
(&[1, 2, 3], &[3], &[3, 6, 9]),
(&[1, 1, 1], &[N1], &[N1, N1, N1]),
(&[1, 2, 3], &[N1], &[N1, N2, N2, 2]),
(&[1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]),
(&[N1], &[N1], &[1, N2]),
(&[N1, N1], &[N1], &[1, N1, N2]),
(&[N1, N1, N1], &[N1], &[1, N1, N1, N2]),
(&[N1, N1, N1, N1], &[N1], &[1, N1, N1, N1, N2]),
(&[M / 2 + 1], &[2], &[0, 1]),
(&[0, M / 2 + 1], &[2], &[0, 0, 1]),
(&[1, 2], &[1, 2, 3], &[1, 4, 7, 6]),
(&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]),
(&[N1, N1, N1],
&[N1, N1, N1, N1],
&[1, 0, 0, N1, N2, N1, N1]),
(&[0, 0, 1], &[1, 2, 3], &[0, 0, 1, 2, 3]),
(&[0, 0, 1], &[0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])];
static DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit],
&'static [BigDigit],
&'static [BigDigit],
&'static [BigDigit])] = &[(&[1], &[2], &[], &[1]),
(&[1, 1], &[2], &[M / 2 + 1], &[1]),
(&[1, 1, 1], &[2], &[M / 2 + 1, M / 2 + 1], &[1]),
(&[0, 1], &[N1], &[1], &[1]),
(&[N1, N1], &[N2], &[2, 1], &[3])];
#[test]
fn test_mul() {
for elm in MUL_TRIPLES.iter() {
let (a_vec, b_vec, c_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
let (na, nb, nc) = (-&a, -&b, -&c);
assert_op!(a * b == c);
assert_op!(b * a == c);
assert_op!(na * nb == c);
assert_op!(na * b == nc);
assert_op!(nb * a == nc);
}
for elm in DIV_REM_QUADRUPLES.iter() {
let (a_vec, b_vec, c_vec, d_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
let d = BigInt::from_slice(Plus, d_vec);
assert!(a == &b * &c + &d);
assert!(a == &c * &b + &d);
}
}
#[test]
fn test_div_mod_floor() {
fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) {
let (d, m) = a.div_mod_floor(b);
if !m.is_zero() {
assert_eq!(m.sign, b.sign);
}
assert!(m.abs() <= b.abs());
assert!(*a == b * &d + &m);
assert!(d == *ans_d);
assert!(m == *ans_m);
}
fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) {
if m.is_zero() {
check_sub(a, b, d, m);
check_sub(a, &b.neg(), &d.neg(), m);
check_sub(&a.neg(), b, &d.neg(), m);
check_sub(&a.neg(), &b.neg(), d, m);
} else {
let one: BigInt = One::one();
check_sub(a, b, d, m);
check_sub(a, &b.neg(), &(d.neg() - &one), &(m - b));
check_sub(&a.neg(), b, &(d.neg() - &one), &(b - m));
check_sub(&a.neg(), &b.neg(), d, &m.neg());
}
}
for elm in MUL_TRIPLES.iter() {
let (a_vec, b_vec, c_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
if !a.is_zero() {
check(&c, &a, &b, &Zero::zero());
}
if !b.is_zero() {
check(&c, &b, &a, &Zero::zero());
}
}
for elm in DIV_REM_QUADRUPLES.iter() {
let (a_vec, b_vec, c_vec, d_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
let d = BigInt::from_slice(Plus, d_vec);
if !b.is_zero() {
check(&a, &b, &c, &d);
}
}
}
#[test]
fn test_div_rem() {
fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) {
let (q, r) = a.div_rem(b);
if !r.is_zero() {
assert_eq!(r.sign, a.sign);
}
assert!(r.abs() <= b.abs());
assert!(*a == b * &q + &r);
assert!(q == *ans_q);
assert!(r == *ans_r);
let (a, b, ans_q, ans_r) = (a.clone(), b.clone(), ans_q.clone(), ans_r.clone());
assert_op!(a / b == ans_q);
assert_op!(a % b == ans_r);
}
fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) {
check_sub(a, b, q, r);
check_sub(a, &b.neg(), &q.neg(), r);
check_sub(&a.neg(), b, &q.neg(), &r.neg());
check_sub(&a.neg(), &b.neg(), q, &r.neg());
}
for elm in MUL_TRIPLES.iter() {
let (a_vec, b_vec, c_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
if !a.is_zero() {
check(&c, &a, &b, &Zero::zero());
}
if !b.is_zero() {
check(&c, &b, &a, &Zero::zero());
}
}
for elm in DIV_REM_QUADRUPLES.iter() {
let (a_vec, b_vec, c_vec, d_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
let d = BigInt::from_slice(Plus, d_vec);
if !b.is_zero() {
check(&a, &b, &c, &d);
}
}
}
#[test]
fn test_checked_add() {
for elm in SUM_TRIPLES.iter() {
let (a_vec, b_vec, c_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
assert!(a.checked_add(&b).unwrap() == c);
assert!(b.checked_add(&a).unwrap() == c);
assert!(c.checked_add(&(-&a)).unwrap() == b);
assert!(c.checked_add(&(-&b)).unwrap() == a);
assert!(a.checked_add(&(-&c)).unwrap() == (-&b));
assert!(b.checked_add(&(-&c)).unwrap() == (-&a));
assert!((-&a).checked_add(&(-&b)).unwrap() == (-&c));
assert!(a.checked_add(&(-&a)).unwrap() == Zero::zero());
}
}
#[test]
fn test_checked_sub() {
for elm in SUM_TRIPLES.iter() {
let (a_vec, b_vec, c_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
assert!(c.checked_sub(&a).unwrap() == b);
assert!(c.checked_sub(&b).unwrap() == a);
assert!((-&b).checked_sub(&a).unwrap() == (-&c));
assert!((-&a).checked_sub(&b).unwrap() == (-&c));
assert!(b.checked_sub(&(-&a)).unwrap() == c);
assert!(a.checked_sub(&(-&b)).unwrap() == c);
assert!((-&c).checked_sub(&(-&a)).unwrap() == (-&b));
assert!(a.checked_sub(&a).unwrap() == Zero::zero());
}
}
#[test]
fn test_checked_mul() {
for elm in MUL_TRIPLES.iter() {
let (a_vec, b_vec, c_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
assert!(a.checked_mul(&b).unwrap() == c);
assert!(b.checked_mul(&a).unwrap() == c);
assert!((-&a).checked_mul(&b).unwrap() == -&c);
assert!((-&b).checked_mul(&a).unwrap() == -&c);
}
for elm in DIV_REM_QUADRUPLES.iter() {
let (a_vec, b_vec, c_vec, d_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
let d = BigInt::from_slice(Plus, d_vec);
assert!(a == b.checked_mul(&c).unwrap() + &d);
assert!(a == c.checked_mul(&b).unwrap() + &d);
}
}
#[test]
fn test_checked_div() {
for elm in MUL_TRIPLES.iter() {
let (a_vec, b_vec, c_vec) = *elm;
let a = BigInt::from_slice(Plus, a_vec);
let b = BigInt::from_slice(Plus, b_vec);
let c = BigInt::from_slice(Plus, c_vec);
if !a.is_zero() {
assert!(c.checked_div(&a).unwrap() == b);
assert!((-&c).checked_div(&(-&a)).unwrap() == b);
assert!((-&c).checked_div(&a).unwrap() == -&b);
}
if !b.is_zero() {
assert!(c.checked_div(&b).unwrap() == a);
assert!((-&c).checked_div(&(-&b)).unwrap() == a);
assert!((-&c).checked_div(&b).unwrap() == -&a);
}
assert!(c.checked_div(&Zero::zero()).is_none());
assert!((-&c).checked_div(&Zero::zero()).is_none());
}
}
#[test]
fn test_gcd() {
fn check(a: isize, b: isize, c: isize) {
let big_a: BigInt = FromPrimitive::from_isize(a).unwrap();
let big_b: BigInt = FromPrimitive::from_isize(b).unwrap();
let big_c: BigInt = FromPrimitive::from_isize(c).unwrap();
assert_eq!(big_a.gcd(&big_b), big_c);
}
check(10, 2, 2);
check(10, 3, 1);
check(0, 3, 3);
check(3, 3, 3);
check(56, 42, 14);
check(3, -3, 3);
check(-6, 3, 3);
check(-4, -2, 2);
}
#[test]
fn test_lcm() {
fn check(a: isize, b: isize, c: isize) {
let big_a: BigInt = FromPrimitive::from_isize(a).unwrap();
let big_b: BigInt = FromPrimitive::from_isize(b).unwrap();
let big_c: BigInt = FromPrimitive::from_isize(c).unwrap();
assert_eq!(big_a.lcm(&big_b), big_c);
}
check(1, 0, 0);
check(0, 1, 0);
check(1, 1, 1);
check(-1, 1, 1);
check(1, -1, 1);
check(-1, -1, 1);
check(8, 9, 72);
check(11, 5, 55);
}
#[test]
fn test_abs_sub() {
let zero: BigInt = Zero::zero();
let one: BigInt = One::one();
assert_eq!((-&one).abs_sub(&one), zero);
let one: BigInt = One::one();
let zero: BigInt = Zero::zero();
assert_eq!(one.abs_sub(&one), zero);
let one: BigInt = One::one();
let zero: BigInt = Zero::zero();
assert_eq!(one.abs_sub(&zero), one);
let one: BigInt = One::one();
let two: BigInt = FromPrimitive::from_isize(2).unwrap();
assert_eq!(one.abs_sub(&-&one), two);
}
#[test]
fn test_from_str_radix() {
fn check(s: &str, ans: Option<isize>) {
let ans = ans.map(|n| {
let x: BigInt = FromPrimitive::from_isize(n).unwrap();
x
});
assert_eq!(BigInt::from_str_radix(s, 10).ok(), ans);
}
check("10", Some(10));
check("1", Some(1));
check("0", Some(0));
check("-1", Some(-1));
check("-10", Some(-10));
check("+10", Some(10));
check("--7", None);
check("++5", None);
check("+-9", None);
check("-+3", None);
check("Z", None);
check("_", None);
// issue 10522, this hit an edge case that caused it to
// attempt to allocate a vector of size (-1u) == huge.
let x: BigInt = format!("1{}", repeat("0").take(36).collect::<String>()).parse().unwrap();
let _y = x.to_string();
}
#[test]
fn test_lower_hex() {
let a = BigInt::parse_bytes(b"A", 16).unwrap();
let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap();
assert_eq!(format!("{:x}", a), "a");
assert_eq!(format!("{:x}", hello), "-48656c6c6f20776f726c6421");
assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa");
}
#[test]
fn test_upper_hex() {
let a = BigInt::parse_bytes(b"A", 16).unwrap();
let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap();
assert_eq!(format!("{:X}", a), "A");
assert_eq!(format!("{:X}", hello), "-48656C6C6F20776F726C6421");
assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA");
}
#[test]
fn test_binary() {
let a = BigInt::parse_bytes(b"A", 16).unwrap();
let hello = BigInt::parse_bytes("-224055342307539".as_bytes(), 10).unwrap();
assert_eq!(format!("{:b}", a), "1010");
assert_eq!(format!("{:b}", hello),
"-110010111100011011110011000101101001100011010011");
assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010");
}
#[test]
fn test_octal() {
let a = BigInt::parse_bytes(b"A", 16).unwrap();
let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap();
assert_eq!(format!("{:o}", a), "12");
assert_eq!(format!("{:o}", hello), "-22062554330674403566756233062041");
assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12");
}
#[test]
fn test_display() {
let a = BigInt::parse_bytes(b"A", 16).unwrap();
let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap();
assert_eq!(format!("{}", a), "10");
assert_eq!(format!("{}", hello), "-22405534230753963835153736737");
assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10");
}
#[test]
fn test_neg() {
assert!(-BigInt::new(Plus, vec![1, 1, 1]) == BigInt::new(Minus, vec![1, 1, 1]));
assert!(-BigInt::new(Minus, vec![1, 1, 1]) == BigInt::new(Plus, vec![1, 1, 1]));
let zero: BigInt = Zero::zero();
assert_eq!(-&zero, zero);
}
#[test]
fn test_rand() {
let mut rng = thread_rng();
let _n: BigInt = rng.gen_bigint(137);
assert!(rng.gen_bigint(0).is_zero());
}
#[test]
fn test_rand_range() {
let mut rng = thread_rng();
for _ in 0..10 {
assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_usize(236).unwrap(),
&FromPrimitive::from_usize(237).unwrap()),
FromPrimitive::from_usize(236).unwrap());
}
fn check(l: BigInt, u: BigInt) {
let mut rng = thread_rng();
for _ in 0..1000 {
let n: BigInt = rng.gen_bigint_range(&l, &u);
assert!(n >= l);
assert!(n < u);
}
}
let l: BigInt = FromPrimitive::from_usize(403469000 + 2352).unwrap();
let u: BigInt = FromPrimitive::from_usize(403469000 + 3513).unwrap();
check(l.clone(), u.clone());
check(-l.clone(), u.clone());
check(-u.clone(), -l.clone());
}
#[test]
#[should_panic]
fn test_zero_rand_range() {
thread_rng().gen_bigint_range(&FromPrimitive::from_isize(54).unwrap(),
&FromPrimitive::from_isize(54).unwrap());
}
#[test]
#[should_panic]
fn test_negative_rand_range() {
let mut rng = thread_rng();
let l = FromPrimitive::from_usize(2352).unwrap();
let u = FromPrimitive::from_usize(3513).unwrap();
// Switching u and l should fail:
let _n: BigInt = rng.gen_bigint_range(&u, &l);
}

1236
bigint/src/tests/biguint.rs Normal file

File diff suppressed because it is too large Load Diff