From 52941252139cc4eadf512b40c4028a6a397e7938 Mon Sep 17 00:00:00 2001 From: Oleksandr <1931331+olksdr@users.noreply.github.com> Date: Fri, 24 Feb 2023 10:52:12 +0100 Subject: [PATCH] fix(sentry-types): Switch to checked version of `from_secs_f64` (#554) This change make use of `try_from_secs_f64` (the checked version of `from_secs_f64`), avoiding panics if the incoming seconds is negative, overflows Duration or not finite. --- sentry-types/src/utils.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/sentry-types/src/utils.rs b/sentry-types/src/utils.rs index 8f3d81e1..aa3cd2a0 100644 --- a/sentry-types/src/utils.rs +++ b/sentry-types/src/utils.rs @@ -13,7 +13,7 @@ pub fn datetime_to_timestamp(st: &SystemTime) -> f64 { } pub fn timestamp_to_datetime(ts: f64) -> Option { - let duration = Duration::from_secs_f64(ts); + let duration = Duration::try_from_secs_f64(ts).ok()?; SystemTime::UNIX_EPOCH.checked_add(duration) } @@ -188,3 +188,16 @@ pub mod ts_rfc3339_opt { } } } + +#[cfg(test)] +mod tests { + use super::timestamp_to_datetime; + + #[test] + fn test_timestamp_to_datetime() { + assert!(timestamp_to_datetime(-10000.0).is_none()); + assert!(timestamp_to_datetime(f64::INFINITY).is_none()); + assert!(timestamp_to_datetime(f64::MAX).is_none()); + assert!(timestamp_to_datetime(123123123.0).is_some()); + } +}