Skip to content

Commit 0404244

Browse files
committed
Make NonZero::get generic.
1 parent a5042de commit 0404244

File tree

1 file changed

+21
-20
lines changed

1 file changed

+21
-20
lines changed

library/core/src/num/nonzero.rs

+21-20
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,27 @@ where
165165
}
166166
}
167167
}
168+
169+
/// Returns the contained value as a primitive type.
170+
#[stable(feature = "nonzero", since = "1.28.0")]
171+
#[rustc_const_stable(feature = "const_nonzero_get", since = "1.34.0")]
172+
#[inline]
173+
pub const fn get(self) -> T {
174+
// FIXME: This can be changed to simply `self.0` once LLVM supports `!range` metadata
175+
// for function arguments: https://github.com/llvm/llvm-project/issues/76628
176+
//
177+
// Rustc can set range metadata only if it loads `self` from
178+
// memory somewhere. If the value of `self` was from by-value argument
179+
// of some not-inlined function, LLVM don't have range metadata
180+
// to understand that the value cannot be zero.
181+
match Self::new(self.0) {
182+
Some(Self(n)) => n,
183+
None => {
184+
// SAFETY: `NonZero` is guaranteed to only contain non-zero values, so this is unreachable.
185+
unsafe { crate::hint::unreachable_unchecked() }
186+
}
187+
}
188+
}
168189
}
169190

170191
macro_rules! impl_nonzero_fmt {
@@ -226,26 +247,6 @@ macro_rules! nonzero_integer {
226247
pub type $Ty = NonZero<$Int>;
227248

228249
impl $Ty {
229-
/// Returns the value as a primitive type.
230-
#[$stability]
231-
#[inline]
232-
#[rustc_const_stable(feature = "const_nonzero_get", since = "1.34.0")]
233-
pub const fn get(self) -> $Int {
234-
// FIXME: Remove this after LLVM supports `!range` metadata for function
235-
// arguments https://github.com/llvm/llvm-project/issues/76628
236-
//
237-
// Rustc can set range metadata only if it loads `self` from
238-
// memory somewhere. If the value of `self` was from by-value argument
239-
// of some not-inlined function, LLVM don't have range metadata
240-
// to understand that the value cannot be zero.
241-
242-
// SAFETY: It is an invariant of this type.
243-
unsafe {
244-
intrinsics::assume(self.0 != 0);
245-
}
246-
self.0
247-
}
248-
249250
/// The size of this non-zero integer type in bits.
250251
///
251252
#[doc = concat!("This value is equal to [`", stringify!($Int), "::BITS`].")]

0 commit comments

Comments
 (0)