From 1561d64c80e6498f90807a1607d84a1405d3e0bb Mon Sep 17 00:00:00 2001 From: Josh McKinney Date: Thu, 11 Jan 2024 08:39:53 -0800 Subject: [PATCH] feat(layout): add Rect -> Size conversion methods (#789) - add Size::new() constructor - add Rect::as_size() - impl From for Size - document and add tests for Size --- src/layout/rect.rs | 24 +++++++++++++++++++++-- src/layout/size.rs | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/src/layout/rect.rs b/src/layout/rect.rs index cb1fe9e4..8cdcc0d4 100644 --- a/src/layout/rect.rs +++ b/src/layout/rect.rs @@ -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 = 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 = 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 + } + ); + } } diff --git a/src/layout/size.rs b/src/layout/size.rs index 2763e997..92ebf1fa 100644 --- a/src/layout/size.rs +++ b/src/layout/size.rs @@ -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 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); + } +}