galgebra/
vector.rs

1use std::cmp::Ordering;
2use std::ops::Add;
3use std::fmt;
4
5#[derive(Debug, Copy, Clone, PartialEq, Eq)]
6pub struct Vec2<T>(pub T, pub T);
7
8impl<T> fmt::Display for Vec2<T> where T: fmt::Display {
9    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10        write!(f, "{{{}; {}}}", self.0, self.1)
11    }
12}
13
14impl<T> PartialOrd for Vec2<T> where Vec2<T>: Eq, T: PartialOrd {
15    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
16        if self == other {
17            Some(Ordering::Equal)
18        }
19        else if self > other {
20            Some(Ordering::Greater)
21        }
22        else if self < other {
23            Some(Ordering::Less)
24        }
25        else {
26            None
27        }
28    }
29
30    fn lt(&self, other: &Self) -> bool {
31        self.0 < other.0 && self.1 < other.1
32    }
33
34    fn le(&self, other: &Self) -> bool {
35        self.0 <= other.0 && self.1 <= other.1
36    }
37
38    fn gt(&self, other: &Self) -> bool {
39        self.0 > other.0 && self.1 > other.1
40    }
41
42    fn ge(&self, other: &Self) -> bool {
43        self.0 >= other.0 && self.1 >= other.1
44    }
45}
46
47impl<Lhs, Rhs, Result> Add<Vec2<Rhs>>
48for Vec2<Lhs>
49    where Lhs: Add<Rhs, Output=Result> {
50    type Output = Vec2<Result>;
51
52    fn add(self, rhs: Vec2<Rhs>) -> Self::Output {
53        Vec2(
54            self.0 + rhs.0,
55            self.1 + rhs.1,
56        )
57    }
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn formatting() {
66        let v = Vec2(0, 3);
67        assert_eq!(format!("{v:?}"), "Vec2(0, 3)");
68    }
69
70    #[test]
71    fn copying() {
72        let original = Vec2(1, 3);
73        let _copy = original;
74        assert_eq!(original, Vec2(1, 3));
75    }
76
77    #[test]
78    fn displaying() {
79        let v = Vec2(2, 1);
80        assert_eq!(format!("{v}"), "{2; 1}");
81    }
82
83    #[test]
84    fn equality() {
85        assert_eq!(Vec2(1, 2), Vec2(1, 2));
86        assert_ne!(Vec2(1, 2), Vec2(2, 1));
87    }
88
89    #[test]
90    fn ordering() {
91        assert!(Vec2(2, 2) > Vec2(1, 1));
92        assert!(Vec2(2, 1) >= Vec2(1, 1));
93    }
94
95    #[test]
96    fn addition() {
97        let result = Vec2(1, 0) + Vec2(-2, 3);
98        assert_eq!(result, Vec2(-1, 3));
99    }
100}