diff --git a/src/cryptonum/signed.rs b/src/cryptonum/signed.rs index 4f05319..1a46c51 100644 --- a/src/cryptonum/signed.rs +++ b/src/cryptonum/signed.rs @@ -12,6 +12,14 @@ pub struct SCN { } impl SCN { + pub fn zero() -> SCN { + SCN{ negative: false, value: UCN::zero() } + } + + pub fn is_zero(&self) -> bool { + self.value.is_zero() + } + pub fn from_str(x: &str) -> SCN { if x.get(0..1) == Some("-") { SCN{ negative: true, value: UCN::from_str(&x[1..]) } @@ -19,6 +27,12 @@ impl SCN { SCN{ negative: false, value: UCN::from_str(x) } } } + + fn cleanup(&mut self) { + if self.value.is_zero() { + self.negative = false; + } + } } impl fmt::UpperHex for SCN { @@ -86,6 +100,7 @@ impl<'a> AddAssign<&'a SCN> for SCN { self.value = &rhs.value - &self.value; } } + self.cleanup(); } } @@ -93,6 +108,7 @@ impl<'a> SubAssign<&'a SCN> for SCN { fn sub_assign(&mut self, rhs: &SCN) { let flipped = SCN{ negative: !rhs.negative, value: rhs.value.clone() }; self.add_assign(&flipped); + self.cleanup(); } } @@ -100,6 +116,7 @@ impl<'a> MulAssign<&'a SCN> for SCN { fn mul_assign(&mut self, rhs: &SCN) { self.negative ^= rhs.negative; self.value.mul_assign(&rhs.value); + self.cleanup(); } } @@ -115,6 +132,7 @@ impl<'a> DivAssign<&'a SCN> for SCN { let one = UCN{ contents: vec![1] }; self.sub_assign(SCN{ negative: false, value: one}); } + self.cleanup(); } } @@ -128,6 +146,7 @@ impl<'a> RemAssign<&'a SCN> for SCN { self.negative = rhs.negative; self.value = &rhs.value - &base; } + self.cleanup(); } } diff --git a/src/cryptonum/unsigned.rs b/src/cryptonum/unsigned.rs index 6e44f12..fe361f3 100644 --- a/src/cryptonum/unsigned.rs +++ b/src/cryptonum/unsigned.rs @@ -11,6 +11,14 @@ pub struct UCN { } impl UCN { + pub fn zero() -> UCN { + UCN{ contents: vec![] } + } + + pub fn is_zero(&self) -> bool { + self.contents.len() == 0 + } + fn clean(&mut self) { loop { match self.contents.pop() {