Open
Description
Feature gate: #![feature(nonzero_ops)]
This is the tracking issue for #82703. The common arithmetic operators that keep the invariants of NonZero*
types enforced are implemented for these types.
Public API
Example with U8
/I8
, but same for U16
/I16
etc.
// core::num
impl NonZeroU8 {
pub const fn checked_add(self, other: u8) -> Option<Self>;
pub const fn saturating_add(self, other: u8) -> Self;
pub const unsafe fn unchecked_add(self, other: u8) -> Self;
pub const fn checked_next_power_of_two(self) -> Option<Self>;
}
impl NonZeroI8 {
pub const fn abs(self) -> Self;
pub const fn checked_abs(self) -> Option<Self>;
pub const fn overflowing_abs(self) -> (Self, bool);
pub const fn saturating_abs(self) -> Self;
pub const fn wrapping_abs(self) -> Self;
pub const fn unsigned_abs(self) -> NonZeroU8;
}
impl NonZeroU8 /* and NonZeroI8 */ {
pub const fn checked_mul(self, other: Self) -> Option<Self>;
pub const fn saturating_mul(self, other: Self) -> Self;
pub const unsafe fn unchecked_mul(self, other: Self) -> Self;
pub const fn checked_pow(self, other: u32) -> Option<Self>;
pub const fn saturating_pow(self, other: u32) -> Self;
}
/* Not yet on nightly, as it is insta-stable:
impl Neg for NonZeroI8 {
type Output = Self;
fn neg(self) -> Self;
}
*/
Steps / History
- Implementation: Implement nonzero arithmetics for NonZero types. #82703
- Merge Mark unsafe methods NonZero*::unchecked_(add|mul) as const. #87910 marking unsafe methods as
const
. - Final commenting period (FCP)
- Stabilize checked methods in Partial stabilization of "nonzero_checked_ops". #97547.
- Stabilize
unchecked_
methods. - Add
impl Neg for NonZeroI*
, which could not be feature-gated.
Unresolved Questions
- Should
unchecked_add
andunchecked_mul
be markedconst
and how? Would it imply that theirconst
-ness for the underlying types be upgraded instd
?
-> Leave as-is (non-const) until add const-ub RFC rfcs#3016 lands. (Implement nonzero arithmetics for NonZero types. #82703 (comment))
-> It has landed now, mark themconst
in Mark unsafe methods NonZero*::unchecked_(add|mul) as const. #87910. - Naming: how to avoid confusion regarding the term
(un)checked
, referring to checking for nonzeroness in std with theNonZeroInt::new_unchecked
method, but here referring to checking overflow? Discussion here.
->check
consistently means "check everything that needs be checked in the current context, and refer to the doc to verify what needs to be checked in this context". The doc has been made explicit about what needs to be checked for every method above.