Skip to content

Commit 5aee138

Browse files
ggoetzbotahamec
andcommitted
Add subsec_millis and subsec_micros methods for TimeDelta.
Co-authored-by: Micha White <[email protected]>
1 parent 611c90e commit 5aee138

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/time_delta.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,24 @@ impl TimeDelta {
299299
if self.secs < 0 && self.nanos > 0 { self.nanos - NANOS_PER_SEC } else { self.nanos }
300300
}
301301

302+
/// Returns the number of microseconds in the fractional part of the duration.
303+
///
304+
/// This is the number of microseconds such that
305+
/// `subsec_micros() + num_seconds() * MICROS_PER_SEC` is the truncated number of
306+
/// microseconds in the duration.
307+
pub const fn subsec_micros(&self) -> i32 {
308+
self.subsec_nanos() / NANOS_PER_MICRO
309+
}
310+
311+
/// Returns the number of milliseconds in the fractional part of the duration.
312+
///
313+
/// This is the number of milliseconds such that
314+
/// `subsec_millis() + num_seconds() * MILLIS_PER_SEC` is the truncated number of
315+
/// milliseconds in the duration.
316+
pub const fn subsec_millis(&self) -> i32 {
317+
self.subsec_nanos() / NANOS_PER_MILLI
318+
}
319+
302320
/// Returns the total number of whole milliseconds in the `TimeDelta`.
303321
pub const fn num_milliseconds(&self) -> i64 {
304322
// A proper TimeDelta will not overflow, because MIN and MAX are defined such
@@ -765,6 +783,26 @@ mod tests {
765783
assert_eq!(TimeDelta::nanoseconds(1_000_000_001).subsec_nanos(), 1);
766784
}
767785

786+
#[test]
787+
fn test_duration_subsec_micros() {
788+
assert_eq!(TimeDelta::zero().subsec_micros(), 0);
789+
assert_eq!(TimeDelta::microseconds(1).subsec_micros(), 1);
790+
assert_eq!(TimeDelta::microseconds(-1).subsec_micros(), -1);
791+
assert_eq!(TimeDelta::seconds(1).subsec_micros(), 0);
792+
assert_eq!(TimeDelta::microseconds(1_000_001).subsec_micros(), 1);
793+
assert_eq!(TimeDelta::nanoseconds(1_000_001_999).subsec_micros(), 1);
794+
}
795+
796+
#[test]
797+
fn test_duration_subsec_millis() {
798+
assert_eq!(TimeDelta::zero().subsec_millis(), 0);
799+
assert_eq!(TimeDelta::milliseconds(1).subsec_millis(), 1);
800+
assert_eq!(TimeDelta::milliseconds(-1).subsec_millis(), -1);
801+
assert_eq!(TimeDelta::seconds(1).subsec_millis(), 0);
802+
assert_eq!(TimeDelta::milliseconds(1_001).subsec_millis(), 1);
803+
assert_eq!(TimeDelta::microseconds(1_001_999).subsec_millis(), 1);
804+
}
805+
768806
#[test]
769807
fn test_duration_num_milliseconds() {
770808
assert_eq!(TimeDelta::zero().num_milliseconds(), 0);

0 commit comments

Comments
 (0)