Skip to content

Commit

Permalink
Avoid panicking on out-of-range value
Browse files Browse the repository at this point in the history
  • Loading branch information
jhpratt committed Aug 2, 2023
1 parent cdc85da commit d671910
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
7 changes: 7 additions & 0 deletions tests/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down
15 changes: 13 additions & 2 deletions time/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down

0 comments on commit d671910

Please sign in to comment.