Skip to content

Commit

Permalink
feat(Rect): add offset method
Browse files Browse the repository at this point in the history
  • Loading branch information
Valentin271 committed Nov 27, 2023
1 parent fe632d7 commit 21dd1ad
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/layout/rect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ use std::{

use crate::prelude::*;

mod offset;

pub use offset::*;

/// A simple rectangle used in the computation of the layout and to give widgets a hint about the
/// area they are supposed to render to.
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
Expand Down Expand Up @@ -106,6 +110,26 @@ impl Rect {
}
}

/// Moves the `Rect` without modifying its size.
///
/// Moves the `Rect` according to the given offset without modifying its [`width`](Rect::width)
/// or [`height`](Rect::height).
/// - Positive `x` moves the whole `Rect` to the right, negative to the left.
/// - Positive `y` moves the whole `Rect` to the bottom, negative to the top.
///
/// See [`Offset`] for details.
pub fn offset(self, offset: Offset) -> Rect {
Rect {
x: i32::from(self.x)
.saturating_add(offset.x)
.clamp(0, u16::MAX as i32) as u16,
y: i32::from(self.y)
.saturating_add(offset.y)
.clamp(0, u16::MAX as i32) as u16,
..self
}
}

/// Returns a new rect that contains both the current one and the given one.
pub fn union(self, other: Rect) -> Rect {
let x1 = min(self.x, other.x);
Expand Down Expand Up @@ -207,6 +231,30 @@ mod tests {
);
}

#[test]
fn offset() {
assert_eq!(
Rect::new(1, 2, 3, 4).offset(Offset { x: 5, y: 6 }),
Rect::new(6, 8, 3, 4),
);
}

#[test]
fn negative_offset() {
assert_eq!(
Rect::new(4, 3, 3, 4).offset(Offset { x: -2, y: -1 }),
Rect::new(2, 2, 3, 4),
);
}

#[test]
fn offset_saturate() {
assert_eq!(
Rect::new(1, 2, 3, 4).offset(Offset { x: -5, y: -6 }),
Rect::new(0, 0, 3, 4),
);
}

#[test]
fn union() {
assert_eq!(
Expand Down
12 changes: 12 additions & 0 deletions src/layout/rect/offset.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/// Amounts by which to move a [`Rect`](super::Rect).
///
/// Positive numbers move to the right/bottom and negative to the left/top.
///
/// See [`Rect::offset`](super::Rect::offset)
#[derive(Debug, Default, Clone, Copy)]

Check warning on line 6 in src/layout/rect/offset.rs

View check run for this annotation

Codecov / codecov/patch

src/layout/rect/offset.rs#L6

Added line #L6 was not covered by tests
pub struct Offset {
/// How much to move on the X axis
pub x: i32,
/// How much to move on the Y axis
pub y: i32,
}

0 comments on commit 21dd1ad

Please sign in to comment.