5

Add functions to add unsigned and signed integers by a1phyr · Pull Request #8760...

 2 years ago
source link: https://github.com/rust-lang/rust/pull/87601
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Copy link

Contributor

a1phyr commented on Jul 29

edited

This PR adds methods to unsigned integers to add signed integers with good overflow semantics under #![feature(mixed_integer_ops)].

The added API is:

// `uX` is `u8`, `u16`, `u32`, `u64`,`u128`, `usize`
impl uX {
    pub const fn checked_add_signed(self, iX) -> Option<Self>;
    pub const fn overflowing_add_signed(self, iX) -> (Self, bool);
    pub const fn saturating_add_signed(self, iX) -> Self;
    pub const fn wrapping_add_signed(self, iX) -> Self;
}


impl iX {
    pub const fn checked_add_unsigned(self, uX) -> Option<Self>;
    pub const fn overflowing_add_unsigned(self, uX) -> (Self, bool);
    pub const fn saturating_add_unsigned(self, uX) -> Self;
    pub const fn wrapping_add_unsigned(self, uX) -> Self;

    pub const fn checked_sub_unsigned(self, uX) -> Option<Self>;
    pub const fn overflowing_sub_unsigned(self, uX) -> (Self, bool);
    pub const fn saturating_sub_unsigned(self, uX) -> Self;
    pub const fn wrapping_sub_unsigned(self, uX) -> Self;
}

Maybe it would be interesting to also have add_signed that panics in debug and wraps in release ?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK