Infallible `div_ceil` for `NonZero<unsigned>`

I think it would be nice if NonZero<unsigned> implemented div_ceil as it would be panic-free and could never produce a zero:

impl NonZero<u8> { // similarly for u16, u32, u64, u128 & usize
    pub const fn div_ceil(self, other: Self) -> Self;
}

I recently needed this for one of my projects, where I ended up using the following code instead:

use std::num::NonZeroU64;

pub(crate) trait NonZeroUnsignedExt {
    fn div_ceil(self, divisor: Self) -> Self;
}

impl NonZeroUnsignedExt for NonZeroU64 {
    fn div_ceil(self, divisor: Self) -> Self {
        Self::new(self.get().div_ceil(divisor.get())).unwrap()
    }
}

I think it would be weird to just add div_ceil without also adding checked versions of div. The signed NonZero types should probably also have the checked versions of both.

So in conclusion I think the following functions should be added to core:

impl NonZero<u8> { // similarly for u16, u32, u64, u128 & usize
    pub const fn checked_div(self, other: Self) -> Option<Self>;
    pub const fn div_ceil(self, other: Self) -> Self;
}
impl NonZero<i8> { // similarly for i16, i32, i64, i128 & isize
    pub const fn checked_div(self, other: Self) -> Option<Self>;
    pub const fn checked_div_ceil(self, other: Self) -> Option<Self>;
}
3 Likes

I just saw that signed::div_ceil has not been stabilized yet, so NonZero<signed>::checked_div_ceil should not be stabilized before that.

This seems fairly reasonable. Generally, the feature lifecycle recommends you should now create an ACP (API change proposal) to get an initial yea/nea on whether T-libs agrees that the API is desirable.

5 Likes

Posted: Infallible `div_ceil` for `NonZero<unsigned>` · Issue #471 · rust-lang/libs-team · GitHub