From fa7cc5c241ac644710b2fda7a125b8d8cc62e5ae Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 8 Dec 2022 16:02:14 +0100 Subject: [PATCH] vector2d: implement few traits and helpers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit • Derive ordering • Implement indexing over 2D Vec with a ‹Vector2D› • Implement boundary checks for ‹Vector2D› indices over 2D Vec • Implement ‹swap› on ‹Vector2D› • Implement dot product and scalar product for ‹Vector2D› Signed-off-by: Matej Focko --- src/vector2d.rs | 74 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 72 insertions(+), 2 deletions(-) diff --git a/src/vector2d.rs b/src/vector2d.rs index 28b3f16..d89bb15 100644 --- a/src/vector2d.rs +++ b/src/vector2d.rs @@ -1,8 +1,9 @@ use std::cmp::Eq; +use std::fmt::Debug; use std::hash::Hash; -use std::ops::Add; +use std::ops::{Add, Mul}; -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Vector2D { x: T, y: T, @@ -22,6 +23,53 @@ impl Vector2D { } } +pub fn index<'a, T, U>(v: &'a [Vec], idx: &Vector2D) -> &'a U +where + usize: TryFrom, + >::Error: Debug, + T: Copy, +{ + let (x, y): (usize, usize) = (idx.y.try_into().unwrap(), idx.x.try_into().unwrap()); + &v[y][x] +} + +pub fn in_range(v: &Vec>, idx: &Vector2D) -> bool +where + usize: TryInto, + >::Error: Debug, + usize: TryFrom, + >::Error: Debug, + T: PartialOrd + Copy, +{ + idx.y >= 0.try_into().unwrap() + && idx.y < v.len().try_into().unwrap() + && idx.x >= 0.try_into().unwrap() + && idx.x + < v[TryInto::::try_into(idx.y).unwrap()] + .len() + .try_into() + .unwrap() +} + +impl Vector2D { + pub fn swap(&self) -> Self { + Self { + x: self.y, + y: self.x, + } + } +} + +// See: https://github.com/rust-lang/rust/issues/102731 +// impl, T> From> for Vector2D { +// fn from(value: Vector2D) -> Self { +// Self { +// x: U::from(value.x), +// y: U::from(value.y), +// } +// } +// } + impl, U> Add for Vector2D { type Output = Vector2D; @@ -32,3 +80,25 @@ impl, U> Add for Vector2D { } } } + +impl, U> Mul for Vector2D { + type Output = Vector2D; + + fn mul(self, rhs: Self) -> Self::Output { + Vector2D { + x: self.x * rhs.x, + y: self.y * rhs.y, + } + } +} + +impl + Copy, U> Mul for Vector2D { + type Output = Vector2D; + + fn mul(self, rhs: T) -> Self::Output { + Vector2D { + x: self.x * rhs, + y: self.y * rhs, + } + } +}