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 Sep 7, 2024
1 parent 5a74b05 commit a809e16
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 2 deletions.
41 changes: 41 additions & 0 deletions src/vector/vector2d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use super::{Component, Vector, Vector3d};
use crate::vector::commutative::impl_commutative;
use crate::F32;
use core::ops::{Div, DivAssign};
use core::{
iter::{FromIterator, Sum},
ops::{Add, AddAssign, Index, Mul, MulAssign, Sub, SubAssign},
Expand Down Expand Up @@ -262,6 +263,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 @@ -404,4 +429,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);
}
}
56 changes: 54 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::{commutative::impl_commutative, 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 @@ -278,6 +278,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 @@ -437,4 +463,30 @@ 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 a809e16

Please sign in to comment.