Skip to main content

photon_ui/layout/
offset.rs

1/// Relative movement in the terminal coordinate system.
2#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
3pub struct Offset {
4    pub x: i16,
5    pub y: i16,
6}
7
8impl Offset {
9    pub const MAX: Self = Self::new(i16::MAX, i16::MAX);
10    pub const MIN: Self = Self::new(i16::MIN, i16::MIN);
11
12    pub const fn new(x: i16, y: i16) -> Self {
13        Self { x, y }
14    }
15}
16
17impl std::ops::Add for Offset {
18    type Output = Self;
19
20    fn add(self, other: Self) -> Self::Output {
21        Self {
22            x: self.x.saturating_add(other.x),
23            y: self.y.saturating_add(other.y),
24        }
25    }
26}
27
28impl std::ops::Sub for Offset {
29    type Output = Self;
30
31    fn sub(self, other: Self) -> Self::Output {
32        Self {
33            x: self.x.saturating_sub(other.x),
34            y: self.y.saturating_sub(other.y),
35        }
36    }
37}
38
39impl std::ops::Neg for Offset {
40    type Output = Self;
41
42    fn neg(self) -> Self::Output {
43        Self {
44            x: self.x.saturating_neg(),
45            y: self.y.saturating_neg(),
46        }
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn offset_new() {
56        let o = Offset::new(5, -3);
57        assert_eq!(o.x, 5);
58        assert_eq!(o.y, -3);
59    }
60
61    #[test]
62    fn offset_add() {
63        let a = Offset::new(10, 20);
64        let b = Offset::new(5, -8);
65        assert_eq!(a + b, Offset::new(15, 12));
66    }
67
68    #[test]
69    fn offset_sub() {
70        let a = Offset::new(10, 20);
71        let b = Offset::new(5, 8);
72        assert_eq!(a - b, Offset::new(5, 12));
73    }
74
75    #[test]
76    fn offset_neg() {
77        let o = Offset::new(5, -3);
78        assert_eq!(-o, Offset::new(-5, 3));
79    }
80
81    #[test]
82    fn offset_add_saturates() {
83        let a = Offset::new(i16::MAX, i16::MAX);
84        let b = Offset::new(1, 1);
85        assert_eq!(a + b, Offset::new(i16::MAX, i16::MAX));
86    }
87
88    #[test]
89    fn offset_sub_saturates() {
90        let a = Offset::new(i16::MIN, i16::MIN);
91        let b = Offset::new(1, 1);
92        assert_eq!(a - b, Offset::new(i16::MIN, i16::MIN));
93    }
94}