Skip to main content

mln_style/
size.rs

1/// A width/height pair in (logical or physical) pixels.
2#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, mln_wire::Wire)]
3pub struct Size {
4    pub width: u32,
5    pub height: u32,
6}
7
8impl Size {
9    #[must_use]
10    pub const fn new(width: u32, height: u32) -> Self {
11        Size { width, height }
12    }
13
14    /// The area, in square pixels.
15    #[must_use]
16    pub const fn area(&self) -> u64 {
17        self.width as u64 * self.height as u64
18    }
19
20    #[must_use]
21    pub fn aspect_ratio(&self) -> f32 {
22        self.width as f32 / self.height as f32
23    }
24
25    #[must_use]
26    pub const fn is_empty(&self) -> bool {
27        self.width == 0 || self.height == 0
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn basics() {
37        let s = Size::new(512, 256);
38        assert_eq!(s.area(), 131_072);
39        assert_eq!(s.aspect_ratio(), 2.0);
40        assert!(!s.is_empty());
41        assert!(Size::default().is_empty());
42        assert!(Size::new(0, 5).is_empty());
43        assert_eq!(Size::new(1, 2), Size::new(1, 2));
44        assert_ne!(Size::new(1, 2), Size::new(2, 1));
45    }
46}