diff --git a/units/src/block.rs b/units/src/block.rs index c94c9a3ab..dcb483f1c 100644 --- a/units/src/block.rs +++ b/units/src/block.rs @@ -89,6 +89,18 @@ impl_u32_wrapper! { pub struct BlockHeight(pub u32); } +impl BlockHeight { + /// Attempt to subtract two [`BlockHeight`]s, returning `None` in case of overflow. + pub fn checked_sub(self, other: Self) -> Option { + self.0.checked_sub(other.0).map(BlockHeightInterval) + } + + /// Attempt to add an interval to this [`BlockHeight`], returning `None` in case of overflow. + pub fn checked_add(self, other: BlockHeightInterval) -> Option { + self.0.checked_add(other.0).map(Self) + } +} + impl From for BlockHeight { /// Converts a [`locktime::absolute::Height`] to a [`BlockHeight`]. /// @@ -122,6 +134,14 @@ impl_u32_wrapper! { pub struct BlockHeightInterval(pub u32); } +impl BlockHeightInterval { + /// Attempt to subtract two [`BlockHeightInterval`]s, returning `None` in case of overflow. + pub fn checked_sub(self, other: Self) -> Option { self.0.checked_sub(other.0).map(Self) } + + /// Attempt to add two [`BlockHeightInterval`]s, returning `None` in case of overflow. + pub fn checked_add(self, other: Self) -> Option { self.0.checked_add(other.0).map(Self) } +} + impl From for BlockHeightInterval { /// Converts a [`locktime::relative::HeightInterval`] to a [`BlockHeightInterval`]. /// @@ -170,6 +190,16 @@ impl BlockMtp { timestamps.sort_unstable(); Self::from_u32(u32::from(timestamps[5])) } + + /// Attempt to subtract two [`BlockMtp`]s, returning `None` in case of overflow. + pub fn checked_sub(self, other: Self) -> Option { + self.0.checked_sub(other.0).map(BlockMtpInterval) + } + + /// Attempt to add an interval to this [`BlockMtp`], returning `None` in case of overflow. + pub fn checked_add(self, other: BlockMtpInterval) -> Option { + self.0.checked_add(other.0).map(Self) + } } impl From for BlockMtp { @@ -235,6 +265,12 @@ impl BlockMtpInterval { ) -> Result { relative::MtpInterval::from_seconds_ceil(self.to_u32()) } + + /// Attempt to subtract two [`BlockMtpInterval`]s, returning `None` in case of overflow. + pub fn checked_sub(self, other: Self) -> Option { self.0.checked_sub(other.0).map(Self) } + + /// Attempt to add two [`BlockMtpInterval`]s, returning `None` in case of overflow. + pub fn checked_add(self, other: Self) -> Option { self.0.checked_add(other.0).map(Self) } } impl From for BlockMtpInterval {