I'd like to be able to represent a signed difference of two unsigned integers (correctly handling overflowing, wrapping, checked and saturating variants).
There's quite a few possible operations on mixed-sign integers involving addition and subtraction, and only a few are missing:
Additions:
- uX + uX = uX:
uX::*_add
- uX + uX = iX: seems trivial and not especially useful
- uX + iX = uX:
uX::*_add_signed
- uX + iX = iX:
iX::*_add_unsigned
- iX + uX = uX:
uX::*_add_signed
- iX + uX = iX:
iX::*_add_unsigned
- iX + iX = uX: seems trivial and not especially useful
- iX + iX = iX:
iX:*_add
Subtractions:
- uX - uX = uX:
uX::*_sub
- uX - uX = iX: hard to implement and useful to have
- uX - iX = uX: could be implemented in terms of
uX::*_add_signed
, thoughiX::MIN
would need special handling - uX - iX = iX: could be implemented in terms of
iX::*_add_unsigned
, thoughiX::MIN
would need special handling - iX - uX = uX: seems trivial and not especially useful
- iX - uX = iX:
iX::*_sub_unsigned
- iX - iX = uX: seems trivial and not especially useful
- iX - iX = iX:
iX::*_sub
I propose adding the following family of methods on unsigned integers (names updated based on @quaternic's suggestion):
impl uX {
checked_signed_sub(self, uX) -> Option<iX>
overflowing_signed_sub(self, uX) -> (iX, bool)
saturating_signed_sub(self, uX) -> iX
wrapping_signed_sub(self, uX) -> iX
}
This fills what I see as the one remaining useful and non-trivial mixed-sign addition/subtraction operation on integers.
I made a related crosspost on stackoverflow, with answers covering several possible implementations: rust signed difference of unsigned integers - Stack Overflow
Along similar lines as Representing difference between unsigned integers