Skip to content

Commit 076ef3d

Browse files
committed
replace From implementation of SwapInterval that could panic with TryFrom
1 parent 315c9e2 commit 076ef3d

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

src/sdl2/video.rs

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -591,20 +591,34 @@ pub enum SwapInterval {
591591
LateSwapTearing = -1,
592592
}
593593

594-
impl From<i32> for SwapInterval {
595-
fn from(i: i32) -> Self {
596-
match i {
594+
impl TryFrom<i32> for SwapInterval {
595+
type Error = SwapIntervalConversionError;
596+
597+
fn try_from(value: i32) -> Result<Self, Self::Error> {
598+
Ok(match value {
597599
-1 => SwapInterval::LateSwapTearing,
598600
0 => SwapInterval::Immediate,
599601
1 => SwapInterval::VSync,
600-
other => panic!(
601-
"Invalid value for SwapInterval: {}; valid values are -1, 0, 1",
602-
other
603-
),
604-
}
602+
_ => return Err(SwapIntervalConversionError(value)),
603+
})
604+
}
605+
}
606+
607+
#[derive(Debug, Clone)]
608+
pub struct SwapIntervalConversionError(pub i32);
609+
610+
impl fmt::Display for SwapIntervalConversionError {
611+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
612+
write!(
613+
f,
614+
"Invalid value for SwapInterval: {}; valid values are -1, 0, 1",
615+
self.0
616+
)
605617
}
606618
}
607619

620+
impl Error for SwapIntervalConversionError {}
621+
608622
/// Represents orientation of a display.
609623
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
610624
#[repr(i32)]

0 commit comments

Comments
 (0)