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>;
}