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
|
use std::ops::{Add, Sub};
use serde::{Serialize, Serializer, Deserialize, Deserializer};
use crate::util::clamp;
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, Default)]
pub struct Pos {
pub x: i64,
pub y: i64
}
impl Pos {
pub fn new(x: i64, y: i64) -> Pos {
Pos {x, y}
}
pub fn from_tuple(p: (i64, i64)) -> Pos {
let (x, y) = p;
Pos {x, y}
}
#[allow(dead_code)]
pub fn clamp(self, smaller: Pos, larger: Pos) -> Pos {
Pos {
x: clamp(self.x, smaller.x, larger.x),
y: clamp(self.y, smaller.y, larger.y)
}
}
pub fn distance_to(&self, other: Pos) -> i64 {
let d = other - *self;
d.x.abs() + d.y.abs()
}
}
impl Serialize for Pos {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer {
(self.x, self.y).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Pos {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de> {
let (x, y) = <(i64, i64)>::deserialize(deserializer)?;
Ok(Self{x, y})
}
}
impl Add<Pos> for Pos {
type Output = Pos;
fn add(self, other: Pos) -> Pos {
Pos {
x: self.x + other.x,
y: self.y + other.y
}
}
}
impl Sub<Pos> for Pos {
type Output = Pos;
fn sub(self, other: Pos) -> Pos {
Pos {
x: self.x - other.x,
y: self.y - other.y
}
}
}
|