442b11c5eb00c74e47fea8fb7a6e9bc4a9a63484
[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 #[macro_export]
41 macro_rules! rect {
42     ( $x:expr, $y:expr ) => {
43         Rect { x: $x, y: $y }
44     };
45 }
46
47 #[derive(Default)]
48 pub struct Rect<T> {
49     pub width: T,
50     pub height: T,
51 }
52
53 impl<T: Mul<Output = T> + Copy> Rect<T> {
54     #[allow(dead_code)]
55     pub fn area(&self) -> T {
56         self.width * self.height
57     }
58 }
59
60 impl<T> From<(T, T)> for Rect<T> {
61     fn from(item: (T, T)) -> Self {
62         Rect {
63             width: item.0,
64             height: item.1,
65         }
66     }
67 }
68
69 #[cfg(test)]
70 mod tests {
71     use super::*;
72
73     #[test]
74     fn immutable_copy_of_point() {
75         let a = point!(0, 0);
76         let mut b = a; // Copy
77         assert_eq!(a, b); // PartialEq
78         b.x = 1;
79         assert_ne!(a, b); // PartialEq
80     }
81
82     #[test]
83     fn add_points() {
84         let mut a = point!(1, 0);
85         assert_eq!(a + point!(2, 2), point!(3, 2)); // Add
86         a += point!(2, 2); // AddAssign
87         assert_eq!(a, point!(3, 2));
88     }
89
90     #[test]
91     fn area_for_rect_of_multipliable_type() {
92         let r: Rect<_> = (30, 20).into(); // the Into trait uses the From trait
93         assert_eq!(r.area(), 30 * 20);
94         // let a = Rect::from(("a".to_string(), "b".to_string())).area(); // this doesn't work, because area() is not implemented for String
95     }
96 }