From e77152ef1bd8eb23fabd8dcca7904b780eeaf58e Mon Sep 17 00:00:00 2001 From: Corwin Kuiper Date: Wed, 16 Jun 2021 19:14:22 +0100 Subject: [PATCH] better mul and div by integer for fixed num type --- agb/src/number.rs | 80 ++++++++++++++++++++++++++++++++++------------- 1 file changed, 58 insertions(+), 22 deletions(-) diff --git a/agb/src/number.rs b/agb/src/number.rs index a4f0238d..5325caac 100644 --- a/agb/src/number.rs +++ b/agb/src/number.rs @@ -144,49 +144,65 @@ where } } -impl Mul for Num +impl Mul> for Num where I: FixedWidthUnsignedInteger, - T: Into>, { type Output = Self; - fn mul(self, rhs: T) -> Self::Output { - let rhs: Self = rhs.into(); - + fn mul(self, rhs: Num) -> Self::Output { Num(((self.floor() * rhs.floor()) << N) + (self.floor() * rhs.frac() + rhs.floor() * self.frac()) + ((self.frac() * rhs.frac()) >> N)) } } -impl MulAssign for Num +impl Mul for Num where I: FixedWidthUnsignedInteger, - T: Into>, { - fn mul_assign(&mut self, rhs: T) { - self.0 = (*self * rhs.into()).0 + type Output = Self; + fn mul(self, rhs: I) -> Self::Output { + Num(self.0 * rhs) } } -impl Div for Num +impl MulAssign for Num +where + I: FixedWidthUnsignedInteger, + Num: Mul>, +{ + fn mul_assign(&mut self, rhs: T) { + self.0 = (*self * rhs).0 + } +} + +impl Div> for Num where I: FixedWidthUnsignedInteger, - T: Into>, { type Output = Self; - fn div(self, rhs: T) -> Self::Output { - Num((self.0 << N) / rhs.into().0) + fn div(self, rhs: Num) -> Self::Output { + Num((self.0 << N) / rhs.0) + } +} + +impl Div for Num +where + I: FixedWidthUnsignedInteger, +{ + type Output = Self; + fn div(self, rhs: I) -> Self::Output { + Num(self.0 / rhs) } } impl DivAssign for Num where I: FixedWidthUnsignedInteger, - T: Into>, + Num: Div>, { fn div_assign(&mut self, rhs: T) { - self.0 = (*self / rhs.into()).0 + self.0 = (*self / rhs).0 } } @@ -471,27 +487,47 @@ impl Add> for Vector2D { } } -impl> Mul for Vector2D { +impl Mul for Vector2D +where + T: Mul, +{ type Output = Vector2D; fn mul(self, rhs: U) -> Self::Output { Vector2D { - x: self.x * rhs.into(), - y: self.y * rhs.into(), + x: self.x * rhs, + y: self.y * rhs, } } } -impl> Div for Vector2D { +impl MulAssign for Vector2D +where + T: Mul, +{ + fn mul_assign(&mut self, rhs: U) { + let result = *self * rhs; + self.x = result.x; + self.y = result.y; + } +} + +impl Div for Vector2D +where + T: Div, +{ type Output = Vector2D; fn div(self, rhs: U) -> Self::Output { Vector2D { - x: self.x / rhs.into(), - y: self.y / rhs.into(), + x: self.x / rhs, + y: self.y / rhs, } } } -impl> DivAssign for Vector2D { +impl DivAssign for Vector2D +where + T: Div, +{ fn div_assign(&mut self, rhs: U) { let result = *self / rhs; self.x = result.x;