Skip to content

Commit ed95966

Browse files
committed
Support converting arrays of integers to Rect via TryFrom
1 parent 146cff6 commit ed95966

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/sdl2/rect.rs

+25-1
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
//! Rectangles and points.
22
33
use crate::sys;
4-
use std::convert::{AsMut, AsRef};
4+
use std::convert::{AsMut, AsRef, TryFrom, TryInto};
55
use std::hash::{Hash, Hasher};
66
use std::mem;
77
use std::ops::{
88
Add, AddAssign, BitAnd, BitOr, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Neg, Sub,
99
SubAssign,
1010
};
11+
use std::num::TryFromIntError;
1112
use std::ptr;
1213

1314
/// The maximal integer value that can be used for rectangles.
@@ -698,6 +699,29 @@ impl From<(i32, i32, u32, u32)> for Rect {
698699
}
699700
}
700701

702+
/// Try to convert an array of numbers to a rectangle
703+
///
704+
/// Example:
705+
/// ```rust
706+
/// use sdl2::rect::Rect;
707+
/// let rect1: Rect = [5_u8; 4].into().unwrap();
708+
/// let rect2: Rect = [5_u64; 4].into().unwrap();
709+
///
710+
/// assert_eq!(rect1, rect2);
711+
/// ```
712+
impl<T> TryFrom<[T; 4]> for Rect where
713+
T: TryInto<u32> + TryInto<i32>,
714+
// need to do this to support Infallible conversions
715+
TryFromIntError: From<<T as TryInto<i32>>::Error>,
716+
TryFromIntError: From<<T as TryInto<u32>>::Error>,
717+
{
718+
type Error = TryFromIntError;
719+
fn try_from([x, y, width, height]: [T; 4]) -> Result<Self, TryFromIntError> {
720+
Ok(Rect::new(x.try_into()?, y.try_into()?,
721+
width.try_into()?, height.try_into()?))
722+
}
723+
}
724+
701725
impl AsRef<sys::SDL_Rect> for Rect {
702726
fn as_ref(&self) -> &sys::SDL_Rect {
703727
&self.raw

0 commit comments

Comments
 (0)