Skip to content

Commit e96aedd

Browse files
committed
fallible offset conversion
1 parent cc7c143 commit e96aedd

File tree

2 files changed

+29
-11
lines changed

2 files changed

+29
-11
lines changed

src/items/mod.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ fn with_timezone_restore(
303303
offset: time::Offset,
304304
at: DateTime<FixedOffset>,
305305
) -> Option<DateTime<FixedOffset>> {
306-
let offset: FixedOffset = chrono::FixedOffset::from(offset);
306+
let offset: FixedOffset = chrono::FixedOffset::try_from(offset).ok()?;
307307
let copy = at;
308308
let x = at
309309
.with_timezone(&offset)
@@ -360,7 +360,9 @@ fn at_date_inner(date: Vec<Item>, mut d: DateTime<FixedOffset>) -> Option<DateTi
360360
},
361361
..
362362
}) => {
363-
let offset = offset.map(chrono::FixedOffset::from).unwrap_or(*d.offset());
363+
let offset = offset
364+
.and_then(|o| chrono::FixedOffset::try_from(o).ok())
365+
.unwrap_or(*d.offset());
364366

365367
d = new_date(
366368
year.map(|x| x as i32).unwrap_or(d.year()),
@@ -379,7 +381,10 @@ fn at_date_inner(date: Vec<Item>, mut d: DateTime<FixedOffset>) -> Option<DateTi
379381
second,
380382
offset,
381383
}) => {
382-
let offset = offset.map(chrono::FixedOffset::from).unwrap_or(*d.offset());
384+
let offset = offset
385+
.and_then(|o| chrono::FixedOffset::try_from(o).ok())
386+
.unwrap_or(*d.offset());
387+
383388
d = new_date(
384389
d.year(),
385390
d.month(),

src/items/time.rs

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ use winnow::{
5050
ModalResult, Parser,
5151
};
5252

53+
use crate::ParseDateTimeError;
54+
5355
use super::{dec_uint, relative, s};
5456

5557
#[derive(PartialEq, Debug, Clone, Default)]
@@ -95,22 +97,33 @@ impl Offset {
9597
}
9698
}
9799

98-
impl From<Offset> for chrono::FixedOffset {
99-
fn from(
100+
impl TryFrom<Offset> for chrono::FixedOffset {
101+
type Error = ParseDateTimeError;
102+
103+
fn try_from(
100104
Offset {
101105
negative,
102106
hours,
103107
minutes,
104108
}: Offset,
105-
) -> Self {
109+
) -> Result<Self, Self::Error> {
106110
let secs = hours * 3600 + minutes * 60;
107111

108-
if negative {
109-
FixedOffset::west_opt(secs.try_into().expect("secs overflow"))
110-
.expect("timezone overflow")
112+
let offset = if negative {
113+
FixedOffset::west_opt(
114+
secs.try_into()
115+
.map_err(|_| ParseDateTimeError::InvalidInput)?,
116+
)
117+
.ok_or(ParseDateTimeError::InvalidInput)?
111118
} else {
112-
FixedOffset::east_opt(secs.try_into().unwrap()).unwrap()
113-
}
119+
FixedOffset::east_opt(
120+
secs.try_into()
121+
.map_err(|_| ParseDateTimeError::InvalidInput)?,
122+
)
123+
.ok_or(ParseDateTimeError::InvalidInput)?
124+
};
125+
126+
Ok(offset)
114127
}
115128
}
116129

0 commit comments

Comments
 (0)