From d671910cb2ee118941680c0023ccaf243613a5dd Mon Sep 17 00:00:00 2001 From: Jacob Pratt Date: Wed, 2 Aug 2023 14:08:08 -0400 Subject: [PATCH] Avoid panicking on out-of-range value --- tests/time.rs | 7 +++++++ time/src/lib.rs | 15 +++++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/tests/time.rs b/tests/time.rs index 1a42358e6..5f3f88b68 100644 --- a/tests/time.rs +++ b/tests/time.rs @@ -190,6 +190,13 @@ fn replace_millisecond() -> Result<()> { Ok(()) } +#[test] +fn replace_millisecond_regression() { + assert!(Time::MIDNIGHT.replace_millisecond(9999).is_err()); + assert!(Time::MIDNIGHT.replace_millisecond(4294).is_err()); + assert!(Time::MIDNIGHT.replace_millisecond(4295).is_err()); +} + #[test] fn replace_microsecond() -> Result<()> { assert_eq!( diff --git a/time/src/lib.rs b/time/src/lib.rs index 0359c9d8f..4e9438190 100644 --- a/time/src/lib.rs +++ b/time/src/lib.rs @@ -284,8 +284,19 @@ macro_rules! ensure_ranged { }; ($type:ident : $value:ident $(as $as_type:ident)? * $factor:expr) => { - match $type::new($value $(as $as_type)? * $factor) { - Some(val) => val, + match ($value $(as $as_type)?).checked_mul($factor) { + Some(val) => match $type::new(val) { + Some(val) => val, + None => { + return Err(crate::error::ComponentRange { + name: stringify!($value), + minimum: $type::MIN.get() as i64 / $factor as i64, + maximum: $type::MAX.get() as i64 / $factor as i64, + value: $value as _, + conditional_range: false, + }); + } + }, None => { return Err(crate::error::ComponentRange { name: stringify!($value),