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

Support converting arrays of integers to Rect via TryFrom #1403

Open
wants to merge 3 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.

### Unreleased

[PR #1403](https://github.com/Rust-SDL2/rust-sdl2/pull/1403) Support converting arrays of integers to Rect via TryFrom.

[PR #1368](https://github.com/Rust-SDL2/rust-sdl2/pull/1368) Remove unnecessary unsafe in Window interface. Make Window `Clone`.

[PR #1366](https://github.com/Rust-SDL2/rust-sdl2/pull/1366) Add Primary Selection bindings.
Expand Down
31 changes: 30 additions & 1 deletion src/sdl2/rect.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
//! Rectangles and points.

use crate::sys;
use std::convert::{AsMut, AsRef};
use std::convert::{AsMut, AsRef, TryFrom, TryInto};
use std::hash::{Hash, Hasher};
use std::mem;
use std::num::TryFromIntError;
use std::ops::{
Add, AddAssign, BitAnd, BitOr, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Neg, Sub,
SubAssign,
Expand Down Expand Up @@ -698,6 +699,34 @@ impl From<(i32, i32, u32, u32)> for Rect {
}
}

/// Try to convert an array of numbers to a rectangle
///
/// Example:
/// ```rust
/// use sdl2::rect::Rect;
/// let rect1: Rect = [5_u8; 4].into().unwrap();
/// let rect2: Rect = [5_u64; 4].into().unwrap();
///
/// assert_eq!(rect1, rect2);
/// ```
impl<T> TryFrom<[T; 4]> for Rect
where
T: TryInto<u32> + TryInto<i32>,
// need to do this to support Infallible conversions
TryFromIntError: From<<T as TryInto<i32>>::Error>,
TryFromIntError: From<<T as TryInto<u32>>::Error>,
{
type Error = TryFromIntError;
fn try_from([x, y, width, height]: [T; 4]) -> Result<Self, TryFromIntError> {
Ok(Rect::new(
x.try_into()?,
y.try_into()?,
width.try_into()?,
height.try_into()?,
))
}
}

impl AsRef<sys::SDL_Rect> for Rect {
fn as_ref(&self) -> &sys::SDL_Rect {
&self.raw
Expand Down