生锈无符号整数的有符号差

问题描述 投票:0回答:1

我知道 rust 具有混合整数运算,但我找不到一种直接的方法来获取两个无符号整数的有符号差,同时正确处理溢出:

// 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);

我可以尝试通过强制转换来实现它,但我不确定如何正确检测溢出:


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);
            // I think the flags should be the same, but I'm not certain...
            assert_eq!((b, flag), (b2, flag2));
        }
    }
}

如上面的测试所示,它在概念上是

uX::overflowing_add_signed(iX)
方法的逆,并且(我认为???)它在相同的情况下会溢出。

rust unsigned signed
1个回答
0
投票

语义很难正确理解,但这是我认为正确的版本:

fn signed_overflowing_sub(self, rhs: Self) -> (Self::Signed, bool) {
    if self < rhs {
        let result = rhs - self;
        if result == 1 << (usize::BITS - 1) /* -isize::MIN */ {
            // `-isize::MIN` will overflow if we convert to it `isize`, so we need to handle it specifically.
            (isize::MIN, false)
        } else {
            (-(result as isize), result > isize::MAX as usize)
        }
    } else {
        let result = self - rhs;
        (result as isize, result > isize::MAX as usize)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.