about summary refs log tree commit diff
diff options
context:
space:
mode:
authorIago-lito <iago-lito@etak>2021-04-15 12:12:46 +0200
committerIago-lito <iago-lito@etak>2021-06-09 17:28:30 +0200
commita67d6054960e3568fbb6816148a17419e09fe29b (patch)
treeee9d12b43a3194969b9bb8370d3cbeda01407bfe
parent832c7f5061b21657db38aa4537fb1864df2cd421 (diff)
downloadrust-a67d6054960e3568fbb6816148a17419e09fe29b.tar.gz
rust-a67d6054960e3568fbb6816148a17419e09fe29b.zip
NonZero saturating_add.
-rw-r--r--library/core/src/num/nonzero.rs29
1 files changed, 29 insertions, 0 deletions
diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs
index e87049450e3..54c67bccdac 100644
--- a/library/core/src/num/nonzero.rs
+++ b/library/core/src/num/nonzero.rs
@@ -322,6 +322,35 @@ macro_rules! nonzero_unsigned_operations {
                         None
                     }
                 }
+
+                /// Add an unsigned integer to a non-zero value.
+                #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
+                ///
+                /// # Examples
+                ///
+                /// ```
+                /// #![feature(nonzero_ops)]
+                /// # #![feature(try_trait)]
+                #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
+                ///
+                /// # fn main() -> Result<(), std::option::NoneError> {
+                #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
+                #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
+                #[doc = concat!("let max = ", stringify!($Ty), "::new(",
+                                stringify!($Int), "::MAX)?;")]
+                ///
+                /// assert_eq!(two, one.saturating_add(1));
+                /// assert_eq!(max, max.saturating_add(1));
+                /// # Ok(())
+                /// # }
+                /// ```
+                #[unstable(feature = "nonzero_ops", issue = "84186")]
+                #[inline]
+                pub const fn saturating_add(self, other: $Int) -> $Ty {
+                    // SAFETY: $Int::saturating_add returns $Int::MAX on overflow
+                    // so the result cannot be zero.
+                    unsafe { $Ty::new_unchecked(self.get().saturating_add(other)) }
+                }
             }
         )+
     }