Skip to content

Commit 384b02c

Browse files
committed
Auto merge of #120521 - reitermarkus:generic-nonzero-constructors, r=dtolnay
Make `NonZero` constructors generic. This makes `NonZero` constructors generic, so that `NonZero::new` can be used without turbofish syntax. Tracking issue: #120257 ~~I cannot figure out how to make this work with `const` traits. Not sure if I'm using it wrong or whether there's a bug:~~ ```rust 101 | if n == T::ZERO { | ^^^^^^^^^^^^ expected `host`, found `true` | = note: expected constant `host` found constant `true` ``` r? `@dtolnay`
2 parents 6894f43 + 4229875 commit 384b02c

File tree

3 files changed

+105
-89
lines changed

3 files changed

+105
-89
lines changed

library/core/src/num/nonzero.rs

+99-87
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,16 @@
33
use crate::cmp::Ordering;
44
use crate::fmt;
55
use crate::hash::{Hash, Hasher};
6+
use crate::intrinsics;
67
#[cfg(bootstrap)]
78
use crate::marker::StructuralEq;
89
use crate::marker::StructuralPartialEq;
910
use crate::ops::{BitOr, BitOrAssign, Div, Neg, Rem};
11+
use crate::ptr;
1012
use crate::str::FromStr;
1113

1214
use super::from_str_radix;
1315
use super::{IntErrorKind, ParseIntError};
14-
use crate::intrinsics;
1516

