feat(layout): add Rect -> Size conversion methods (#789)

- add Size::new() constructor
- add Rect::as_size()
- impl From<Rect> for Size
- document and add tests for Size
This commit is contained in:
Josh McKinney 2024-01-11 08:39:53 -08:00 committed by GitHub
parent ffd5fc79fc
commit 1561d64c80
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 69 additions and 2 deletions

View file

@ -8,6 +8,7 @@ use crate::prelude::*;
mod offset;
use layout::Size;
pub use offset::*;
/// A simple rectangle used in the computation of the layout and to give widgets a hint about the
@ -325,6 +326,14 @@ impl Rect {
current_column: self.x,
}
}
/// Converts the rect into a size struct.
pub fn as_size(self) -> Size {
Size {
width: self.width,
height: self.height,
}
}
}
#[cfg(test)]
@ -548,7 +557,7 @@ mod tests {
}
#[test]
fn test_rows() {
fn rows() {
let area = Rect::new(0, 0, 3, 2);
let rows: Vec<Rect> = area.rows().collect();
@ -558,7 +567,7 @@ mod tests {
}
#[test]
fn test_columns() {
fn columns() {
let area = Rect::new(0, 0, 3, 2);
let columns: Vec<Rect> = area.columns().collect();
@ -570,4 +579,15 @@ mod tests {
assert_eq!(columns, expected_columns);
}
#[test]
fn as_size() {
assert_eq!(
Rect::new(1, 2, 3, 4).as_size(),
Size {
width: 3,
height: 4
}
);
}
}

View file

@ -1,12 +1,59 @@
#![warn(missing_docs)]
use crate::prelude::*;
/// A simple size struct
///
/// The width and height are stored as `u16` values and represent the number of columns and rows
/// respectively.
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
pub struct Size {
/// The width in columns
pub width: u16,
/// The height in rows
pub height: u16,
}
impl Size {
/// Create a new `Size` struct
pub fn new(width: u16, height: u16) -> Self {
Size { width, height }
}
}
impl From<(u16, u16)> for Size {
fn from((width, height): (u16, u16)) -> Self {
Size { width, height }
}
}
impl From<Rect> for Size {
fn from(rect: Rect) -> Self {
rect.as_size()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new() {
let size = Size::new(10, 20);
assert_eq!(size.width, 10);
assert_eq!(size.height, 20);
}
#[test]
fn from_tuple() {
let size = Size::from((10, 20));
assert_eq!(size.width, 10);
assert_eq!(size.height, 20);
}
#[test]
fn from_rect() {
let size = Size::from(Rect::new(0, 0, 10, 20));
assert_eq!(size.width, 10);
assert_eq!(size.height, 20);
}
}