Skip to content

Tracking Issue for nonzero_ops #84186

Open
@iago-lito

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

Unresolved Questions

  • Should unchecked_add and unchecked_mul be marked const and how? Would it imply that their const-ness for the underlying types be upgraded in std?
    -> 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 them const 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 the NonZeroInt::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.

Metadata

Assignees

No one assigned

    Labels

    C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions