Skip to content

Commit 25936a4

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

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
@@ -313,6 +313,24 @@ impl TimeDelta {
313313
if self.secs < 0 && self.nanos > 0 { self.nanos - NANOS_PER_SEC } else { self.nanos }
314314
}
315315

316+
/// Returns the number of microseconds in the fractional part of the duration.
317+
///
318+
/// This is the number of microseconds such that
319+
/// `subsec_micros() + num_seconds() * MICROS_PER_SEC` is the truncated number of
320+
/// microseconds in the duration.
321+
pub const fn subsec_micros(&self) -> i32 {
322+
self.subsec_nanos() / NANOS_PER_MICRO
323+
}
324+
325+
/// Returns the number of milliseconds in the fractional part of the duration.
326+
///
327+
/// This is the number of milliseconds such that
328+
/// `subsec_millis() + num_seconds() * MILLIS_PER_SEC` is the truncated number of
329+
/// milliseconds in the duration.
330+
pub const fn subsec_millis(&self) -> i32 {
331+
self.subsec_nanos() / NANOS_PER_MILLI
332+
}
333+
316334
/// Returns the total number of whole milliseconds in the `TimeDelta`.
317335
pub const fn num_milliseconds(&self) -> i64 {
318336
// A proper TimeDelta will not overflow, because MIN and MAX are defined such
@@ -779,6 +797,26 @@ mod tests {
779797
assert_eq!(TimeDelta::nanoseconds(1_000_000_001).subsec_nanos(), 1);
780798
}
781799

800+
#[test]
801+
fn test_duration_subsec_micros() {
802+
assert_eq!(TimeDelta::zero().subsec_micros(), 0);
803+
assert_eq!(TimeDelta::microseconds(1).subsec_micros(), 1);
804+
assert_eq!(TimeDelta::microseconds(-1).subsec_micros(), -1);
805+
assert_eq!(TimeDelta::seconds(1).subsec_micros(), 0);
806+
assert_eq!(TimeDelta::microseconds(1_000_001).subsec_micros(), 1);
807+
assert_eq!(TimeDelta::nanoseconds(1_000_001_999).subsec_micros(), 1);
808+
}
809+
810+
#[test]
811+
fn test_duration_subsec_millis() {
812+
assert_eq!(TimeDelta::zero().subsec_millis(), 0);
813+
assert_eq!(TimeDelta::milliseconds(1).subsec_millis(), 1);
814+
assert_eq!(TimeDelta::milliseconds(-1).subsec_millis(), -1);
815+
assert_eq!(TimeDelta::seconds(1).subsec_millis(), 0);
816+
assert_eq!(TimeDelta::milliseconds(1_001).subsec_millis(), 1);
817+
assert_eq!(TimeDelta::microseconds(1_001_999).subsec_millis(), 1);
818+
}
819+
782820
#[test]
783821
fn test_duration_num_milliseconds() {
784822
assert_eq!(TimeDelta::zero().num_milliseconds(), 0);

0 commit comments

Comments
 (0)