From a809e16ff27b90bbfdd6883cd220346e3c101e67 Mon Sep 17 00:00:00 2001 From: Markus Mayer Date: Wed, 17 Jul 2024 17:06:29 +0200 Subject: [PATCH] Add scalar division for vectors --- src/vector/vector2d.rs | 41 +++++++++++++++++++++++++++++++ src/vector/vector3d.rs | 56 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 95 insertions(+), 2 deletions(-) diff --git a/src/vector/vector2d.rs b/src/vector/vector2d.rs index dc0d99b..562ba00 100644 --- a/src/vector/vector2d.rs +++ b/src/vector/vector2d.rs @@ -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}, @@ -262,6 +263,30 @@ where } } +impl Div for Vector2d +where + C: Component, +{ + type Output = Self; + + fn div(self, rhs: C) -> Self { + Self { + x: self.x / rhs, + y: self.y / rhs, + } + } +} + +impl DivAssign for Vector2d +where + C: Component, +{ + fn div_assign(&mut self, rhs: C) { + self.x = self.x / rhs; + self.y = self.y / rhs; + } +} + impl Sum> for Vector2d where C: Component, @@ -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); + } } diff --git a/src/vector/vector3d.rs b/src/vector/vector3d.rs index 32c6ea4..fa95183 100644 --- a/src/vector/vector3d.rs +++ b/src/vector/vector3d.rs @@ -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}, }; @@ -278,6 +278,32 @@ where } } +impl Div for Vector3d +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 DivAssign for Vector3d +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 Sum> for Vector3d where C: Component, @@ -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); + } }