graph_layout/
vector.rs

1pub trait Vector: Clone {
2    type Scalar: Copy;
3
4    fn length_squared(&self) -> Self::Scalar;
5
6    fn scale(&mut self, factor: Self::Scalar);
7
8    fn sub(&self, other: &Self) -> Self;
9
10    fn add_scaled(&mut self, factor: Self::Scalar, other: &Self);
11
12    fn reset(&mut self);
13
14    fn clip_within(&mut self, min: &Self, max: &Self);
15
16    fn new() -> Self;
17}
18
19#[derive(Debug, Copy, Clone)]
20pub struct P2d (pub f32, pub f32);
21
22impl Vector for P2d {
23    type Scalar = f32;
24
25    fn new() -> Self {
26        P2d (0.0, 0.0)
27    }
28
29    fn length_squared(&self) -> f32 {
30        self.0 * self.0 + self.1 * self.1
31    }
32
33    fn reset(&mut self) {
34        self.0 = 0.0;
35        self.1 = 0.0;
36    }
37
38    fn scale(&mut self, factor: f32) {
39        self.0 *= factor;
40        self.1 *= factor;
41    }
42
43    fn sub(&self, other: &Self) -> Self {
44        P2d (self.0 - other.0, self.1 - other.1)
45    }
46
47    fn add_scaled(&mut self, factor: f32, other: &P2d) {
48        self.0 += factor * other.0;
49        self.1 += factor * other.1;
50    }
51
52    fn clip_within(&mut self, min: &Self, max: &Self) {
53        if self.0 < min.0 {
54            self.0 = min.0
55        } else if self.0 > max.0 {
56            self.0 = max.0
57        }
58
59        if self.1 < min.1 {
60            self.1 = min.1
61        } else if self.1 > max.1 {
62            self.1 = max.1
63        }
64    }
65}