Add correct `BlockHeight` subtraction & remove panics.

In contrast to the implementation of `Sub<BlockHeight> for BlockHeight`
that was removed in version `0.3.0`, a saturating subtraction for block
heights having a return type of `u32` makes sense for `BlockHeight`.
Subtracting one block height from another yields the delta between them.

Other block height addition and subtraction operations have been made
saturating, removing panics and the possibility of overflow.
This commit is contained in:
Kris Nuttycombe 2024-08-27 16:44:00 -06:00
parent a1047adf0b
commit 1b3433e0dd
2 changed files with 19 additions and 5 deletions

View File

@ -7,6 +7,16 @@ and this library adheres to Rust's notion of
## [Unreleased] ## [Unreleased]
### Added
- `impl Sub<BlockHeight> for BlockHeight` unlike the implementation that was
removed in version `0.3.0`, a saturating subtraction for block heights having
a return type of `u32` makes sense for `BlockHeight`. Subtracting one block
height from another yields the delta between them.
### Changed
- Adding a delta to a `BlockHeight` now uses saturating addition.
- Subtracting a delta to a `BlockHeight` now uses saturating subtraction.
## [0.3.0] - 2024-08-26 ## [0.3.0] - 2024-08-26
### Changed ### Changed
- Testnet activation height has been set for `consensus::BranchId::Nu6`. - Testnet activation height has been set for `consensus::BranchId::Nu6`.

View File

@ -103,7 +103,7 @@ impl Add<u32> for BlockHeight {
type Output = Self; type Output = Self;
fn add(self, other: u32) -> Self { fn add(self, other: u32) -> Self {
BlockHeight(self.0 + other) BlockHeight(self.0.saturating_add(other))
} }
} }
@ -111,11 +111,15 @@ impl Sub<u32> for BlockHeight {
type Output = Self; type Output = Self;
fn sub(self, other: u32) -> Self { fn sub(self, other: u32) -> Self {
if other > self.0 { BlockHeight(self.0.saturating_sub(other))
panic!("Subtraction resulted in negative block height."); }
} }
BlockHeight(self.0 - other) impl Sub<BlockHeight> for BlockHeight {
type Output = u32;
fn sub(self, other: BlockHeight) -> u32 {
self.0.saturating_sub(other.0)
} }
} }