Skip to content

Commit

Permalink
Merge pull request #60 from moia-oss/const-as-unsigned
Browse files Browse the repository at this point in the history
Make `as_millis_unsigned` & `as_seconds_unsigned` const
  • Loading branch information
Felerius authored Apr 24, 2024
2 parents 1d665a0 + 9c9fb14 commit a2112df
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1067,11 +1067,8 @@ impl Duration {
/// Returns the number of non-negative whole milliseconds in the Duration
/// instance.
#[must_use]
pub fn as_millis_unsigned(&self) -> u64 {
#[allow(clippy::cast_sign_loss)]
{
max(self.0, 0) as u64
}
pub const fn as_millis_unsigned(&self) -> u64 {
as_unsigned(self.0)
}

/// Returns the number of whole seconds in the Duration instance.
Expand All @@ -1083,11 +1080,8 @@ impl Duration {
/// Returns the number of non-negative whole seconds in the Duration
/// instance.
#[must_use]
pub fn as_seconds_unsigned(&self) -> u64 {
#[allow(clippy::cast_sign_loss)]
{
max(0, self.0 / 1000) as u64
}
pub const fn as_seconds_unsigned(&self) -> u64 {
as_unsigned(self.0 / 1000)
}

/// Returns the number of whole minutes in the Duration instance.
Expand Down Expand Up @@ -1549,6 +1543,15 @@ impl Display for DurationParseError {
}
}

/// Work-around for `max` in `std` not being const
const fn as_unsigned(x: i64) -> u64 {
if x >= 0 {
x as u64
} else {
0
}
}

const REGEX: &str = r"^(?P<sign>-)?((?P<h>\d+)h)?((?P<m>\d+)m)?((?P<s>\d+)s)?((?P<ms>\d+)ms)?$";

#[cfg(test)]
Expand Down

0 comments on commit a2112df

Please sign in to comment.