From de319670ae2b0ec1554f5265cdc5978f0d9adcdd Mon Sep 17 00:00:00 2001 From: Christian Lewe Date: Sat, 28 Sep 2024 18:26:27 +0200 Subject: [PATCH] feat: Create relative lock times at compile time Also mark these methods as const. Because >::from is not available in const contexts, I had to cast u16 as u32. I try to avoid casts as much as I can, but in this case a cast seems unavoidable. Casting u16 as u32 should be safe on all architectures. --- units/src/locktime/relative.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/units/src/locktime/relative.rs b/units/src/locktime/relative.rs index bd0b444e2..0fef5b7e5 100644 --- a/units/src/locktime/relative.rs +++ b/units/src/locktime/relative.rs @@ -28,12 +28,14 @@ impl Height { /// Returns the inner `u16` value. #[inline] - pub fn value(self) -> u16 { self.0 } + pub const fn value(self) -> u16 { self.0 } /// Returns the `u32` value used to encode this locktime in an nSequence field or /// argument to `OP_CHECKSEQUENCEVERIFY`. #[inline] - pub fn to_consensus_u32(&self) -> u32 { self.0.into() } + pub const fn to_consensus_u32(&self) -> u32 { + self.0 as u32 // cast safety: u32 is wider than u16 on all architectures + } } impl From for Height { @@ -106,12 +108,14 @@ impl Time { /// Returns the inner `u16` value. #[inline] - pub fn value(self) -> u16 { self.0 } + pub const fn value(self) -> u16 { self.0 } /// Returns the `u32` value used to encode this locktime in an nSequence field or /// argument to `OP_CHECKSEQUENCEVERIFY`. #[inline] - pub fn to_consensus_u32(&self) -> u32 { (1u32 << 22) | u32::from(self.0) } + pub const fn to_consensus_u32(&self) -> u32 { + (1u32 << 22) | self.0 as u32 // cast safety: u32 is wider than u16 on all architectures + } } crate::impl_parse_str_from_int_infallible!(Time, u16, from_512_second_intervals);