From ae77ede1c0d4a8a5473ba7004a4a59ac81bcb82f Mon Sep 17 00:00:00 2001 From: "Timothy J. Warren" Date: Tue, 10 Mar 2020 20:46:51 -0400 Subject: [PATCH] Partially implement subtraction --- src/bigint.rs | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/bigint.rs b/src/bigint.rs index cb87012..6f4a7f6 100644 --- a/src/bigint.rs +++ b/src/bigint.rs @@ -137,7 +137,33 @@ impl Sub for BigInt { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { - todo!() + let mut out = BigInt::new_empty(); + + let u_digits = self.inner.len(); + let v_digits = rhs.inner.len(); + + let digits = if v_digits > u_digits { + v_digits + } else { + u_digits + }; + + let mut borrow = 0usize; + for i in 0..digits { + let a = *self.inner.get(i).unwrap_or(&0usize); + let b = *rhs.inner.get(i).unwrap_or(&0usize); + + if a > b { + out.inner.push(a - b - borrow); + borrow = 0; + } else if a < b { + todo!(); + } else { + todo!(); + } + } + + out } } @@ -335,6 +361,18 @@ mod tests { assert_eq!(sum.inner[1], 1usize); } + #[test] + fn test_sub() { + let a = BigInt::from(core::usize::MAX); + let b = BigInt::from(core::u16::MAX); + + let diff = a - b; + assert_eq!( + diff.inner[0], + core::usize::MAX - core::u16::MAX as usize + ); + } + #[test] fn test_not() { let a = BigInt::from(0u8);