cp_library_rs/geometry/
vec2.rs1use std::{
4 hash::Hash,
5 ops::{Add, Div, Mul, Neg, Sub},
6};
7
8#[allow(unused_imports)]
9use crate::geometry::basic;
10
11use num_traits::Num;
12
13#[derive(Debug, Clone, Copy)]
15pub struct Vec2<T>(pub T, pub T);
16
17impl<T: PartialEq> PartialEq for Vec2<T> {
18 fn eq(&self, other: &Self) -> bool {
19 self.0.eq(&other.0) && self.1.eq(&other.1)
20 }
21}
22
23impl<T: Hash> Hash for Vec2<T> {
24 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
25 self.0.hash(state);
26 self.1.hash(state);
27 }
28}
29
30impl<T> Add for Vec2<T>
31where
32 T: Add<Output = T>,
33{
34 type Output = Self;
35 fn add(self, rhs: Self) -> Self::Output {
36 Self(self.0 + rhs.0, self.1 + rhs.1)
37 }
38}
39
40impl<T> Sub for Vec2<T>
41where
42 T: Sub<Output = T>,
43{
44 type Output = Self;
45 fn sub(self, rhs: Self) -> Self::Output {
46 Self(self.0 - rhs.0, self.1 - rhs.1)
47 }
48}
49
50impl<T> Neg for Vec2<T>
51where
52 T: Neg<Output = T>,
53{
54 type Output = Self;
55 fn neg(self) -> Self::Output {
56 Self(-self.0, -self.1)
57 }
58}
59
60impl<T> Mul<T> for Vec2<T>
61where
62 T: Mul<Output = T> + Clone,
63{
64 type Output = Self;
65 fn mul(self, rhs: T) -> Self::Output {
66 Self(self.0 * rhs.clone(), self.1 * rhs)
67 }
68}
69
70impl<T> Div<T> for Vec2<T>
71where
72 T: Div<Output = T> + Clone,
73{
74 type Output = Self;
75 fn div(self, rhs: T) -> Self::Output {
76 Self(self.0 / rhs.clone(), self.1 / rhs)
77 }
78}
79
80impl<T: Num + Copy> Vec2<T> {
81 pub fn dot(&self, other: Self) -> T {
87 let Self(ax, ay) = *self;
88 let Self(bx, by) = other;
89 ax * bx + ay * by
90 }
91
92 pub fn norm2(&self) -> T {
98 self.dot(*self)
99 }
100
101 pub fn dist2(&self, other: Self) -> T {
107 let diff = *self - other;
108 diff.norm2()
109 }
110
111 pub fn cross(&self, other: Self) -> T {
117 let Self(ax, ay) = *self;
118 let Self(bx, by) = other;
119 ax * by - ay * bx
120 }
121}