283640e87667e53ada0a7ecf6bfb332b98016b5e
[kaka/rust-sdl-test.git] / src / common.rs
1 use std::ops::{Add, AddAssign, Mul};
2
3 #[macro_export]
4 macro_rules! point {
5     ( $x:expr, $y:expr ) => {
6         Point2D { x: $x, y: $y }
7     };
8 }
9
10 #[derive(Debug, Copy, Clone, PartialEq)]
11 pub struct Point2D<T> {
12     pub x: T,
13     pub y: T,
14 }
15
16 impl Point2D<f64> {
17     pub fn length(self) -> f64 {
18         ((self.x * self.x) + (self.y * self.y)).sqrt()
19     }
20 }
21
22 impl<T: Add<Output = T>> Add for Point2D<T> {
23     type Output = Point2D<T>;
24
25     fn add(self, rhs: Point2D<T>) -> Self::Output {
26         Point2D {
27             x: self.x + rhs.x,
28             y: self.y + rhs.y,
29         }
30     }
31 }
32
33 impl<T: AddAssign> AddAssign for Point2D<T> {
34     fn add_assign(&mut self, rhs: Point2D<T>) {
35         self.x += rhs.x;
36         self.y += rhs.y;
37     }
38 }
39
40 #[derive(Default)]
41 pub struct Rect<T> {
42     pub width: T,
43     pub height: T,
44 }
45
46 impl<T: Mul<Output = T> + Copy> Rect<T> {
47     #[allow(dead_code)]
48     pub fn area(&self) -> T {
49         self.width * self.height
50     }
51 }
52
53 impl<T> From<(T, T)> for Rect<T> {
54     fn from(item: (T, T)) -> Self {
55         Rect {
56             width: item.0,
57             height: item.1,
58         }
59     }
60 }
61
62 #[cfg(test)]
63 mod tests {
64     use super::*;
65
66     #[test]
67     fn immutable_copy_of_point() {
68         let a = point!(0, 0);
69         let mut b = a; // Copy
70         assert_eq!(a, b); // PartialEq
71         b.x = 1;
72         assert_ne!(a, b); // PartialEq
73     }
74
75     #[test]
76     fn add_points() {
77         let mut a = point!(1, 0);
78         assert_eq!(a + point!(2, 2), point!(3, 2)); // Add
79         a += point!(2, 2); // AddAssign
80         assert_eq!(a, point!(3, 2));
81     }
82
83     #[test]
84     fn area_for_rect_of_multipliable_type() {
85         let r: Rect<_> = (30, 20).into(); // the Into trait uses the From trait
86         assert_eq!(r.area(), 30 * 20);
87         // let a = Rect::from(("a".to_string(), "b".to_string())).area(); // this doesn't work, because area() is not implemented for String
88     }
89 }