@@ -171,6 +171,39 @@ macro_rules! nonzero_integer {
171
171
}
172
172
}
173
173
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
+
174
207
/// Returns the value as a primitive type.
175
208
#[ $stability]
176
209
#[ inline]
0 commit comments