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

Commit a67d605

Browse files
committed
NonZero saturating_add.
1 parent 832c7f5 commit a67d605

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

library/core/src/num/nonzero.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,35 @@ macro_rules! nonzero_unsigned_operations {
322322
None
323323
}
324324
}
325+
326+
/// Add an unsigned integer to a non-zero value.
327+
#[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
328+
///
329+
/// # Examples
330+
///
331+
/// ```
332+
/// #![feature(nonzero_ops)]
333+
/// # #![feature(try_trait)]
334+
#[doc = concat!("# use std::num::", stringify!($Ty), ";")]
335+
///
336+
/// # fn main() -> Result<(), std::option::NoneError> {
337+
#[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
338+
#[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
339+
#[doc = concat!("let max = ", stringify!($Ty), "::new(",
340+
stringify!($Int), "::MAX)?;")]
341+
///
342+
/// assert_eq!(two, one.saturating_add(1));
343+
/// assert_eq!(max, max.saturating_add(1));
344+
/// # Ok(())
345+
/// # }
346+
/// ```
347+
#[unstable(feature = "nonzero_ops", issue = "84186")]
348+
#[inline]
349+
pub const fn saturating_add(self, other: $Int) -> $Ty {
350+
// SAFETY: $Int::saturating_add returns $Int::MAX on overflow
351+
// so the result cannot be zero.
352+
unsafe { $Ty::new_unchecked(self.get().saturating_add(other)) }
353+
}
325354
}
326355
)+
327356
}

0 commit comments

Comments
 (0)