From 48b3f03d40ab457f1b872b25af3d0d8ec2e132e2 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Tue, 17 Mar 2020 13:55:49 +0100 Subject: [PATCH] library: core: color: add Mul-like ops by self --- src/core/color.rs | 65 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/src/core/color.rs b/src/core/color.rs index b48e082..05a5100 100644 --- a/src/core/color.rs +++ b/src/core/color.rs @@ -1,4 +1,5 @@ use derive_more::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; +use std::ops::{Div, DivAssign, Mul, MulAssign}; #[derive( Debug, Clone, PartialEq, Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign, @@ -30,6 +31,42 @@ impl Default for LinearColor { } } +impl Mul for LinearColor { + type Output = LinearColor; + + fn mul(self, other: Self) -> Self::Output { + LinearColor { + r: self.r * other.r, + g: self.g * other.g, + b: self.b * other.b, + } + } +} + +impl MulAssign for LinearColor { + fn mul_assign(&mut self, other: Self) { + *self = self.clone() * other + } +} + +impl Div for LinearColor { + type Output = LinearColor; + + fn div(self, other: Self) -> Self::Output { + LinearColor { + r: self.r / other.r, + g: self.g / other.g, + b: self.b / other.b, + } + } +} + +impl DivAssign for LinearColor { + fn div_assign(&mut self, other: Self) { + *self = self.clone() / other + } +} + #[cfg(test)] mod test { use super::*; @@ -145,6 +182,34 @@ mod test { ) } + #[test] + fn mul_by_color_works() { + let lhs = LinearColor::new(0.125, 0.25, 0.0625); + let rhs = LinearColor::new(1.0, 0.5, 2.0); + assert_eq!(lhs * rhs, LinearColor::new(0.125, 0.125, 0.125)) + } + + #[test] + fn div_by_color_works() { + let lhs = LinearColor::new(1.0, 0.5, 0.25); + let rhs = LinearColor::new(4.0, 2.0, 1.0); + assert_eq!(lhs / rhs, LinearColor::new(0.25, 0.25, 0.25)) + } + + #[test] + fn mulassign_by_color_works() { + let mut lhs = LinearColor::new(0.125, 0.25, 0.0625); + lhs *= LinearColor::new(1.0, 0.5, 2.0); + assert_eq!(lhs, LinearColor::new(0.125, 0.125, 0.125)) + } + + #[test] + fn divassign_by_color_works() { + let mut lhs = LinearColor::new(1.0, 0.5, 0.25); + lhs /= LinearColor::new(4.0, 2.0, 1.0); + assert_eq!(lhs, LinearColor::new(0.25, 0.25, 0.25)) + } + #[test] fn add_works() { let lhs = LinearColor::new(1., 0., 0.125);