|
1 | 1 | //! Rectangles and points.
|
2 | 2 |
|
3 | 3 | use crate::sys;
|
4 |
| -use std::convert::{AsMut, AsRef}; |
| 4 | +use std::convert::{AsMut, AsRef, TryFrom, TryInto}; |
5 | 5 | use std::hash::{Hash, Hasher};
|
6 | 6 | use std::mem;
|
7 | 7 | use std::ops::{
|
8 | 8 | Add, AddAssign, BitAnd, BitOr, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Neg, Sub,
|
9 | 9 | SubAssign,
|
10 | 10 | };
|
| 11 | +use std::num::TryFromIntError; |
11 | 12 | use std::ptr;
|
12 | 13 |
|
13 | 14 | /// The maximal integer value that can be used for rectangles.
|
@@ -698,6 +699,29 @@ impl From<(i32, i32, u32, u32)> for Rect {
|
698 | 699 | }
|
699 | 700 | }
|
700 | 701 |
|
| 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 | + |
701 | 725 | impl AsRef<sys::SDL_Rect> for Rect {
|
702 | 726 | fn as_ref(&self) -> &sys::SDL_Rect {
|
703 | 727 | &self.raw
|
|
0 commit comments