Skip to content

NonZero*? #66

Open
Open
@Rudxain

Description

@Rudxain

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions