Merge pull request #171 from yuankunzhang/check-overflows

fix: check overflows during date time composition
This commit is contained in:
Daniel Hofstetter
2025-06-28 16:18:41 +02:00
committed by GitHub
2 changed files with 10 additions and 8 deletions
+3 -3
View File
@@ -356,7 +356,7 @@ fn at_date_inner(date: Vec<Item>, at: DateTime<FixedOffset>) -> Option<DateTime<
let delta = (day.num_days_from_monday() as i32
- d.weekday().num_days_from_monday() as i32)
.rem_euclid(7)
+ x * 7;
+ x.checked_mul(7)?;
d = if delta < 0 {
d.checked_sub_days(chrono::Days::new((-delta) as u64))?
@@ -394,11 +394,11 @@ fn at_date_inner(date: Vec<Item>, at: DateTime<FixedOffset>) -> Option<DateTime<
relative::Relative::Days(x) => d += chrono::Duration::days(x.into()),
relative::Relative::Hours(x) => d += chrono::Duration::hours(x.into()),
relative::Relative::Minutes(x) => {
d += chrono::Duration::minutes(x.into());
d += chrono::Duration::try_minutes(x.into())?;
}
// Seconds are special because they can be given as a float
relative::Relative::Seconds(x) => {
d += chrono::Duration::seconds(x as i64);
d += chrono::Duration::try_seconds(x as i64)?;
}
}
}
+7 -5
View File
@@ -54,13 +54,15 @@ pub enum Relative {
}
impl Relative {
// TODO: determine how to handle multiplication overflows,
// using saturating_mul for now.
fn mul(self, n: i32) -> Self {
match self {
Self::Years(x) => Self::Years(n * x),
Self::Months(x) => Self::Months(n * x),
Self::Days(x) => Self::Days(n * x),
Self::Hours(x) => Self::Hours(n * x),
Self::Minutes(x) => Self::Minutes(n * x),
Self::Years(x) => Self::Years(n.saturating_mul(x)),
Self::Months(x) => Self::Months(n.saturating_mul(x)),
Self::Days(x) => Self::Days(n.saturating_mul(x)),
Self::Hours(x) => Self::Hours(n.saturating_mul(x)),
Self::Minutes(x) => Self::Minutes(n.saturating_mul(x)),
Self::Seconds(x) => Self::Seconds(f64::from(n) * x),
}
}