Skip to content

Commit

Permalink
Switch NonZero alias direction.
Browse files Browse the repository at this point in the history
  • Loading branch information
reitermarkus committed Jan 20, 2024
1 parent 086d887 commit 4d13c28
Showing 1 changed file with 31 additions and 14 deletions.
45 changes: 31 additions & 14 deletions library/core/src/num/nonzero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -67,24 +67,40 @@ 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<T> = <T as ZeroablePrimitive>::NonZero;
/// A value that is known not to equal zero.
///
/// This enables some memory layout optimization.
/// For example, `Option<NonZero<u32>>` is the same size as `u32`:
///
/// ```rust
/// #![feature(generic_nonzero)]
///
/// use core::mem::size_of;
/// assert_eq!(size_of::<Option<core::num::NonZero<u32>>>(), size_of::<u32>());
/// ```
#[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: ZeroablePrimitive>(T);

macro_rules! impl_nonzero_traits {
(#[$stability:meta] $Ty:ty) => {
#[$stability]
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]
Expand All @@ -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]
Expand Down Expand Up @@ -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);

Expand Down

0 comments on commit 4d13c28

Please sign in to comment.