From a9ac2b95f485c31e40273dee7f09dcfff8340777 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Tue, 7 May 2013 14:36:32 +1000 Subject: Add abs_sub method to Signed trait --- src/libstd/num/bigint.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'src/libstd') diff --git a/src/libstd/num/bigint.rs b/src/libstd/num/bigint.rs index cd347098e25..a5cf929ed93 100644 --- a/src/libstd/num/bigint.rs +++ b/src/libstd/num/bigint.rs @@ -831,6 +831,11 @@ impl Signed for BigInt { } } + #[inline(always)] + fn abs_sub(&self, other: &BigInt) -> BigInt { + if *self <= *other { Zero::zero() } else { *self - *other } + } + #[inline(always)] fn signum(&self) -> BigInt { match self.sign { @@ -1920,6 +1925,15 @@ mod bigint_tests { check(11, 5, 55); } + #[test] + fn test_abs_sub() { + assert_eq!((-One::one::()).abs_sub(&One::one()), Zero::zero()); + assert_eq!(One::one::().abs_sub(&One::one()), Zero::zero()); + assert_eq!(One::one::().abs_sub(&Zero::zero()), One::one()); + assert_eq!(One::one::().abs_sub(&-One::one::()), + IntConvertible::from_int(2)); + } + #[test] fn test_to_str_radix() { fn check(n: int, ans: &str) { -- cgit 1.4.1-3-g733a5