Commit | Line | Data |
---|---|---|
6edafdc0 | 1 | use std::ops::{Add, AddAssign, Mul}; |
296187ca | 2 | |
787dbfb4 | 3 | #[macro_export] |
296187ca | 4 | macro_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)] | |
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 | ||
6ba7aef1 | 22 | impl<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 | ||
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 | ||
6edafdc0 TW |
40 | #[derive(Default)] |
41 | pub struct Rect<T> { | |
42 | pub width: T, | |
43 | pub height: T, | |
44 | } | |
45 | ||
6ba7aef1 | 46 | impl<T: Mul<Output = T> + Copy> Rect<T> { |
6edafdc0 TW |
47 | #[allow(dead_code)] |
48 | pub fn area(&self) -> T { | |
6ba7aef1 | 49 | self.width * self.height |
6edafdc0 TW |
50 | } |
51 | } | |
52 | ||
53 | impl<T> From<(T, T)> for Rect<T> { | |
54 | fn from(item: (T, T)) -> Self { | |
6ba7aef1 TW |
55 | Rect { |
56 | width: item.0, | |
57 | height: item.1, | |
58 | } | |
6edafdc0 TW |
59 | } |
60 | } | |
61 | ||
296187ca TW |
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 | } | |
6edafdc0 TW |
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 | |
6ba7aef1 | 86 | assert_eq!(r.area(), 30 * 20); |
6edafdc0 TW |
87 | // let a = Rect::from(("a".to_string(), "b".to_string())).area(); // this doesn't work, because area() is not implemented for String |
88 | } | |
296187ca | 89 | } |