Skip to content

Commit e69a62c

Browse files
committed
Added assert_unsafe_precondition! check for NonZeroXxx::from_mut_unchecked
1 parent c8bc957 commit e69a62c

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
@@ -78,18 +78,6 @@ macro_rules! nonzero_integers {
7878
}
7979
}
8080

81-
/// Converts a primitive mutable reference to a non-zero mutable reference
82-
/// if the referenced integer is not zero.
83-
#[unstable(feature = "nonzero_from_mut", issue = "none")]
84-
#[must_use]
85-
#[inline]
86-
pub fn from_mut(n: &mut $Int) -> Option<&mut Self> {
87-
// SAFETY: Self is repr(transparent), and the value is non-zero.
88-
// As long as the returned reference is alive,
89-
// the user cannot `*n = 0` directly.
90-
(*n != 0).then(|| unsafe { &mut *(n as *mut $Int as *mut Self) })
91-
}
92-
9381
/// Converts a primitive mutable reference to a non-zero mutable reference
9482
/// without checking whether the referenced value is non-zero.
9583
/// This results in undefined behavior if `*n` is zero.
@@ -101,7 +89,26 @@ macro_rules! nonzero_integers {
10189
#[inline]
10290
pub unsafe fn from_mut_unchecked(n: &mut $Int) -> &mut Self {
10391
// SAFETY: Self is repr(transparent), and the value is assumed to be non-zero.
104-
unsafe { &mut *(n as *mut $Int as *mut Self) }
92+
unsafe {
93+
let n_alias = &mut *n;
94+
core::intrinsics::assert_unsafe_precondition!(
95+
concat!(stringify!($Ty), "::from_mut_unchecked requires the argument to dereference as non-zero"),
96+
(n_alias: &mut $Int) => *n_alias != 0
97+
);
98+
&mut *(n as *mut $Int as *mut Self)
99+
}
100+
}
101+
102+
/// Converts a primitive mutable reference to a non-zero mutable reference
103+
/// if the referenced integer is not zero.
104+
#[unstable(feature = "nonzero_from_mut", issue = "none")]
105+
#[must_use]
106+
#[inline]
107+
pub fn from_mut(n: &mut $Int) -> Option<&mut Self> {
108+
// SAFETY: Self is repr(transparent), and the value is non-zero.
109+
// As long as the returned reference is alive,
110+
// the user cannot `*n = 0` directly.
111+
(*n != 0).then(|| unsafe { &mut *(n as *mut $Int as *mut Self) })
105112
}
106113

107114

0 commit comments

Comments
 (0)