Fix FeeRate::checked_add/sub

Currently the `checked_add` and `checked_sub` functions use a `u64` for
the right hand side. This leaks the inner unit because the RHS value is
implicitly in the same unit.

Make the functions have `FeeRate` on the RHS.
This commit is contained in:
Tobin C. Harding 2025-05-21 10:28:59 +10:00
parent 855299ab7e
commit 395252c6d9
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
1 changed files with 15 additions and 10 deletions

View File

@ -110,9 +110,9 @@ impl FeeRate {
/// ///
/// Computes `self + rhs` returning [`None`] if overflow occurred. /// Computes `self + rhs` returning [`None`] if overflow occurred.
#[must_use] #[must_use]
pub const fn checked_add(self, rhs: u64) -> Option<Self> { pub const fn checked_add(self, rhs: FeeRate) -> Option<Self> {
// No `map()` in const context. // No `map()` in const context.
match self.to_sat_per_kwu().checked_add(rhs) { match self.to_sat_per_kwu().checked_add(rhs.to_sat_per_kwu()) {
Some(res) => Some(Self::from_sat_per_kwu(res)), Some(res) => Some(Self::from_sat_per_kwu(res)),
None => None, None => None,
} }
@ -122,9 +122,9 @@ impl FeeRate {
/// ///
/// Computes `self - rhs` returning [`None`] if overflow occurred. /// Computes `self - rhs` returning [`None`] if overflow occurred.
#[must_use] #[must_use]
pub const fn checked_sub(self, rhs: u64) -> Option<Self> { pub const fn checked_sub(self, rhs: FeeRate) -> Option<Self> {
// No `map()` in const context. // No `map()` in const context.
match self.to_sat_per_kwu().checked_sub(rhs) { match self.to_sat_per_kwu().checked_sub(rhs.to_sat_per_kwu()) {
Some(res) => Some(Self::from_sat_per_kwu(res)), Some(res) => Some(Self::from_sat_per_kwu(res)),
None => None, None => None,
} }
@ -260,19 +260,24 @@ mod tests {
#[test] #[test]
fn checked_add() { fn checked_add() {
let f = FeeRate::from_sat_per_kwu(1).checked_add(2).unwrap(); let one = FeeRate::from_sat_per_kwu(1);
assert_eq!(FeeRate::from_sat_per_kwu(3), f); let two = FeeRate::from_sat_per_kwu(2);
let three = FeeRate::from_sat_per_kwu(3);
let f = FeeRate::from_sat_per_kwu(u64::MAX).checked_add(1); assert_eq!(one.checked_add(two).unwrap(), three);
let f = FeeRate::from_sat_per_kwu(u64::MAX).checked_add(one);
assert!(f.is_none()); assert!(f.is_none());
} }
#[test] #[test]
fn checked_sub() { fn checked_sub() {
let f = FeeRate::from_sat_per_kwu(2).checked_sub(1).unwrap(); let one = FeeRate::from_sat_per_kwu(1);
assert_eq!(FeeRate::from_sat_per_kwu(1), f); let two = FeeRate::from_sat_per_kwu(2);
let three = FeeRate::from_sat_per_kwu(3);
assert_eq!(three.checked_sub(two).unwrap(), one);
let f = FeeRate::ZERO.checked_sub(1); let f = FeeRate::ZERO.checked_sub(one);
assert!(f.is_none()); assert!(f.is_none());
} }