Minor refactor
[kaka/rust-sdl-test.git] / src / common.rs
CommitLineData
6edafdc0 1use std::ops::{Add, AddAssign, Mul};
296187ca 2
787dbfb4 3#[macro_export]
296187ca 4macro_rules! point {
6ba7aef1
TW
5 ( $x:expr, $y:expr ) => {
6 Point2D { x: $x, y: $y }
7 };
296187ca
TW
8}
9
10#[derive(Debug, Copy, Clone, PartialEq)]
11pub struct Point2D<T> {
12 pub x: T,
13 pub y: T,
14}
15
16impl Point2D<f64> {
17 pub fn length(self) -> f64 {
18 ((self.x * self.x) + (self.y * self.y)).sqrt()
19 }
20}
21
6ba7aef1 22impl<T: Add<Output = T>> Add for Point2D<T> {
296187ca
TW
23 type Output = Point2D<T>;
24
25 fn add(self, rhs: Point2D<T>) -> Self::Output {
6ba7aef1
TW
26 Point2D {
27 x: self.x + rhs.x,
28 y: self.y + rhs.y,
29 }
296187ca
TW
30 }
31}
32
33impl<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
0b5024d1
TW
40#[macro_export]
41macro_rules! rect {
42 ( $x:expr, $y:expr ) => {
43 Rect { x: $x, y: $y }
44 };
45}
46
6edafdc0
TW
47#[derive(Default)]
48pub struct Rect<T> {
49 pub width: T,
50 pub height: T,
51}
52
6ba7aef1 53impl<T: Mul<Output = T> + Copy> Rect<T> {
6edafdc0
TW
54 #[allow(dead_code)]
55 pub fn area(&self) -> T {
6ba7aef1 56 self.width * self.height
6edafdc0
TW
57 }
58}
59
60impl<T> From<(T, T)> for Rect<T> {
61 fn from(item: (T, T)) -> Self {
6ba7aef1
TW
62 Rect {
63 width: item.0,
64 height: item.1,
65 }
6edafdc0
TW
66 }
67}
68
296187ca
TW
69#[cfg(test)]
70mod 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 }
6edafdc0
TW
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
6ba7aef1 93 assert_eq!(r.area(), 30 * 20);
6edafdc0
TW
94 // let a = Rect::from(("a".to_string(), "b".to_string())).area(); // this doesn't work, because area() is not implemented for String
95 }
296187ca 96}