Skip to content

Commit

Permalink
Merge pull request #1294 from juliohq/rect-shifted
Browse files Browse the repository at this point in the history
Add Rect::*_shifted functions
  • Loading branch information
Cobrand authored Sep 18, 2023
2 parents cdbbeda + 2adfea4 commit 1555fe8
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions src/sdl2/rect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,11 +149,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
}
Expand Down Expand Up @@ -223,6 +225,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,
Expand Down Expand Up @@ -328,6 +382,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),
Expand Down Expand Up @@ -1036,6 +1091,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);
Expand Down

0 comments on commit 1555fe8

Please sign in to comment.