Skip to content

Create NonZero trait with primitive associated type #95155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions library/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -422,3 +422,11 @@ pub mod simd {
}

include!("primitive_docs.rs");

mod sealed {
/// This trait being unreachable from outside the crate
/// prevents outside implementations of our extension traits.
/// This allows adding more trait methods in the future.
#[unstable(feature = "sealed", issue = "none")]
pub trait Sealed {}
}
36 changes: 35 additions & 1 deletion library/core/src/num/nonzero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,33 @@ use crate::str::FromStr;

use super::from_str_radix;
use super::{IntErrorKind, ParseIntError};
use crate::intrinsics;
use crate::{intrinsics, sealed::Sealed};

/// A number that is known not to equal zero.
///
/// # Safety
///
/// Implementors of this trait must not have a memory representation for zero.
#[unstable(feature = "nonzero_trait", issue = "95157")]
pub unsafe trait NonZero: Sealed {
/// The primitive scalar type.
///
/// # Examples
///
/// ## Type Aliases
///
/// When referring to an integer type through an alias, this can be used to
/// state its primitive type.
///
/// ```
/// use std::num::{NonZero, NonZeroU32};
///
/// type NonZeroInt = NonZeroU32;
///
/// let n: <NonZeroInt as NonZero>::Scalar = 1;
/// ```
type Scalar;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm open to suggestions for a better name.

}

macro_rules! impl_nonzero_fmt {
( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
Expand Down Expand Up @@ -41,6 +67,14 @@ macro_rules! nonzero_integers {
#[rustc_nonnull_optimization_guaranteed]
pub struct $Ty($Int);

#[unstable(feature = "sealed", issue = "none")]
impl Sealed for $Ty {}

#[unstable(feature = "nonzero_trait", issue = "95157")]
unsafe impl NonZero for $Ty {
type Scalar = $Int;
}

impl $Ty {
/// Creates a non-zero without checking whether the value is non-zero.
/// This results in undefined behaviour if the value is zero.
Expand Down