1use crate::{Loc, Scale};
2use std::fmt::{Debug, Display, Formatter};
3
4#[derive(Copy, Clone, Eq, PartialEq, Hash, Default)]
6pub struct Dim {
7 pub w: Scale,
8 pub h: Scale,
9}
10
11impl Dim {
12 pub const fn new(w: Scale, h: Scale) -> Self {
16 Self { w, h }
17 }
18}
19
20impl From<(Scale, Scale)> for Dim {
21 fn from((w, h): (Scale, Scale)) -> Self {
22 Self { w, h }
23 }
24}
25
26impl Dim {
27 pub fn size(&self) -> usize {
31 self.w as usize * self.h as usize
32 }
33
34 pub const fn contains(&self, loc: Loc) -> bool {
36 loc.x < self.w && loc.y < self.h
37 }
38}
39
40impl Debug for Dim {
41 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
42 write!(f, "{}", self)
43 }
44}
45
46impl Display for Dim {
47 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
48 write!(f, "{}x{}", self.w, self.h)
49 }
50}
51
52#[cfg(test)]
53mod tests {
54 use crate::{Dim, Loc, Scale};
55
56 #[test]
57 fn size() {
58 let dim: Dim = Dim::new(3, 4);
59 assert_eq!(dim.size(), 12);
60 }
61
62 #[test]
63 fn size_zero() {
64 let dim: Dim = Dim::new(0, 5);
65 assert_eq!(dim.size(), 0);
66 }
67
68 #[test]
69 fn size_max() {
70 let dim: Dim = Dim::new(Scale::MAX, Scale::MAX);
71 let expected: usize = Scale::MAX as usize * Scale::MAX as usize;
72 assert_eq!(dim.size(), expected);
73 }
74
75 #[test]
76 fn contains_inside() {
77 let dim: Dim = Dim::new(3, 3);
78 assert!(dim.contains(Loc::new(0, 0)));
79 assert!(dim.contains(Loc::new(2, 2)));
80 assert!(dim.contains(Loc::new(1, 0)));
81 }
82
83 #[test]
84 fn contains_outside() {
85 let dim: Dim = Dim::new(3, 3);
86 assert!(!dim.contains(Loc::new(3, 0)));
87 assert!(!dim.contains(Loc::new(0, 3)));
88 assert!(!dim.contains(Loc::new(3, 3)));
89 }
90
91 #[test]
92 fn contains_zero_dim() {
93 let dim: Dim = Dim::new(0, 0);
94 assert!(!dim.contains(Loc::new(0, 0)));
95 }
96}