feat: Create relative lock times at compile time

Also mark these methods as const. Because <u32 as From<u16>>::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.
This commit is contained in:
Christian Lewe 2024-09-28 18:26:27 +02:00
parent 53e1fb6b0c
commit de319670ae
1 changed files with 8 additions and 4 deletions

View File

@ -28,12 +28,14 @@ impl Height {
/// Returns the inner `u16` value. /// Returns the inner `u16` value.
#[inline] #[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 /// Returns the `u32` value used to encode this locktime in an nSequence field or
/// argument to `OP_CHECKSEQUENCEVERIFY`. /// argument to `OP_CHECKSEQUENCEVERIFY`.
#[inline] #[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<u16> for Height { impl From<u16> for Height {
@ -106,12 +108,14 @@ impl Time {
/// Returns the inner `u16` value. /// Returns the inner `u16` value.
#[inline] #[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 /// Returns the `u32` value used to encode this locktime in an nSequence field or
/// argument to `OP_CHECKSEQUENCEVERIFY`. /// argument to `OP_CHECKSEQUENCEVERIFY`.
#[inline] #[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); crate::impl_parse_str_from_int_infallible!(Time, u16, from_512_second_intervals);