Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace From implementation of SwapInterval that could panic with TryFrom #1413

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ when upgrading from a version of rust-sdl2 to another.

### Next

[PR #1413](https://github.com/Rust-SDL2/rust-sdl2/pull/1413) Deprecate `From` implementation of `SwapInterval` that could panic, add `TryFrom`-like inherent function.

[PR #1416](https://github.com/Rust-SDL2/rust-sdl2/pull/1416) Apply clippy fixes, fix deprecations and other code quality improvements.

[PR #1408](https://github.com/Rust-SDL2/rust-sdl2/pull/1408) Allow comparing `Version`s, add constant with the version the bindings were compiled with.
Expand Down
36 changes: 28 additions & 8 deletions src/sdl2/video.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,17 +592,37 @@ pub enum SwapInterval {
LateSwapTearing = -1,
}

impl From<i32> for SwapInterval {
fn from(i: i32) -> Self {
match i {
impl SwapInterval {
/// This function will be replaced later with a [`TryFrom`] implementation
pub fn try_from(value: i32) -> Result<Self, SwapIntervalConversionError> {
Ok(match value {
-1 => SwapInterval::LateSwapTearing,
0 => SwapInterval::Immediate,
1 => SwapInterval::VSync,
other => panic!(
"Invalid value for SwapInterval: {}; valid values are -1, 0, 1",
other
),
}
_ => return Err(SwapIntervalConversionError(value)),
})
}
}

#[derive(Debug, Clone)]
pub struct SwapIntervalConversionError(pub i32);

impl fmt::Display for SwapIntervalConversionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Invalid value for SwapInterval: {}; valid values are -1, 0, 1",
self.0
)
}
}

impl Error for SwapIntervalConversionError {}

impl From<i32> for SwapInterval {
/// This function is deprecated, use [`SwapInterval::try_from`] instead and handle the error.
fn from(i: i32) -> Self {
Self::try_from(i).unwrap()
}
}

Expand Down
Loading