num-integer icon indicating copy to clipboard operation
num-integer copied to clipboard

`NonZero*`?

Open Rudxain opened this issue 1 year ago • 1 comments

This isn't a follow-up to #63, but it's related. I understand that despite NonZero being stable, its trait-bound isn't, so nothing should be done WRT that.

However, if it does get stabilized with that trait-bound, it would be convenient if there was a non-primitive counterpart provided by this crate, such as:

use std::hint::unreachable_unchecked;
use num_integer::Integer; // 0.1

pub struct NonZeroInt<T: Integer>(T);
impl<T: Integer> NonZeroInt<T> {
    #[must_use]
    fn new(n: T) -> Option<Self> {
        if n.is_zero() {
            None
        } else {
            Some(Self(n))
        }
    }
    #[must_use]
    unsafe fn new_unchecked(n: T) -> Self {
        match Self::new(n) {
            Some(n) => n,
            _ => unsafe { unreachable_unchecked() },
        }
    }
    #[must_use]
    fn get(self) -> T {
        self.0
    }
}

// (optional)
use core::ops::Deref;
impl<T: Integer> Deref for NonZeroInt<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

Rudxain avatar Jun 22 '24 06:06 Rudxain