Skip to content

Commit 3acb445

Browse files
SOF3dtolnay
authored andcommitted
Added assert_unsafe_precondition! check for NonZeroXxx::from_mut_unchecked
1 parent 4459be7 commit 3acb445

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

library/core/src/num/nonzero.rs

+20-13
Original file line numberDiff line numberDiff line change
@@ -171,18 +171,6 @@ macro_rules! nonzero_integer {
171171
}
172172
}
173173

174-
/// Converts a primitive mutable reference to a non-zero mutable reference
175-
/// if the referenced integer is not zero.
176-
#[unstable(feature = "nonzero_from_mut", issue = "none")]
177-
#[must_use]
178-
#[inline]
179-
pub fn from_mut(n: &mut $Int) -> Option<&mut Self> {
180-
// SAFETY: Self is repr(transparent), and the value is non-zero.
181-
// As long as the returned reference is alive,
182-
// the user cannot `*n = 0` directly.
183-
(*n != 0).then(|| unsafe { &mut *(n as *mut $Int as *mut Self) })
184-
}
185-
186174
/// Converts a primitive mutable reference to a non-zero mutable reference
187175
/// without checking whether the referenced value is non-zero.
188176
/// This results in undefined behavior if `*n` is zero.
@@ -194,7 +182,26 @@ macro_rules! nonzero_integer {
194182
#[inline]
195183
pub unsafe fn from_mut_unchecked(n: &mut $Int) -> &mut Self {
196184
// SAFETY: Self is repr(transparent), and the value is assumed to be non-zero.
197-
unsafe { &mut *(n as *mut $Int as *mut Self) }
185+
unsafe {
186+
let n_alias = &mut *n;
187+
core::intrinsics::assert_unsafe_precondition!(
188+
concat!(stringify!($Ty), "::from_mut_unchecked requires the argument to dereference as non-zero"),
189+
(n_alias: &mut $Int) => *n_alias != 0
190+
);
191+
&mut *(n as *mut $Int as *mut Self)
192+
}
193+
}
194+
195+
/// Converts a primitive mutable reference to a non-zero mutable reference
196+
/// if the referenced integer is not zero.
197+
#[unstable(feature = "nonzero_from_mut", issue = "none")]
198+
#[must_use]
199+
#[inline]
200+
pub fn from_mut(n: &mut $Int) -> Option<&mut Self> {
201+
// SAFETY: Self is repr(transparent), and the value is non-zero.
202+
// As long as the returned reference is alive,
203+
// the user cannot `*n = 0` directly.
204+
(*n != 0).then(|| unsafe { &mut *(n as *mut $Int as *mut Self) })
198205
}
199206

200207
/// Returns the value as a primitive type.

0 commit comments

Comments
 (0)