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 8, 2024
1 parent a3c4194 commit 848bb52
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions units/src/amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,25 @@ 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.
///
/// Panics in debug mode, wraps in release mode.
pub fn unchecked_add(self, rhs: Amount) -> Amount {
Self(self.0 + rhs.0)
}

/// Unchecked subtraction.
///
/// Panics in debug mode, wraps in release mode.
pub fn unchecked_sub(self, rhs: Amount) -> Amount {
Self(self.0 - rhs.0)
}

/// Unchecked multiplication.
///
/// Panics in debug mode, wraps in release mode.
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 +1248,25 @@ impl SignedAmount {
self.0.checked_rem(rhs).map(SignedAmount)
}

/// Unchecked addition.
///
/// Panics in debug mode, wraps in release mode.
pub fn unchecked_add(self, rhs: SignedAmount) -> SignedAmount {
Self(self.0 + rhs.0)
}

/// Unchecked subtraction.
///
/// Panics in debug mode, wraps in release mode.
pub fn unchecked_sub(self, rhs: SignedAmount) -> SignedAmount {
Self(self.0 - rhs.0)
}

/// Unchecked multiplication.
///
/// Panics in debug mode, wraps in release mode.
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 848bb52

Please sign in to comment.