Skip to main content

uncurses/layout/
size.rs

1//! [`Size`] — a width and height in the cell grid.
2
3use core::fmt;
4
5use super::Rect;
6
7/// A size in the cell grid (`width` columns by `height` rows).
8#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
9pub struct Size {
10    /// Width in cells (columns).
11    pub width: u16,
12    /// Height in cells (rows).
13    pub height: u16,
14}
15
16impl Size {
17    /// A zero-sized area.
18    pub const ZERO: Self = Self::new(0, 0);
19
20    /// Create a size from `(width, height)`.
21    pub const fn new(width: u16, height: u16) -> Self {
22        Self { width, height }
23    }
24}
25
26impl From<(u16, u16)> for Size {
27    fn from((width, height): (u16, u16)) -> Self {
28        Self { width, height }
29    }
30}
31
32impl From<Size> for (u16, u16) {
33    fn from(s: Size) -> Self {
34        (s.width, s.height)
35    }
36}
37
38impl From<Rect> for Size {
39    /// The rectangle's `width` by `height`, dropping its position.
40    fn from(r: Rect) -> Self {
41        Self {
42            width: r.width,
43            height: r.height,
44        }
45    }
46}
47
48impl fmt::Display for Size {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        write!(f, "{}x{}", self.width, self.height)
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn size_from_tuple() {
60        let s: Size = (80, 24).into();
61        assert_eq!(s, Size::new(80, 24));
62        let (w, h): (u16, u16) = s.into();
63        assert_eq!((w, h), (80, 24));
64    }
65
66    #[test]
67    fn size_from_rect() {
68        let r = Rect::new(7, 9, 10, 2);
69        assert_eq!(Size::from(r), Size::new(10, 2));
70    }
71}