1617
mod private {
1718
#[unstable(
@@ -35,7 +36,7 @@ mod private {
3536
pub trait ZeroablePrimitive: Sized + Copy + private::Sealed {}
3637

3738
macro_rules! impl_zeroable_primitive {
38-
($NonZero:ident ( $primitive:ty )) => {
39+
($primitive:ty) => {
3940
#[unstable(
4041
feature = "nonzero_internals",
4142
reason = "implementation detail which may disappear or be replaced at any time",
@@ -52,18 +53,18 @@ macro_rules! impl_zeroable_primitive {
5253
};
5354
}
5455

55-
impl_zeroable_primitive!(NonZeroU8(u8));
56-
impl_zeroable_primitive!(NonZeroU16(u16));
57-
impl_zeroable_primitive!(NonZeroU32(u32));
58-
impl_zeroable_primitive!(NonZeroU64(u64));
59-
impl_zeroable_primitive!(NonZeroU128(u128));
60-
impl_zeroable_primitive!(NonZeroUsize(usize));
61-
impl_zeroable_primitive!(NonZeroI8(i8));
62-
impl_zeroable_primitive!(NonZeroI16(i16));
63-
impl_zeroable_primitive!(NonZeroI32(i32));
64-
impl_zeroable_primitive!(NonZeroI64(i64));
65-
impl_zeroable_primitive!(NonZeroI128(i128));
66-
impl_zeroable_primitive!(NonZeroIsize(isize));
56+
impl_zeroable_primitive!(u8);
57+
impl_zeroable_primitive!(u16);
58+
impl_zeroable_primitive!(u32);
59+
impl_zeroable_primitive!(u64);
60+
impl_zeroable_primitive!(u128);
61+
impl_zeroable_primitive!(usize);
62+
impl_zeroable_primitive!(i8);
63+
impl_zeroable_primitive!(i16);
64+
impl_zeroable_primitive!(i32);
65+
impl_zeroable_primitive!(i64);
66+
impl_zeroable_primitive!(i128);
67+
impl_zeroable_primitive!(isize);
6768

6869
/// A value that is known not to equal zero.
6970
///
@@ -83,6 +84,88 @@ impl_zeroable_primitive!(NonZeroIsize(isize));
8384
#[rustc_diagnostic_item = "NonZero"]
8485
pub struct NonZero<T: ZeroablePrimitive>(T);
8586

87+
impl<T> NonZero<T>
88+
where
89+
T: ZeroablePrimitive,
90+
{
91+
/// Creates a non-zero if the given value is not zero.
92+
#[stable(feature = "nonzero", since = "1.28.0")]
93+
#[rustc_const_stable(feature = "const_nonzero_int_methods", since = "1.47.0")]
94+
#[rustc_allow_const_fn_unstable(const_refs_to_cell)]
95+
#[must_use]
96+
#[inline]
97+
pub const fn new(n: T) -> Option<Self> {
98+
// SAFETY: Memory layout optimization guarantees that `Option<NonZero<T>>` has
99+
// the same layout and size as `T`, with `0` representing `None`.
100+
unsafe { ptr::read(ptr::addr_of!(n).cast()) }
101+
}
102+
103+
/// Creates a non-zero without checking whether the value is non-zero.
104+
/// This results in undefined behaviour if the value is zero.
105+
///
106+
/// # Safety
107+
///
108+
/// The value must not be zero.
109+
#[stable(feature = "nonzero", since = "1.28.0")]
110+
#[rustc_const_stable(feature = "nonzero", since = "1.28.0")]
111+
#[must_use]
112+
#[inline]
113+
pub const unsafe fn new_unchecked(n: T) -> Self {
114+
match Self::new(n) {
115+
Some(n) => n,
116+
None => {
117+
// SAFETY: The caller guarantees that `n` is non-zero, so this is unreachable.
118+
unsafe {
119+
intrinsics::assert_unsafe_precondition!(
120+
"NonZero::new_unchecked requires the argument to be non-zero",
121+
() => false,
122+
);
123+
intrinsics::unreachable()
124+
}
125+
}
126+
}
127+
}
128+
129+
/// Converts a reference to a non-zero mutable reference
130+
/// if the referenced value is not zero.
131+
#[unstable(feature = "nonzero_from_mut", issue = "106290")]
132+
#[must_use]
133+
#[inline]
134+
pub fn from_mut(n: &mut T) -> Option<&mut Self> {
135+
// SAFETY: Memory layout optimization guarantees that `Option<NonZero<T>>` has
136+
// the same layout and size as `T`, with `0` representing `None`.
137+
let opt_n = unsafe { &mut *(n as *mut T as *mut Option<Self>) };
138+
139+
opt_n.as_mut()
140+
}
141+
142+
/// Converts a mutable reference to a non-zero mutable reference
143+
/// without checking whether the referenced value is non-zero.
144+
/// This results in undefined behavior if the referenced value is zero.
145+
///
146+
/// # Safety
147+
///
148+
/// The referenced value must not be zero.
149+
#[unstable(feature = "nonzero_from_mut", issue = "106290")]
150+
#[must_use]
151+
#[inline]
152+
pub unsafe fn from_mut_unchecked(n: &mut T) -> &mut Self {
153+
match Self::from_mut(n) {
154+
Some(n) => n,
155+
None => {
156+
// SAFETY: The caller guarantees that `n` references a value that is non-zero, so this is unreachable.
157+
unsafe {
158+
intrinsics::assert_unsafe_precondition!(
159+
"NonZero::from_mut_unchecked requires the argument to dereference as non-zero",
160+
() => false,
161+
);
162+
intrinsics::unreachable()
163+
}
164+
}
165+
}
166+
}
167+
}
168+
86169
macro_rules! impl_nonzero_fmt {
87170
( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
88171
$(
@@ -100,7 +183,6 @@ macro_rules! impl_nonzero_fmt {
100183
macro_rules! nonzero_integer {
101184
(
102185
#[$stability:meta]
103-
#[$const_new_unchecked_stability:meta]
104186
Self = $Ty:ident,
105187
Primitive = $signedness:ident $Int:ident,
106188
$(UnsignedNonZero = $UnsignedNonZero:ident,)?
@@ -143,74 +225,6 @@ macro_rules! nonzero_integer {
143225
pub type $Ty = NonZero<$Int>;
144226

145227
impl $Ty {
146-
/// Creates a non-zero without checking whether the value is non-zero.
147-
/// This results in undefined behaviour if the value is zero.
148-
///
149-
/// # Safety
150-
///
151-
/// The value must not be zero.
152-
#[$stability]
153-
#[$const_new_unchecked_stability]
154-
#[must_use]
155-
#[inline]
156-
pub const unsafe fn new_unchecked(n: $Int) -> Self {
157-
crate::panic::debug_assert_nounwind!(
158-
n != 0,
159-
concat!(stringify!($Ty), "::new_unchecked requires a non-zero argument")
160-
);
161-
// SAFETY: this is guaranteed to be safe by the caller.
162-
unsafe {
163-
Self(n)
164-
}
165-
}
166-
167-
/// Creates a non-zero if the given value is not zero.
168-
#[$stability]
169-
#[rustc_const_stable(feature = "const_nonzero_int_methods", since = "1.47.0")]
170-
#[must_use]
171-
#[inline]
172-
pub const fn new(n: $Int) -> Option<Self> {
173-
if n != 0 {
174-
// SAFETY: we just checked that there's no `0`
175-
Some(unsafe { Self(n) })
176-
} else {
177-
None
178-
}
179-
}
180-
181-
/// Converts a primitive mutable reference to a non-zero mutable reference
182-
/// without checking whether the referenced value is non-zero.
183-
/// This results in undefined behavior if `*n` is zero.
184-
///
185-
/// # Safety
186-
/// The referenced value must not be currently zero.
187-
#[unstable(feature = "nonzero_from_mut", issue = "106290")]
188-
#[must_use]
189-
#[inline]
190-
pub unsafe fn from_mut_unchecked(n: &mut $Int) -> &mut Self {
191-
// SAFETY: Self is repr(transparent), and the value is assumed to be non-zero.
192-
unsafe {
193-
let n_alias = &mut *n;
194-
core::intrinsics::assert_unsafe_precondition!(
195-
concat!(stringify!($Ty), "::from_mut_unchecked requires the argument to dereference as non-zero"),
196-
(n_alias: &mut $Int) => *n_alias != 0
197-
);
198-
&mut *(n as *mut $Int as *mut Self)
199-
}
200-
}
201-
202-
/// Converts a primitive mutable reference to a non-zero mutable reference
203-
/// if the referenced integer is not zero.
204-
#[unstable(feature = "nonzero_from_mut", issue = "106290")]
205-
#[must_use]
206-
#[inline]
207-
pub fn from_mut(n: &mut $Int) -> Option<&mut Self> {
208-
// SAFETY: Self is repr(transparent), and the value is non-zero.
209-
// As long as the returned reference is alive,
210-
// the user cannot `*n = 0` directly.
211-
(*n != 0).then(|| unsafe { &mut *(n as *mut $Int as *mut Self) })
212-
}
213-
214228
/// Returns the value as a primitive type.
215229
#[$stability]
216230
#[inline]
@@ -724,7 +738,6 @@ macro_rules! nonzero_integer {
724738
(Self = $Ty:ident, Primitive = unsigned $Int:ident $(,)?) => {
725739
nonzero_integer! {
726740
#[stable(feature = "nonzero", since = "1.28.0")]
727-
#[rustc_const_stable(feature = "nonzero", since = "1.28.0")]
728741
Self = $Ty,
729742
Primitive = unsigned $Int,
730743
UnsignedPrimitive = $Int,
@@ -735,7 +748,6 @@ macro_rules! nonzero_integer {
735748
(Self = $Ty:ident, Primitive = signed $Int:ident, $($rest:tt)*) => {
736749
nonzero_integer! {
737750
#[stable(feature = "signed_nonzero", since = "1.34.0")]
738-
#[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")]
739751
Self = $Ty,
740752
Primitive = signed $Int,
741753
$($rest)*
@@ -757,7 +769,7 @@ macro_rules! nonzero_integer_signedness_dependent_impls {
757769
fn div(self, other: $Ty) -> $Int {
758770
// SAFETY: div by zero is checked because `other` is a nonzero,
759771
// and MIN/-1 is checked because `self` is an unsigned int.
760-
unsafe { crate::intrinsics::unchecked_div(self, other.get()) }
772+
unsafe { intrinsics::unchecked_div(self, other.get()) }
761773
}
762774
}
763775

@@ -770,7 +782,7 @@ macro_rules! nonzero_integer_signedness_dependent_impls {
770782
fn rem(self, other: $Ty) -> $Int {
771783
// SAFETY: rem by zero is checked because `other` is a nonzero,
772784
// and MIN/-1 is checked because `self` is an unsigned int.
773-
unsafe { crate::intrinsics::unchecked_rem(self, other.get()) }
785+
unsafe { intrinsics::unchecked_rem(self, other.get()) }
774786
}
775787
}
776788
};

tests/ui/print_type_sizes/niche-filling.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
// compile-flags: -Z print-type-sizes --crate-type=lib
2-
// ignore-debug debug assertions will print more types
1+
// compile-flags: -Z print-type-sizes --crate-type lib
2+
// ignore-debug: debug assertions will print more types
33
// build-pass
44
// ignore-pass
55
// ^-- needed because `--pass check` does not emit the output needed.

tests/ui/print_type_sizes/niche-filling.stdout

+4
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ print-type-size field `.a`: 4 bytes
7070
print-type-size field `.b`: 4 bytes, offset: 0 bytes, alignment: 4 bytes
7171
print-type-size type: `std::num::NonZero<u32>`: 4 bytes, alignment: 4 bytes
7272
print-type-size field `.0`: 4 bytes
73+
print-type-size type: `std::option::Option<std::num::NonZero<u32>>`: 4 bytes, alignment: 4 bytes
74+
print-type-size variant `Some`: 4 bytes
75+
print-type-size field `.0`: 4 bytes
76+
print-type-size variant `None`: 0 bytes
7377
print-type-size type: `Enum4<(), (), (), MyOption<u8>>`: 2 bytes, alignment: 1 bytes
7478
print-type-size variant `Four`: 2 bytes
7579
print-type-size field `.0`: 2 bytes

0 commit comments

Comments
 (0)