Skip to content

Commit

Permalink
Fix potential panic in edge case
Browse files Browse the repository at this point in the history
  • Loading branch information
jhpratt committed Oct 3, 2022
1 parent 44382c3 commit 9295603
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
8 changes: 4 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,12 +216,12 @@ macro_rules! cascade {
cascade!(@ordinal $ordinal);
cascade!(@year $year);
#[allow(unused_assignments)]
if $ordinal > crate::util::days_in_year($year) {
if $ordinal > crate::util::days_in_year($year) as i16 {
$ordinal -= crate::util::days_in_year($year) as i16;
$year += 1;
$ordinal = 1;
} else if $ordinal == 0 {
} else if $ordinal < 1 {
$year -= 1;
$ordinal = crate::util::days_in_year($year);
$ordinal += crate::util::days_in_year($year) as i16;
}
};
}
Expand Down
8 changes: 6 additions & 2 deletions src/offset_date_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,8 @@ impl OffsetDateTime {
let mut minute =
self.minute() as i16 - from.minutes_past_hour() as i16 + to.minutes_past_hour() as i16;
let mut hour = self.hour() as i8 - from.whole_hours() + to.whole_hours();
let (mut year, mut ordinal) = self.to_ordinal_date();
let (mut year, ordinal) = self.to_ordinal_date();
let mut ordinal = ordinal as i16;

// Cascade the values twice. This is needed because the values are adjusted twice above.
cascade!(second in 0..60 => minute);
Expand All @@ -163,9 +164,12 @@ impl OffsetDateTime {
cascade!(hour in 0..24 => ordinal);
cascade!(ordinal => year);

debug_assert!(ordinal > 0);
debug_assert!(ordinal <= crate::util::days_in_year(year) as i16);

(
year,
ordinal,
ordinal as _,
Time::__from_hms_nanos_unchecked(
hour as _,
minute as _,
Expand Down
8 changes: 8 additions & 0 deletions tests/integration/offset_date_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@ fn to_offset_panic() {
assert_panic!(PrimitiveDateTime::MIN.assume_utc().to_offset(offset!(-1)));
}

#[test]
fn to_offset_invalid_regression() {
assert_eq!(
datetime!(2019-01-01 0:00 +13).to_offset(offset!(-13)),
datetime!(2018-12-30 22:00:00 -13),
);
}

#[test]
fn from_unix_timestamp() {
assert_eq!(
Expand Down

0 comments on commit 9295603

Please sign in to comment.