Skip to content

Implement nonzero arithmetics for NonZero types. #82703

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Jun 12, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
NonZero saturating_add.
  • Loading branch information
iago-lito committed Jun 9, 2021
commit a67d6054960e3568fbb6816148a17419e09fe29b
29 changes: 29 additions & 0 deletions library/core/src/num/nonzero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,35 @@ macro_rules! nonzero_unsigned_operations {
None
}
}

/// Add an unsigned integer to a non-zero value.
#[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
///
/// # Examples
///
/// ```
/// #![feature(nonzero_ops)]
/// # #![feature(try_trait)]
#[doc = concat!("# use std::num::", stringify!($Ty), ";")]
///
/// # fn main() -> Result<(), std::option::NoneError> {
#[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
#[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
#[doc = concat!("let max = ", stringify!($Ty), "::new(",
stringify!($Int), "::MAX)?;")]
///
/// assert_eq!(two, one.saturating_add(1));
/// assert_eq!(max, max.saturating_add(1));
/// # Ok(())
/// # }
/// ```
#[unstable(feature = "nonzero_ops", issue = "84186")]
#[inline]
pub const fn saturating_add(self, other: $Int) -> $Ty {
// SAFETY: $Int::saturating_add returns $Int::MAX on overflow
// so the result cannot be zero.
unsafe { $Ty::new_unchecked(self.get().saturating_add(other)) }
}
}
)+
}
Expand Down