Skip to content

Commit acf673e

Browse files
committed
replace From implementation of SwapInterval that could panic with TryFrom
1 parent dba66e8 commit acf673e

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
@@ -592,20 +592,34 @@ pub enum SwapInterval {
592592
LateSwapTearing = -1,
593593
}
594594

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

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

0 commit comments

Comments
 (0)