iced_core/
vector.rs

1/// A 2D vector.
2#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3pub struct Vector<T = f32> {
4    /// The X component of the [`Vector`]
5    pub x: T,
6
7    /// The Y component of the [`Vector`]
8    pub y: T,
9}
10
11impl<T> Vector<T> {
12    /// Creates a new [`Vector`] with the given components.
13    pub const fn new(x: T, y: T) -> Self {
14        Self { x, y }
15    }
16}
17
18impl Vector {
19    /// The zero [`Vector`].
20    pub const ZERO: Self = Self::new(0.0, 0.0);
21}
22
23impl<T> std::ops::Neg for Vector<T>
24where
25    T: std::ops::Neg<Output = T>,
26{
27    type Output = Self;
28
29    fn neg(self) -> Self::Output {
30        Self::new(-self.x, -self.y)
31    }
32}
33
34impl<T> std::ops::Add for Vector<T>
35where
36    T: std::ops::Add<Output = T>,
37{
38    type Output = Self;
39
40    fn add(self, b: Self) -> Self {
41        Self::new(self.x + b.x, self.y + b.y)
42    }
43}
44
45impl<T> std::ops::AddAssign for Vector<T>
46where
47    T: std::ops::AddAssign,
48{
49    fn add_assign(&mut self, b: Self) {
50        self.x += b.x;
51        self.y += b.y;
52    }
53}
54
55impl<T> std::ops::Sub for Vector<T>
56where
57    T: std::ops::Sub<Output = T>,
58{
59    type Output = Self;
60
61    fn sub(self, b: Self) -> Self {
62        Self::new(self.x - b.x, self.y - b.y)
63    }
64}
65
66impl<T> std::ops::SubAssign for Vector<T>
67where
68    T: std::ops::SubAssign,
69{
70    fn sub_assign(&mut self, b: Self) {
71        self.x -= b.x;
72        self.y -= b.y;
73    }
74}
75
76impl<T> std::ops::Mul<T> for Vector<T>
77where
78    T: std::ops::Mul<Output = T> + Copy,
79{
80    type Output = Self;
81
82    fn mul(self, scale: T) -> Self {
83        Self::new(self.x * scale, self.y * scale)
84    }
85}
86
87impl<T> std::ops::MulAssign<T> for Vector<T>
88where
89    T: std::ops::MulAssign + Copy,
90{
91    fn mul_assign(&mut self, scale: T) {
92        self.x *= scale;
93        self.y *= scale;
94    }
95}
96
97impl<T> std::ops::Div<T> for Vector<T>
98where
99    T: std::ops::Div<Output = T> + Copy,
100{
101    type Output = Self;
102
103    fn div(self, scale: T) -> Self {
104        Self::new(self.x / scale, self.y / scale)
105    }
106}
107
108impl<T> std::ops::DivAssign<T> for Vector<T>
109where
110    T: std::ops::DivAssign + Copy,
111{
112    fn div_assign(&mut self, scale: T) {
113        self.x /= scale;
114        self.y /= scale;
115    }
116}
117
118impl<T> From<[T; 2]> for Vector<T> {
119    fn from([x, y]: [T; 2]) -> Self {
120        Self::new(x, y)
121    }
122}
123
124impl<T> From<Vector<T>> for [T; 2]
125where
126    T: Copy,
127{
128    fn from(other: Vector<T>) -> Self {
129        [other.x, other.y]
130    }
131}