From 4d13c28206813c11ec9148aa46779aa3dbd01ef3 Mon Sep 17 00:00:00 2001 From: Markus Reiter Date: Sat, 20 Jan 2024 18:02:56 +0100 Subject: [PATCH] Switch `NonZero` alias direction. --- library/core/src/num/nonzero.rs | 45 +++++++++++++++++++++++---------- 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index 703080757d518..bfbb0b07bfee7 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -3,7 +3,7 @@ use crate::cmp::Ordering; use crate::fmt; use crate::hash::{Hash, Hasher}; -use crate::marker::StructuralPartialEq; +use crate::marker::{StructuralEq, StructuralPartialEq}; use crate::ops::{BitOr, BitOrAssign, Div, Neg, Rem}; use crate::str::FromStr; @@ -67,12 +67,23 @@ impl_zeroable_primitive!(NonZeroI64(i64)); impl_zeroable_primitive!(NonZeroI128(i128)); impl_zeroable_primitive!(NonZeroIsize(isize)); -#[unstable( - feature = "nonzero_internals", - reason = "implementation detail which may disappear or be replaced at any time", - issue = "none" -)] -pub(crate) type NonZero = ::NonZero; +/// A value that is known not to equal zero. +/// +/// This enables some memory layout optimization. +/// For example, `Option>` is the same size as `u32`: +/// +/// ```rust +/// #![feature(generic_nonzero)] +/// +/// use core::mem::size_of; +/// assert_eq!(size_of::>>(), size_of::()); +/// ``` +#[unstable(feature = "generic_nonzero", issue = "82363")] +#[repr(transparent)] +#[rustc_layout_scalar_valid_range_start(1)] +#[rustc_nonnull_optimization_guaranteed] +#[rustc_diagnostic_item = "NonZero"] +pub struct NonZero(T); macro_rules! impl_nonzero_traits { (#[$stability:meta] $Ty:ty) => { @@ -80,11 +91,16 @@ macro_rules! impl_nonzero_traits { impl Clone for $Ty { #[inline] fn clone(&self) -> Self { + let value = self.0; + // SAFETY: The contained value is non-zero. - unsafe { Self(self.0) } + unsafe { Self(value) } } } + #[$stability] + impl Copy for $Ty {} + #[$stability] impl PartialEq for $Ty { #[inline] @@ -101,6 +117,12 @@ macro_rules! impl_nonzero_traits { #[unstable(feature = "structural_match", issue = "31434")] impl StructuralPartialEq for $Ty {} + #[$stability] + impl Eq for $Ty {} + + #[unstable(feature = "structural_match", issue = "31434")] + impl StructuralEq for $Ty {} + #[$stability] impl PartialOrd for $Ty { #[inline] @@ -225,12 +247,7 @@ macro_rules! nonzero_integer { /// /// [null pointer optimization]: crate::option#representation #[$stability] - #[derive(Copy, Eq)] - #[repr(transparent)] - #[rustc_layout_scalar_valid_range_start(1)] - #[rustc_nonnull_optimization_guaranteed] - #[rustc_diagnostic_item = stringify!($Ty)] - pub struct $Ty($Int); + pub type $Ty = NonZero<$Int>; impl_nonzero_traits!(#[$stability] $Ty);