From 2adfea48d52292877d3e9025e486fb1d94dec7cc Mon Sep 17 00:00:00 2001 From: juliohq Date: Sun, 26 Mar 2023 10:48:25 -0300 Subject: [PATCH] Add Rect::*_shifted functions --- src/sdl2/rect.rs | 66 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/src/sdl2/rect.rs b/src/sdl2/rect.rs index efe8e06289..5a3609b218 100644 --- a/src/sdl2/rect.rs +++ b/src/sdl2/rect.rs @@ -150,11 +150,13 @@ impl Rect { } /// The horizontal position of this rectangle. + #[inline] pub fn x(&self) -> i32 { self.raw.x } /// The vertical position of this rectangle. + #[inline] pub fn y(&self) -> i32 { self.raw.y } @@ -224,6 +226,58 @@ impl Rect { self.raw.y + self.raw.h } + /// Shifts this rectangle to the left by `offset`. + /// + /// # Example + /// + /// ``` + /// use sdl2::rect::Rect; + /// assert_eq!(Rect::new(0, 0, 10, 10).left_shifted(5), Rect::new(-5, 0, 10, 10)); + /// ``` + pub fn left_shifted(mut self, offset: i32) -> Rect { + self.offset(-offset, self.y()); + self + } + + /// Shifts this rectangle to the right by `offset`. + /// + /// # Example + /// + /// ``` + /// use sdl2::rect::Rect; + /// assert_eq!(Rect::new(0, 0, 10, 10).right_shifted(5), Rect::new(5, 0, 10, 10)); + /// ``` + pub fn right_shifted(mut self, offset: i32) -> Rect { + self.offset(offset, self.y()); + self + } + + /// Shifts this rectangle to the top by `offset`. + /// + /// # Example + /// + /// ``` + /// use sdl2::rect::Rect; + /// assert_eq!(Rect::new(0, 0, 10, 10).top_shifted(5), Rect::new(0, -5, 10, 10)); + /// ``` + pub fn top_shifted(mut self, offset: i32) -> Rect { + self.offset(self.x(), -offset); + self + } + + /// Shifts this rectangle to the bottom by `offset`. + /// + /// # Example + /// + /// ``` + /// use sdl2::rect::Rect; + /// assert_eq!(Rect::new(0, 0, 10, 10).bottom_shifted(5), Rect::new(0, 5, 10, 10)); + /// ``` + pub fn bottom_shifted(mut self, offset: i32) -> Rect { + self.offset(self.x(), offset); + self + } + /// Returns the center position of this rectangle. /// /// Note that if the width or height is not a multiple of two, @@ -318,6 +372,7 @@ impl Rect { /// Move this rect and clamp the positions to prevent over/underflow. /// This also clamps the size to prevent overflow. + #[inline] pub fn offset(&mut self, x: i32, y: i32) { match self.raw.x.checked_add(x) { Some(val) => self.raw.x = clamp_position(val), @@ -1017,6 +1072,17 @@ mod test { ); } + #[test] + fn shifted() { + // Groups all functions into a single assertion + let rect = Rect::new(0, 0, 10, 10) + .left_shifted(5) + .right_shifted(5) + .top_shifted(5) + .bottom_shifted(5); + assert_eq!(rect, Rect::new(0, 0, 10, 10)); + } + #[test] fn rect_into() { let test: (i32, i32, u32, u32) = (-11, 5, 50, 20);