Skip to content

Commit 4459be7

Browse files
SOF3dtolnay
authored andcommitted
Added NonZeroXxx::from_mut(_unchecked)?
1 parent 88189a7 commit 4459be7

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

library/core/src/num/nonzero.rs

+26
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,32 @@ 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+
186+
/// Converts a primitive mutable reference to a non-zero mutable reference
187+
/// without checking whether the referenced value is non-zero.
188+
/// This results in undefined behavior if `*n` is zero.
189+
///
190+
/// # Safety
191+
/// The referenced value must not be currently zero.
192+
#[unstable(feature = "nonzero_from_mut", issue = "none")]
193+
#[must_use]
194+
#[inline]
195+
pub unsafe fn from_mut_unchecked(n: &mut $Int) -> &mut Self {
196+
// SAFETY: Self is repr(transparent), and the value is assumed to be non-zero.
197+
unsafe { &mut *(n as *mut $Int as *mut Self) }
198+
}
199+
174200
/// Returns the value as a primitive type.
175201
#[$stability]
176202
#[inline]

0 commit comments

Comments
 (0)