Skip to content

Commit

Permalink
Add subsec_millis and subsec_micros methods for TimeDelta.
Browse files Browse the repository at this point in the history
Co-authored-by: Micha White <[email protected]>
  • Loading branch information
ggoetz and botahamec committed Feb 26, 2025
1 parent 611c90e commit 5aee138
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/time_delta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,24 @@ impl TimeDelta {
if self.secs < 0 && self.nanos > 0 { self.nanos - NANOS_PER_SEC } else { self.nanos }
}

/// Returns the number of microseconds in the fractional part of the duration.
///
/// This is the number of microseconds such that
/// `subsec_micros() + num_seconds() * MICROS_PER_SEC` is the truncated number of
/// microseconds in the duration.
pub const fn subsec_micros(&self) -> i32 {
self.subsec_nanos() / NANOS_PER_MICRO
}

/// Returns the number of milliseconds in the fractional part of the duration.
///
/// This is the number of milliseconds such that
/// `subsec_millis() + num_seconds() * MILLIS_PER_SEC` is the truncated number of
/// milliseconds in the duration.
pub const fn subsec_millis(&self) -> i32 {
self.subsec_nanos() / NANOS_PER_MILLI
}

/// Returns the total number of whole milliseconds in the `TimeDelta`.
pub const fn num_milliseconds(&self) -> i64 {
// A proper TimeDelta will not overflow, because MIN and MAX are defined such
Expand Down Expand Up @@ -765,6 +783,26 @@ mod tests {
assert_eq!(TimeDelta::nanoseconds(1_000_000_001).subsec_nanos(), 1);
}

#[test]
fn test_duration_subsec_micros() {
assert_eq!(TimeDelta::zero().subsec_micros(), 0);
assert_eq!(TimeDelta::microseconds(1).subsec_micros(), 1);
assert_eq!(TimeDelta::microseconds(-1).subsec_micros(), -1);
assert_eq!(TimeDelta::seconds(1).subsec_micros(), 0);
assert_eq!(TimeDelta::microseconds(1_000_001).subsec_micros(), 1);
assert_eq!(TimeDelta::nanoseconds(1_000_001_999).subsec_micros(), 1);
}

#[test]
fn test_duration_subsec_millis() {
assert_eq!(TimeDelta::zero().subsec_millis(), 0);
assert_eq!(TimeDelta::milliseconds(1).subsec_millis(), 1);
assert_eq!(TimeDelta::milliseconds(-1).subsec_millis(), -1);
assert_eq!(TimeDelta::seconds(1).subsec_millis(), 0);
assert_eq!(TimeDelta::milliseconds(1_001).subsec_millis(), 1);
assert_eq!(TimeDelta::microseconds(1_001_999).subsec_millis(), 1);
}

#[test]
fn test_duration_num_milliseconds() {
assert_eq!(TimeDelta::zero().num_milliseconds(), 0);
Expand Down

0 comments on commit 5aee138

Please sign in to comment.