From a3d1737062280a7f0a638bd9d8d79d99d084380f Mon Sep 17 00:00:00 2001 From: yancy Date: Sat, 3 Feb 2024 12:03:49 +0100 Subject: [PATCH] Add unchecked variants to Amount and SignedAmount The checked variants have worse performance than the unchecked variants due to the additional branching operations. To improve performance where overflow is either not possible or not a concern, unchecked variants of Amount and SignedAmount are introduced. --- units/src/amount.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/units/src/amount.rs b/units/src/amount.rs index 559c956234..bb06c72267 100644 --- a/units/src/amount.rs +++ b/units/src/amount.rs @@ -864,6 +864,22 @@ impl Amount { /// Returns [None] if overflow occurred. pub fn checked_rem(self, rhs: u64) -> Option { self.0.checked_rem(rhs).map(Amount) } + /// Unchecked addition. + /// This is the unsafe variant of addition. Overflow instead of panic. + pub fn unchecked_add(self, rhs: Amount) -> Amount { + Self(self.0 + rhs.0) + } + + /// Unchecked subtraction. + /// This is the unsafe variant of subtraction. Overflow instead of panic. + pub fn unchecked_sub(self, rhs: Amount) -> Amount { + Self(self.0 - rhs.0) + } + + /// Unchecked multiplication. + /// This is the unsafe variant of multiplication. Overflow instead of panic. + pub fn unchecked_mul(self, rhs: Amount) -> Amount { Self(self.0 * rhs.0) } + /// Convert to a signed amount. pub fn to_signed(self) -> Result { if self.to_sat() > SignedAmount::MAX.to_sat() as u64 { @@ -1229,6 +1245,22 @@ impl SignedAmount { self.0.checked_rem(rhs).map(SignedAmount) } + /// Unchecked addition. + /// This is the unsafe variant of addition. Overflow instead of panic. + pub fn unchecked_add(self, rhs: SignedAmount) -> SignedAmount { + Self(self.0 + rhs.0) + } + + /// Unchecked subtraction. + /// This is the unsafe variant of subtraction. Overflow instead of panic. + pub fn unchecked_sub(self, rhs: SignedAmount) -> SignedAmount { + Self(self.0 - rhs.0) + } + + /// Unchecked multiplication. + /// This is the unsafe variant of multiplication. Overflow instead of panic. + pub fn unchecked_mul(self, rhs: SignedAmount) -> SignedAmount { Self(self.0 * rhs.0) } + /// Subtraction that doesn't allow negative [SignedAmount]s. /// Returns [None] if either [self], `rhs` or the result is strictly negative. pub fn positive_sub(self, rhs: SignedAmount) -> Option {