@@ -285,6 +285,57 @@ nonzero_integers_div! {
285
285
NonZeroUsize ( usize ) ;
286
286
}
287
287
288
+ // A bunch of methods for unsigned nonzero types only.
289
+ macro_rules! nonzero_unsigned_operations {
290
+ ( $( $Ty: ident( $Int: ty) ; ) + ) => {
291
+ $(
292
+ impl $Ty {
293
+ /// Add an unsigned integer to a non-zero value.
294
+ /// Return [`None`] on overflow.
295
+ ///
296
+ /// # Examples
297
+ ///
298
+ /// ```
299
+ /// #![feature(nonzero_ops)]
300
+ /// # #![feature(try_trait)]
301
+ #[ doc = concat!( "# use std::num::" , stringify!( $Ty) , ";" ) ]
302
+ ///
303
+ /// # fn main() -> Result<(), std::option::NoneError> {
304
+ #[ doc = concat!( "let one = " , stringify!( $Ty) , "::new(1)?;" ) ]
305
+ #[ doc = concat!( "let two = " , stringify!( $Ty) , "::new(2)?;" ) ]
306
+ #[ doc = concat!( "let max = " , stringify!( $Ty) , "::new(" ,
307
+ stringify!( $Int) , "::MAX)?;" ) ]
308
+ ///
309
+ /// assert_eq!(Some(two), one.checked_add(1));
310
+ /// assert_eq!(None, max.checked_add(1));
311
+ /// # Ok(())
312
+ /// # }
313
+ /// ```
314
+ #[ unstable( feature = "nonzero_ops" , issue = "84186" ) ]
315
+ #[ inline]
316
+ pub const fn checked_add( self , other: $Int) -> Option <$Ty> {
317
+ if let Some ( result) = self . get( ) . checked_add( other) {
318
+ // SAFETY: $Int::checked_add returns None on overflow
319
+ // so the result cannot be zero.
320
+ Some ( unsafe { $Ty:: new_unchecked( result) } )
321
+ } else {
322
+ None
323
+ }
324
+ }
325
+ }
326
+ ) +
327
+ }
328
+ }
329
+
330
+ nonzero_unsigned_operations ! {
331
+ NonZeroU8 ( u8 ) ;
332
+ NonZeroU16 ( u16 ) ;
333
+ NonZeroU32 ( u32 ) ;
334
+ NonZeroU64 ( u64 ) ;
335
+ NonZeroU128 ( u128 ) ;
336
+ NonZeroUsize ( usize ) ;
337
+ }
338
+
288
339
macro_rules! nonzero_unsigned_is_power_of_two {
289
340
( $( $Ty: ident ) + ) => {
290
341
$(
0 commit comments