Skip to content

Commit f1713b0

Browse files
authoredJan 20, 2024
Rollup merge of #103730 - SOF3:nonzero-from-mut, r=Mark-Simulacrum,dtolnay
Added NonZeroXxx::from_mut(_unchecked)? ACP: rust-lang/libs-team#129 Tracking issue: #106290
2 parents 5378c1c + 596410e commit f1713b0

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
 

‎library/core/src/num/nonzero.rs

+33
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,39 @@ macro_rules! nonzero_integer {
171171
}
172172
}
173173

174+
/// Converts a primitive mutable reference to a non-zero mutable reference
175+
/// without checking whether the referenced value is non-zero.
176+
/// This results in undefined behavior if `*n` is zero.
177+
///
178+
/// # Safety
179+
/// The referenced value must not be currently zero.
180+
#[unstable(feature = "nonzero_from_mut", issue = "106290")]
181+
#[must_use]
182+
#[inline]
183+
pub unsafe fn from_mut_unchecked(n: &mut $Int) -> &mut Self {
184+
// SAFETY: Self is repr(transparent), and the value is assumed to be non-zero.
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 = "106290")]
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) })
205+
}
206+
174207
/// Returns the value as a primitive type.
175208
#[$stability]
176209
#[inline]

0 commit comments

Comments
 (0)
Please sign in to comment.