Skip to main content

uncurses/layout/
size.rs

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