Merge pull request #3131 from edwloef/assign-traits

Implement `*Assign` traits for operations on `Point` and `Vector`
This commit is contained in:
Héctor 2025-12-01 01:34:51 +01:00 committed by GitHub
commit 01c79ad816
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 57 additions and 9 deletions

View file

@ -74,6 +74,16 @@ where
}
}
impl<T> std::ops::AddAssign<Vector<T>> for Point<T>
where
T: std::ops::AddAssign,
{
fn add_assign(&mut self, vector: Vector<T>) {
self.x += vector.x;
self.y += vector.y;
}
}
impl<T> std::ops::Sub<Vector<T>> for Point<T>
where
T: std::ops::Sub<Output = T>,
@ -88,6 +98,16 @@ where
}
}
impl<T> std::ops::SubAssign<Vector<T>> for Point<T>
where
T: std::ops::SubAssign,
{
fn sub_assign(&mut self, vector: Vector<T>) {
self.x -= vector.x;
self.y -= vector.y;
}
}
impl<T> std::ops::Sub<Point<T>> for Point<T>
where
T: std::ops::Sub<Output = T>,

View file

@ -1,5 +1,5 @@
/// A 2D vector.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Vector<T = f32> {
/// The X component of the [`Vector`]
pub x: T,
@ -42,6 +42,16 @@ where
}
}
impl<T> std::ops::AddAssign for Vector<T>
where
T: std::ops::AddAssign,
{
fn add_assign(&mut self, b: Self) {
self.x += b.x;
self.y += b.y;
}
}
impl<T> std::ops::Sub for Vector<T>
where
T: std::ops::Sub<Output = T>,
@ -53,6 +63,16 @@ where
}
}
impl<T> std::ops::SubAssign for Vector<T>
where
T: std::ops::SubAssign,
{
fn sub_assign(&mut self, b: Self) {
self.x -= b.x;
self.y -= b.y;
}
}
impl<T> std::ops::Mul<T> for Vector<T>
where
T: std::ops::Mul<Output = T> + Copy,
@ -64,6 +84,16 @@ where
}
}
impl<T> std::ops::MulAssign<T> for Vector<T>
where
T: std::ops::MulAssign + Copy,
{
fn mul_assign(&mut self, scale: T) {
self.x *= scale;
self.y *= scale;
}
}
impl<T> std::ops::Div<T> for Vector<T>
where
T: std::ops::Div<Output = T> + Copy,
@ -75,15 +105,13 @@ where
}
}
impl<T> Default for Vector<T>
impl<T> std::ops::DivAssign<T> for Vector<T>
where
T: Default,
T: std::ops::DivAssign + Copy,
{
fn default() -> Self {
Self {
x: T::default(),
y: T::default(),
}
fn div_assign(&mut self, scale: T) {
self.x /= scale;
self.y /= scale;
}
}

View file

@ -211,7 +211,7 @@ where
state,
});
self.translation = self.translation - translation;
self.translation -= translation;
self.viewport = visible_bounds.unwrap_or_default();
}