From 87a0d44a8ade00c3912aeb45b1bae8d617d014bc Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Thu, 3 Dec 2026 13:05:54 -0700 Subject: [PATCH] improve Coord2d arithmetic implementation with macro --- 2026/utils/grid/lib.rs | 43 ++++++++++++++---------------------------- 1 file changed, 14 insertions(+), 29 deletions(-) diff --git a/2026/utils/grid/lib.rs b/2026/utils/grid/lib.rs index 82846b9..1ecb5ec 100644 --- a/2026/utils/grid/lib.rs +++ b/2026/utils/grid/lib.rs @@ -60,38 +60,23 @@ pub trait AsCoord2d { } } -impl Sub for &Coord2d { - type Output = Coord2d; - fn sub(self, rhs: T) -> Self::Output { - Coord2d { - x: self.x() - rhs.x(), - y: self.y() - rhs.y(), +// Implements `lhs rhs` for each listed lhs type, with any `AsCoord2d` on the right. +macro_rules! impl_coord_op { + ($trait:ident, $method:ident, $op:tt; $($lhs:ty),+) => {$( + impl $trait for $lhs { + type Output = Coord2d; + fn $method(self, rhs: T) -> Coord2d { + Coord2d { + x: self.x() $op rhs.x(), + y: self.y() $op rhs.y(), + } + } } - } + )+}; } -impl Add for &Coord2d -where - T: Copy, -{ - type Output = Coord2d; - fn add(self, rhs: T) -> Self::Output { - Coord2d { - x: self.x() + rhs.x(), - y: self.y() + rhs.y(), - } - } -} - -impl Add<&T> for Coord2d { - type Output = Coord2d; - fn add(self, rhs: &T) -> Self::Output { - Coord2d { - x: self.x() + rhs.x(), - y: self.y() + rhs.y(), - } - } -} +impl_coord_op!(Add, add, +; Coord2d, &Coord2d); +impl_coord_op!(Sub, sub, -; Coord2d, &Coord2d); impl AsCoord2d for Coord2d { fn to_coord(self) -> Coord2d {