ratatui/layout/
size.rs

1#![warn(missing_docs)]
2use std::fmt;
3
4use crate::layout::Rect;
5
6/// A simple size struct
7///
8/// The width and height are stored as `u16` values and represent the number of columns and rows
9/// respectively.
10#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub struct Size {
13    /// The width in columns
14    pub width: u16,
15    /// The height in rows
16    pub height: u16,
17}
18
19impl Size {
20    /// A zero sized Size
21    pub const ZERO: Self = Self::new(0, 0);
22
23    /// Create a new `Size` struct
24    pub const fn new(width: u16, height: u16) -> Self {
25        Self { width, height }
26    }
27}
28
29impl From<(u16, u16)> for Size {
30    fn from((width, height): (u16, u16)) -> Self {
31        Self { width, height }
32    }
33}
34
35impl From<Rect> for Size {
36    fn from(rect: Rect) -> Self {
37        rect.as_size()
38    }
39}
40
41impl fmt::Display for Size {
42    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43        write!(f, "{}x{}", self.width, self.height)
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn new() {
53        let size = Size::new(10, 20);
54        assert_eq!(size.width, 10);
55        assert_eq!(size.height, 20);
56    }
57
58    #[test]
59    fn from_tuple() {
60        let size = Size::from((10, 20));
61        assert_eq!(size.width, 10);
62        assert_eq!(size.height, 20);
63    }
64
65    #[test]
66    fn from_rect() {
67        let size = Size::from(Rect::new(0, 0, 10, 20));
68        assert_eq!(size.width, 10);
69        assert_eq!(size.height, 20);
70    }
71
72    #[test]
73    fn display() {
74        assert_eq!(Size::new(10, 20).to_string(), "10x20");
75    }
76}