Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit a3e1c35

Browse files
committed
NonZero unchecked_add.
1 parent a67d605 commit a3e1c35

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

library/core/src/num/nonzero.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,34 @@ macro_rules! nonzero_unsigned_operations {
351351
// so the result cannot be zero.
352352
unsafe { $Ty::new_unchecked(self.get().saturating_add(other)) }
353353
}
354+
355+
/// Add an unsigned integer to a non-zero value,
356+
/// assuming overflow cannot occur.
357+
/// This results in undefined behaviour when
358+
#[doc = concat!("`self + rhs > ", stringify!($Int), "::MAX`")]
359+
#[doc = concat!(" or `self + rhs < ", stringify!($Int), "::MIN`.")]
360+
///
361+
/// # Examples
362+
///
363+
/// ```
364+
/// #![feature(nonzero_ops)]
365+
/// # #![feature(try_trait)]
366+
#[doc = concat!("# use std::num::", stringify!($Ty), ";")]
367+
///
368+
/// # fn main() -> Result<(), std::option::NoneError> {
369+
#[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
370+
#[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
371+
///
372+
/// assert_eq!(two, unsafe { one.unchecked_add(1) });
373+
/// # Ok(())
374+
/// # }
375+
/// ```
376+
#[unstable(feature = "nonzero_ops", issue = "84186")]
377+
#[inline]
378+
pub unsafe fn unchecked_add(self, other: $Int) -> $Ty {
379+
// SAFETY: The caller ensures there is no overflow.
380+
unsafe { $Ty::new_unchecked(self.get().unchecked_add(other)) }
381+
}
354382
}
355383
)+
356384
}

0 commit comments

Comments
 (0)