Skip to content

Commit

Permalink
feat(Rect): Rect manipulation methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Valentin271 committed Nov 25, 2023
1 parent 3bda372 commit 893dd7a
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
60 changes: 60 additions & 0 deletions src/layout/rect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,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 @@ -86,6 +90,56 @@ impl Rect {
}
}

/// Adjusts the size of the `Rect`.
///
/// - Positive `width` grows the width, negative shrinks.
/// - Positive `height` grows the height, negative shrinks.
///
/// # See also
///
/// See also [`Rect::relocate`] to move the `Rect`.
pub fn resize<I, J>(self, width: I, height: J) -> Rect
where
I: Into<i32>,
J: Into<i32>,
{
Rect {
width: i32::from(self.width)
.saturating_add(width.into())
.clamp(0, u16::MAX as i32) as u16,
height: i32::from(self.height)
.saturating_add(height.into())
.clamp(0, u16::MAX as i32) as u16,
..self
}
}

/// Moves the `Rect` without modifying its size.
///
/// Moves the `Rect` according to `x` or `y` without modifying its [`Rect::width`] or
/// [`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 also
///
/// See also [`Rect::resize`] to resize.
pub fn relocate<I, J>(self, x: I, y: J) -> Rect
where
I: Into<i32>,
J: Into<i32>,
{
Rect {
x: i32::from(self.x)
.saturating_add(x.into())
.clamp(0, u16::MAX as i32) as u16,
y: i32::from(self.y)
.saturating_add(y.into())
.clamp(0, u16::MAX as i32) as u16,
..self
}
}

pub fn union(self, other: Rect) -> Rect {
let x1 = min(self.x, other.x);
let y1 = min(self.y, other.y);
Expand Down Expand Up @@ -263,4 +317,10 @@ mod tests {
const _BOTTOM: u16 = RECT.bottom();
assert!(RECT.intersects(RECT));
}

#[test]
fn saturate_add_neg() {
let t: i32 = -1;
assert_eq!(t.clamp(0, i32::from(u16::MAX)) as u16, 0u16);
}
}
30 changes: 30 additions & 0 deletions src/layout/rect/offset.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/// Not used for now, might be used by `Rect::offset` later of removed
#[derive(Debug, Default, Clone, Copy)]
pub struct Offset {
pub top: i32,
pub right: i32,
pub bottom: i32,
pub left: i32,
}

impl Offset {
pub fn topleft(top: i32, left: i32) -> Self {
Self {
top,
right: 0,
bottom: 0,
left,
}
}
}

impl From<(i32, i32)> for Offset {
fn from(value: (i32, i32)) -> Self {
Self {
top: value.0,
right: value.1,
bottom: value.0,
left: value.1,
}
}
}

0 comments on commit 893dd7a

Please sign in to comment.