1
0
Fork 0

vector2d: refactor indexing

This commit is contained in:
Matej Focko 2022-12-30 12:11:41 +01:00
parent 37a4fca618
commit b02e7207ac

View file

@ -1,7 +1,7 @@
use std::cmp::Eq; use std::cmp::Eq;
use std::fmt::Debug; use std::fmt::Debug;
use std::hash::Hash; use std::hash::Hash;
use std::ops::{Add, Mul, Sub}; use std::ops::{Add, Index, IndexMut, Mul, Sub};
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Vector2D<T> { pub struct Vector2D<T> {
@ -23,16 +23,28 @@ impl<T> Vector2D<T> {
} }
} }
pub fn index<'a, T, U>(v: &'a [Vec<U>], idx: &Vector2D<T>) -> &'a U pub fn index<'a, C, I>(v: &'a [C], idx: &Vector2D<I>) -> &'a C::Output
where where
usize: TryFrom<T>, I: Copy,
<usize as TryFrom<T>>::Error: Debug, C: Index<usize>,
T: Copy, usize: TryFrom<I>,
<usize as TryFrom<I>>::Error: Debug,
{ {
let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap()); let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());
&v[y][x] &v[y][x]
} }
pub fn index_mut<'a, C, I>(v: &'a mut [C], idx: &Vector2D<I>) -> &'a mut C::Output
where
I: Copy,
C: IndexMut<usize>,
usize: TryFrom<I>,
<usize as TryFrom<I>>::Error: Debug,
{
let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());
&mut v[y][x]
}
pub fn in_range<T, U>(v: &[Vec<U>], idx: &Vector2D<T>) -> bool pub fn in_range<T, U>(v: &[Vec<U>], idx: &Vector2D<T>) -> bool
where where
usize: TryInto<T>, usize: TryInto<T>,