Skip to content

Commit

Permalink
Add unchecked variants to Amount and SignedAmount
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
yancyribbens committed Feb 3, 2024
1 parent a3c4194 commit a3d1737
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions units/src/amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,22 @@ impl Amount {
/// Returns [None] if overflow occurred.
pub fn checked_rem(self, rhs: u64) -> Option<Amount> { 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<SignedAmount, ParseAmountError> {
if self.to_sat() > SignedAmount::MAX.to_sat() as u64 {
Expand Down Expand Up @@ -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<SignedAmount> {
Expand Down

0 comments on commit a3d1737

Please sign in to comment.