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
use super::Position;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum N {
N(usize),
P(usize),
}
impl N {
fn get_number(&self) -> usize {
match self {
N::N(n) => *n,
N::P(n) => *n,
}
}
fn from_isize(n: isize) -> Self {
if n < 0 {
return N::N((-n) as usize);
}
N::P(n as usize)
}
fn from_i32(n: i32) -> Self {
if n < 0 {
return N::N((-n) as usize);
}
N::P(n as usize)
}
pub(crate) fn checked_add_sub(&self, n: usize) -> Option<usize> {
Some(match self {
N::N(pn) => n.checked_sub(*pn)?,
N::P(pn) => n.checked_add(*pn)?,
})
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Step {
x: N,
y: N,
}
impl Step {
pub fn new(x: usize, y: usize) -> Self {
Step {
x: N::P(x),
y: N::P(y),
}
}
pub fn negate_x(mut self) -> Self {
self.x = N::N(self.x.get_number());
self
}
pub fn negate_y(mut self) -> Self {
self.y = N::N(self.y.get_number());
self
}
pub(crate) fn take_step_from_position(&self, pos: Position) -> Option<Position> {
let x = self.x.checked_add_sub(pos.x)?;
let y = self.y.checked_add_sub(pos.y)?;
Some((x, y).into())
}
}
impl From<(usize, usize)> for Step {
fn from((x, y): (usize, usize)) -> Self {
Step::new(x, y)
}
}
impl From<(isize, isize)> for Step {
fn from((x, y): (isize, isize)) -> Self {
Step {
x: N::from_isize(x),
y: N::from_isize(y),
}
}
}
impl From<(i32, i32)> for Step {
fn from((x, y): (i32, i32)) -> Self {
Step {
x: N::from_i32(x),
y: N::from_i32(y),
}
}
}