relative locktime: constify a bunch of constructors

This commit is contained in:
Andrew Poelstra 2024-03-18 13:12:15 +00:00
parent f27e675e1e
commit ac968e02b6
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
2 changed files with 20 additions and 10 deletions

View File

@ -70,8 +70,11 @@ impl LockTime {
///
/// Will return an error if the input cannot be encoded in 16 bits.
#[inline]
pub fn from_seconds_floor(seconds: u32) -> Result<Self, TimeOverflowError> {
Time::from_seconds_floor(seconds).map(LockTime::Time)
pub const fn from_seconds_floor(seconds: u32) -> Result<Self, TimeOverflowError> {
match Time::from_seconds_floor(seconds) {
Ok(time) => Ok(LockTime::Time(time)),
Err(e) => Err(e),
}
}
/// Create a [`LockTime`] from seconds, converting the seconds into 512 second interval
@ -81,8 +84,11 @@ impl LockTime {
///
/// Will return an error if the input cannot be encoded in 16 bits.
#[inline]
pub fn from_seconds_ceil(seconds: u32) -> Result<Self, TimeOverflowError> {
Time::from_seconds_ceil(seconds).map(LockTime::Time)
pub const fn from_seconds_ceil(seconds: u32) -> Result<Self, TimeOverflowError> {
match Time::from_seconds_ceil(seconds) {
Ok(time) => Ok(LockTime::Time(time)),
Err(e) => Err(e),
}
}
/// Returns true if this [`relative::LockTime`] is satisfied by either height or time.

View File

@ -72,9 +72,11 @@ impl Time {
///
/// Will return an error if the input cannot be encoded in 16 bits.
#[inline]
pub fn from_seconds_floor(seconds: u32) -> Result<Self, TimeOverflowError> {
if let Ok(interval) = u16::try_from(seconds / 512) {
Ok(Time::from_512_second_intervals(interval))
#[rustfmt::skip] // moves comments to unrelated code
pub const fn from_seconds_floor(seconds: u32) -> Result<Self, TimeOverflowError> {
let interval = seconds / 512;
if interval <= u16::MAX as u32 { // infallible cast, needed by const code
Ok(Time::from_512_second_intervals(interval as u16)) // cast checked above, needed by const code
} else {
Err(TimeOverflowError { seconds })
}
@ -87,9 +89,11 @@ impl Time {
///
/// Will return an error if the input cannot be encoded in 16 bits.
#[inline]
pub fn from_seconds_ceil(seconds: u32) -> Result<Self, TimeOverflowError> {
if let Ok(interval) = u16::try_from((seconds + 511) / 512) {
Ok(Time::from_512_second_intervals(interval))
#[rustfmt::skip] // moves comments to unrelated code
pub const fn from_seconds_ceil(seconds: u32) -> Result<Self, TimeOverflowError> {
let interval = (seconds + 511) / 512;
if interval <= u16::MAX as u32 { // infallible cast, needed by const code
Ok(Time::from_512_second_intervals(interval as u16)) // cast checked above, needed by const code
} else {
Err(TimeOverflowError { seconds })
}