From 2067e270dcb80c155d570399a0177a021f9bd04f Mon Sep 17 00:00:00 2001 From: Ian Jackson Date: Sun, 8 May 2022 10:52:09 +0100 Subject: [PATCH] geometry: Rename pos_zip_try_map, add infallible pos_zip_map, use Signed-off-by: Ian Jackson --- base/geometry.rs | 44 +++++++++++++++++--------------------------- 1 file changed, 17 insertions(+), 27 deletions(-) diff --git a/base/geometry.rs b/base/geometry.rs index fcaed93a..e32362dd 100644 --- a/base/geometry.rs +++ b/base/geometry.rs @@ -99,7 +99,7 @@ impl PosPromote for PosC where T: Into + Copy + Debug { pub struct PosCFromIteratorError; display_as_debug!{PosCFromIteratorError} -macro_rules! pos_zip_map { { +macro_rules! pos_zip_try_map { { $( $input:expr ),* => $closure:expr } => { PosC::try_from_iter_2( @@ -107,6 +107,14 @@ macro_rules! pos_zip_map { { .map($closure) ) } } +macro_rules! pos_zip_map { { + $( $input:expr ),* => $closure:expr +} => { + PosC::from_iter_2( + izip!($( $input .coords(), )*) + .map($closure) + ) +} } impl PosC { pub const fn new(x: T, y: T) -> Self { PosC{ coords: [x,y] } } @@ -185,7 +193,7 @@ impl Add> for PosC { type Output = Result; #[throws(CoordinateOverflow)] fn add(self, rhs: PosC) -> PosC { - pos_zip_map!( self, rhs => |(a,b)| a.checked_add(b) )? + pos_zip_try_map!( self, rhs => |(a,b)| a.checked_add(b) )? } } @@ -193,12 +201,7 @@ impl Sub> for PosC { type Output = Result; #[throws(CoordinateOverflow)] fn sub(self, rhs: PosC) -> PosC { - PosC::try_from_iter_2( - itertools::zip_eq( - self.coords.iter().cloned(), - rhs .coords.iter().cloned(), - ).map(|(a,b)| a.checked_sub(b)) - )? + pos_zip_try_map!( self, rhs => |(a,b)| a.checked_sub(b) )? } } @@ -206,11 +209,7 @@ impl> Mul for PosC { type Output = Result; #[throws(CoordinateOverflow)] fn mul(self, rhs: S) -> PosC { - PosC::try_from_iter_2( - self.coords.iter().cloned().map( - |a| a.checked_mul(rhs) - ) - )? + pos_zip_try_map!( self => |a| a.checked_mul(rhs) )? } } @@ -218,17 +217,13 @@ impl Neg for PosC { type Output = Result; #[throws(CoordinateOverflow)] fn neg(self) -> Self { - PosC::try_from_iter_2( - self.coords.iter().cloned().map(|a| a.checked_neg()) - )? + pos_zip_try_map!( self => |a| a.checked_neg() )? } } impl PosC { pub fn map U>(self, f: F) -> PosC { - PosC::from_iter( - self.coords.iter().cloned().map(f) - ).unwrap() + pos_zip_map!( self => f ) } } @@ -236,18 +231,13 @@ impl PosC { pub fn try_map Result> (self, f: F) -> Result,E> { - PosC::try_from_iter_2( - self.coords.iter().cloned().map(f) - ) + pos_zip_try_map!( self => f ) } } -impl Mean for PosC where T: Mean + Debug { +impl Mean for PosC where T: Mean + Debug + Copy { fn mean(&self, other: &Self) -> Self where T: Mean { - PosC::from_iter_2( - izip!(&self.coords, &other.coords) - .map(|(a,b)| a.mean(b)) - ) + pos_zip_map!( self, other => |(a,b)| a.mean(&b) ) } } -- 2.30.2