From 47edde1086412b36e9efd6098b191ec15a2a760a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20du=20Garreau?= Date: Mon, 4 Oct 2021 18:52:17 +0200 Subject: [PATCH] Optimize `saturating_add_signed` --- library/core/src/num/uint_macros.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index 5a65f77a87993..96375b82582ed 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -1037,10 +1037,13 @@ macro_rules! uint_impl { without modifying the original"] #[inline] pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self { - if rhs >= 0 { - self.saturating_add(rhs as Self) + let (res, overflow) = self.overflowing_add(rhs as Self); + if overflow == (rhs < 0) { + res + } else if overflow { + Self::MAX } else { - self.saturating_sub(rhs.unsigned_abs()) + 0 } }