我知道rust has mixed integer operations,但我找不到一种直接的方法来获得两个无符号整数的有符号差,同时正确处理溢出:
// one or both values may be too large to just cast to isize
let x: usize = (isize::MAX as usize) + 5;
let y: usize = (isize::MAX as usize) + 7;
let d: isize = x.signed_saturating_sub(y); // non-existent method
assert_eq!(d, -2);
我可以try 以强制转换的方式实现它,但我不确定如何正确检测溢出:
trait SignedSub {
type Signed;
fn signed_overflowing_sub(self, rhs: Self) -> (Self::Signed, bool);
fn signed_wrapping_sub(self, rhs: Self) -> Self::Signed;
fn signed_saturating_sub(self, rhs: Self) -> Self::Signed;
fn signed_checked_sub(self, rhs: Self) -> Option<Self::Signed>;
}
impl SignedSub for usize {
type Signed = isize;
fn signed_overflowing_sub(self, rhs: Self) -> (Self::Signed, bool) {
let (abs, neg) = if self < rhs {
(rhs - self, true)
} else {
(self - rhs, false)
};
let abs = abs as isize;
let res = match neg {
true => -abs,
false => abs,
};
(res, todo!("how to tell if it overflowed isize?"))
}
fn signed_wrapping_sub(self, rhs: Self) -> Self::Signed {
self.signed_overflowing_sub(rhs).0
}
fn signed_saturating_sub(self, rhs: Self) -> Self::Signed {
let (r, overflowed) = self.signed_overflowing_sub(rhs);
match overflowed {
true => match self.cmp(&rhs) {
Ordering::Less => isize::MIN,
Ordering::Equal => unreachable!(),
Ordering::Greater => isize::MAX,
},
false => r,
}
}
fn signed_checked_sub(self, rhs: Self) -> Option<Self::Signed> {
let (r, overflowed) = self.signed_overflowing_sub(rhs);
match overflowed {
true => None,
false => Some(r),
}
}
}
#[cfg(test)]
mod test {
use super::SignedSub;
use proptest::prelude::*;
proptest! {
#[test]
fn it_works(a: usize, b: isize) {
// a + b = c
// a + b - a = c - a
// b = c - a
let (c,flag) = a.overflowing_add_signed(b);
let (b2, flag2) = c.signed_overflowing_sub(a);
// the flags should be the same
assert_eq!((b, flag), (b2, flag2));
}
}
}
如上面的测试所示,它在概念上与uX::overflowing_add_signed(iX)
方法相反,并且在相同的情况下会溢出.