diff --git a/changelog.md b/changelog.md index 6235875112..c36fa9582b 100644 --- a/changelog.md +++ b/changelog.md @@ -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. diff --git a/src/sdl2/rect.rs b/src/sdl2/rect.rs index c0519e6fbc..3f3264ddfd 100644 --- a/src/sdl2/rect.rs +++ b/src/sdl2/rect.rs @@ -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, @@ -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 TryFrom<[T; 4]> for Rect +where + T: TryInto + TryInto, + // need to do this to support Infallible conversions + TryFromIntError: From<>::Error>, + TryFromIntError: From<>::Error>, +{ + type Error = TryFromIntError; + fn try_from([x, y, width, height]: [T; 4]) -> Result { + Ok(Rect::new( + x.try_into()?, + y.try_into()?, + width.try_into()?, + height.try_into()?, + )) + } +} + impl AsRef for Rect { fn as_ref(&self) -> &sys::SDL_Rect { &self.raw