Skip to content

Commit 9295603

Browse files
committed
Fix potential panic in edge case
1 parent 44382c3 commit 9295603

File tree

3 files changed

+18
-6
lines changed

3 files changed

+18
-6
lines changed

src/lib.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -216,12 +216,12 @@ macro_rules! cascade {
216216
cascade!(@ordinal $ordinal);
217217
cascade!(@year $year);
218218
#[allow(unused_assignments)]
219-
if $ordinal > crate::util::days_in_year($year) {
219+
if $ordinal > crate::util::days_in_year($year) as i16 {
220+
$ordinal -= crate::util::days_in_year($year) as i16;
220221
$year += 1;
221-
$ordinal = 1;
222-
} else if $ordinal == 0 {
222+
} else if $ordinal < 1 {
223223
$year -= 1;
224-
$ordinal = crate::util::days_in_year($year);
224+
$ordinal += crate::util::days_in_year($year) as i16;
225225
}
226226
};
227227
}

src/offset_date_time.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,8 @@ impl OffsetDateTime {
152152
let mut minute =
153153
self.minute() as i16 - from.minutes_past_hour() as i16 + to.minutes_past_hour() as i16;
154154
let mut hour = self.hour() as i8 - from.whole_hours() + to.whole_hours();
155-
let (mut year, mut ordinal) = self.to_ordinal_date();
155+
let (mut year, ordinal) = self.to_ordinal_date();
156+
let mut ordinal = ordinal as i16;
156157

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

167+
debug_assert!(ordinal > 0);
168+
debug_assert!(ordinal <= crate::util::days_in_year(year) as i16);
169+
166170
(
167171
year,
168-
ordinal,
172+
ordinal as _,
169173
Time::__from_hms_nanos_unchecked(
170174
hour as _,
171175
minute as _,

tests/integration/offset_date_time.rs

+8
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,14 @@ fn to_offset_panic() {
5555
assert_panic!(PrimitiveDateTime::MIN.assume_utc().to_offset(offset!(-1)));
5656
}
5757

58+
#[test]
59+
fn to_offset_invalid_regression() {
60+
assert_eq!(
61+
datetime!(2019-01-01 0:00 +13).to_offset(offset!(-13)),
62+
datetime!(2018-12-30 22:00:00 -13),
63+
);
64+
}
65+
5866
#[test]
5967
fn from_unix_timestamp() {
6068
assert_eq!(

0 commit comments

Comments
 (0)