From 0cb1157df0591a344faa793cc31e8e968f8f2c84 Mon Sep 17 00:00:00 2001 From: Matthew Gordon Date: Thu, 24 Oct 2019 20:42:58 -0400 Subject: [PATCH] Implement Mul for Vector2D * scalar --- src/lib.rs | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index effd0ee..f7ff75b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ use std::ops::Add; +use std::ops::Mul; use std::ops::Sub; #[derive(Clone, Copy, Eq, PartialEq)] @@ -20,6 +21,14 @@ impl Sub for Vector2D { } } +impl Mul for Vector2D { + type Output = Vector2D; + + fn mul(self, other: T) -> Vector2D { + Vector2D(self.0 * other, self.1 * other) + } +} + #[derive(Clone, Copy, Eq, PartialEq)] struct Vector3D(T, T, T); @@ -238,6 +247,69 @@ mod tests { } } + #[test] + fn test_vector2_multiply_zeroes_yields_zeroes() { + let a = Vector2D(0.0, 0.0); + let b = 0.0; + let c = a * b; + assert!(c.0 == 0.0); + assert!(c.1 == 0.0); + } + + #[test] + fn test_vector2_multiplication_by_zero_yields_zeroes() { + let a = Vector2D(1.0, 2.0); + let b = 0.0; + let c = a * b; + assert!(c.0 == 0.0); + assert!(c.1 == 0.0); + } + + #[test] + fn test_vector2_multiplication_identity() { + let a = Vector2D(1.0, 2.0); + let b = 1.0; + let c = a * b; + assert!(c.0 == a.0); + assert!(c.1 == a.1); + } + + #[test] + fn test_vector2_multiplication_by_positive_float() { + let a = Vector2D(1.0, 2.0); + let b = 2.0; + let c = a * b; + assert!(c.0 == a.0 * 2.0); + assert!(c.1 == a.1 * 2.0); + } + + #[test] + fn test_vector2_multiplication_by_negative_float() { + let a = Vector2D(1.0, 2.0); + let b = -2.0; + let c = a * b; + assert!(c.0 == a.0 * -2.0); + assert!(c.1 == a.1 * -2.0); + } + + #[test] + fn test_vector2_multiplication_by_positive_int() { + let a = Vector2D(1, 2); + let b = 2; + let c = a * b; + assert!(c.0 == a.0 * 2); + assert!(c.1 == a.1 * 2); + } + + #[test] + fn test_vector2_multiplication_by_negative_int() { + let a = Vector2D(1, 2); + let b = -2; + let c = a * b; + assert!(c.0 == a.0 * -2); + assert!(c.1 == a.1 * -2); + } + #[test] fn test_vector3d_add_zeroes_yields_zeroes() { let a = Vector3D(0.0, 0.0, 0.0);