Skip to content

Commit

Permalink
Add scalar division for vectors
Browse files Browse the repository at this point in the history
  • Loading branch information
sunsided committed Jul 31, 2024
1 parent 4548408 commit a6fc44d
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 2 deletions.
41 changes: 41 additions & 0 deletions src/vector/vector2d.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! 2-dimensional vector
use super::{Component, Vector, Vector3d};
use core::ops::{Div, DivAssign};
use core::{
iter::{FromIterator, Sum},
ops::{Add, AddAssign, Index, Mul, MulAssign, Sub, SubAssign},
Expand Down Expand Up @@ -251,6 +252,30 @@ where
}
}

impl<C> Div<C> for Vector2d<C>
where
C: Component,
{
type Output = Self;

fn div(self, rhs: C) -> Self {
Self {
x: self.x / rhs,
y: self.y / rhs,
}
}
}

impl<C> DivAssign<C> for Vector2d<C>
where
C: Component,
{
fn div_assign(&mut self, rhs: C) {
self.x = self.x / rhs;
self.y = self.y / rhs;
}
}

impl<C> Sum<Vector2d<C>> for Vector2d<C>
where
C: Component,
Expand Down Expand Up @@ -393,4 +418,20 @@ mod tests {
let dot = lhs.dot(rhs);
assert_eq!(dot, 11);
}

#[test]
fn div() {
let vec = Vector2d { x: 10, y: 20 };
let result = vec / 2;
assert_eq!(result.x, 5);
assert_eq!(result.y, 10);
}

#[test]
fn div_assign() {
let mut vec = Vector2d { x: 10, y: 20 };
vec /= 2;
assert_eq!(vec.x, 5);
assert_eq!(vec.y, 10);
}
}
48 changes: 46 additions & 2 deletions src/vector/vector3d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
use super::{Component, Vector, Vector2d};
use crate::F32;
use core::iter::Sum;
use core::ops::{Div, DivAssign};
use core::{
iter::FromIterator,
iter::{FromIterator, Sum},
ops::{Add, AddAssign, Index, Mul, MulAssign, Sub, SubAssign},
};

Expand Down Expand Up @@ -269,6 +269,32 @@ where
}
}

impl<C> Div<C> for Vector3d<C>
where
C: Component,
{
type Output = Self;

fn div(self, rhs: C) -> Self {
Self {
x: self.x / rhs,
y: self.y / rhs,
z: self.z / rhs,
}
}
}

impl<C> DivAssign<C> for Vector3d<C>
where
C: Component,
{
fn div_assign(&mut self, rhs: C) {
self.x = self.x / rhs;
self.y = self.y / rhs;
self.z = self.z / rhs;
}
}

impl<C> Sum<Vector3d<C>> for Vector3d<C>
where
C: Component,
Expand Down Expand Up @@ -428,4 +454,22 @@ mod tests {
let dot = lhs.dot(rhs);
assert_eq!(dot, 32);
}

#[test]
fn div() {
let vec = Vector3d { x: 10, y: 20, z: 30 };
let result = vec / 2;
assert_eq!(result.x, 5);
assert_eq!(result.y, 10);
assert_eq!(result.z, 15);
}

#[test]
fn div_assign() {
let mut vec = Vector3d { x: 10, y: 20, z: 30 };
vec /= 2;
assert_eq!(vec.x, 5);
assert_eq!(vec.y, 10);
assert_eq!(vec.z, 15);
}
}

0 comments on commit a6fc44d

Please sign in to comment.