library/
generics.rs

1use std::cmp::{max, Ord};
2use std::hash::{Hash, Hasher};
3use std::marker::Copy;
4use std::ops::Add;
5
6pub mod traits;
7
8pub struct Point<T>
9where
10    T: Ord + Hash + Add<Output = T> + Copy,
11{
12    x: T,
13    y: T,
14}
15
16impl<T> Point<T>
17where
18    T: Ord + Hash + Add<Output = T> + Copy,
19{
20    pub fn new(x: T, y: T) -> Point<T> {
21        Point { x, y }
22    }
23
24    pub fn x(&mut self) -> &mut T {
25        &mut self.x
26    }
27
28    pub fn y(&mut self) -> &mut T {
29        &mut self.y
30    }
31
32    pub fn larger(&self) -> T {
33        *max(&self.x, &self.y)
34    }
35
36    pub fn panic(&self) {
37        panic!("intentionally panic for test");
38    }
39}
40
41impl<T> Hash for Point<T>
42where
43    T: Ord + Hash + Add<Output = T> + Copy,
44{
45    fn hash<H: Hasher>(&self, state: &mut H) {
46        self.x.hash(state);
47        self.y.hash(state);
48    }
49}
50
51impl<T> traits::Norm1d<T> for Point<T>
52where
53    T: Ord + Hash + Add<Output = T> + Copy,
54{
55    fn len(&self) -> T {
56        self.x + self.y
57    }
58}
59
60#[cfg(test)]
61mod test_point {
62    use super::*;
63
64    #[test]
65    fn test_larger() {
66        let x = 13;
67        let y = 9;
68        let point1 = Point::new(x, y);
69        assert_eq!(point1.larger(), x, "should return larger");
70
71        let point2 = Point::new(y, x);
72        assert_eq!(point2.larger(), x, "should return larger");
73    }
74
75    #[test]
76    #[should_panic(expected = "intentionally")]
77    fn test_panic() {
78        let x = 13;
79        let y = 9;
80        let point1 = Point::new(x, y);
81        point1.panic();
82    }
83}