1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use super::unsignedcoord::UnsignedCoord;
type CoordPart = i32;
#[cfg(not(feature = "nalgebra_support"))]
mod internal_coord {
use super::*;
use core::ops::{Add, AddAssign, Index, Sub, SubAssign};
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Coord(pub CoordPart, pub CoordPart);
impl Coord {
pub fn new(x: CoordPart, y: CoordPart) -> Self {
Coord(x, y)
}
pub fn clamp_positive(&self) -> Self {
Coord(self.0.max(0), self.1.max(0))
}
pub fn abs(&self) -> Self {
Coord(self.0.abs(), self.1.abs())
}
}
impl Add for Coord {
type Output = Coord;
fn add(self, other: Coord) -> Coord {
Coord::new(self.0 + other.0, self.1 + other.1)
}
}
impl AddAssign for Coord {
fn add_assign(&mut self, other: Coord) {
self.0 += other.0;
self.1 += other.1;
}
}
impl Sub for Coord {
type Output = Coord;
fn sub(self, other: Coord) -> Coord {
Coord::new(self.0 - other.0, self.1 - other.1)
}
}
impl SubAssign for Coord {
fn sub_assign(&mut self, other: Coord) {
self.0 -= other.0;
self.1 -= other.1;
}
}
impl Index<usize> for Coord {
type Output = CoordPart;
fn index(&self, idx: usize) -> &CoordPart {
match idx {
0 => &self.0,
1 => &self.1,
_ => panic!("Unreachable index {}", idx),
}
}
}
}
#[cfg(not(feature = "nalgebra_support"))]
pub use self::internal_coord::Coord;
#[cfg(feature = "nalgebra_support")]
use nalgebra;
#[cfg(feature = "nalgebra_support")]
pub type Coord = nalgebra::Vector2<CoordPart>;
pub trait ToUnsigned {
fn to_unsigned(self) -> UnsignedCoord;
}
impl ToUnsigned for Coord {
fn to_unsigned(self) -> UnsignedCoord {
UnsignedCoord::new(self[0].max(0) as u32, self[1].max(0) as u32)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn coords_can_be_added() {
let left = Coord::new(10, 20);
let right = Coord::new(30, 40);
assert_eq!(left + right, Coord::new(40, 60));
}
#[test]
fn coords_can_be_subtracted() {
let left = Coord::new(30, 40);
let right = Coord::new(10, 20);
assert_eq!(left - right, Coord::new(20, 20));
}
#[test]
fn coords_can_be_negative_subtracted() {
let left = Coord::new(10, 20);
let right = Coord::new(30, 40);
assert_eq!(left - right, Coord::new(-20, -20));
}
#[test]
#[cfg(feature = "nalgebra_support")]
fn nalgebra_support() {
let left = nalgebra::Vector2::new(30, 40);
let right = nalgebra::Vector2::new(10, 20);
assert_eq!(left - right, Coord::new(20, 20));
}
}