From 784d26bbf8e24dd7ce1b6f7c8e4cd45a496aa11f Mon Sep 17 00:00:00 2001 From: Sam Cappleman-Lynes Date: Wed, 28 Jun 2017 16:59:35 +0100 Subject: [PATCH] Scalar division of a BigUint by a BigDigit A BigUint can be divided by a BigDigit - this is one of several operations being implemented to allow scalar operations on BigInt and BigUint across the board. --- bigint/src/biguint.rs | 24 ++++++++++++++++++++++-- bigint/src/tests/biguint.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/bigint/src/biguint.rs b/bigint/src/biguint.rs index 5d71465..9064490 100644 --- a/bigint/src/biguint.rs +++ b/bigint/src/biguint.rs @@ -479,7 +479,17 @@ impl<'a, 'b> Div<&'b BigUint> for &'a BigUint { #[inline] fn div(self, other: &BigUint) -> BigUint { let (q, _) = self.div_rem(other); - return q; + q + } +} + +impl Div for BigUint { + type Output = BigUint; + + #[inline] + fn div(self, other: BigDigit) -> BigUint { + let (q, _) = div_rem_digit(self, other); + q } } @@ -491,7 +501,17 @@ impl<'a, 'b> Rem<&'b BigUint> for &'a BigUint { #[inline] fn rem(self, other: &BigUint) -> BigUint { let (_, r) = self.div_rem(other); - return r; + r + } +} + +impl Rem for BigUint { + type Output = BigDigit; + + #[inline] + fn rem(self, other: BigDigit) -> BigDigit { + let (_, r) = div_rem_digit(self, other); + r } } diff --git a/bigint/src/tests/biguint.rs b/bigint/src/tests/biguint.rs index f5c226f..1c57d86 100644 --- a/bigint/src/tests/biguint.rs +++ b/bigint/src/tests/biguint.rs @@ -866,6 +866,41 @@ fn test_div_rem() { } } +#[test] +fn test_scalar_div_rem() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let c = BigUint::from_slice(c_vec); + + if a_vec.len() == 1 && a_vec[0] != 0 { + let a = a_vec[0]; + let b = BigUint::from_slice(b_vec); + assert!(c.clone() / a == b); + assert!(c.clone() % a == Zero::zero()); + } + + if b_vec.len() == 1 && b_vec[0] != 0 { + let a = BigUint::from_slice(a_vec); + let b = b_vec[0]; + assert!(c.clone() / b == a); + assert!(c.clone() % b == Zero::zero()); + } + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let c = BigUint::from_slice(c_vec); + + if b_vec.len() == 1 && b_vec[0] != 0 { + let b = b_vec[0]; + let d = d_vec[0]; + assert!(a.clone() / b == c); + assert!(a.clone() % b == d); + } + } +} + #[test] fn test_checked_add() { for elm in SUM_TRIPLES.iter() {