add OffsetDimensionedSlice, with basic indexing operations

This commit is contained in:
2022-08-17 20:43:38 -07:00
parent ae5bfcf311
commit 694906aa32
2 changed files with 82 additions and 0 deletions

View File

@@ -1,5 +1,7 @@
mod dim_slice;
mod offset_dim_slice;
pub use dim_slice::{
DimensionedSlice,
DimIter,
};
pub use offset_dim_slice::OffsetDimensionedSlice;

View File

@@ -0,0 +1,80 @@
use core::ops::{Index, IndexMut};
use crate::dim::DimensionedSlice;
use crate::vec::Vec3u;
pub struct OffsetDimensionedSlice<T> {
offset: Vec3u,
inner: DimensionedSlice<T>,
}
impl<T> OffsetDimensionedSlice<T> {
pub fn new(offset: Vec3u, dim: Vec3u, items: T) -> Self {
Self { offset, inner: DimensionedSlice::new(dim, items) }
}
}
impl<T> Index<Vec3u> for OffsetDimensionedSlice<T>
where
DimensionedSlice<T>: Index<Vec3u>
{
type Output=<DimensionedSlice<T> as Index<Vec3u>>::Output;
fn index(&self, idx: Vec3u) -> &Self::Output {
&self.inner[idx - self.offset]
}
}
impl<T> IndexMut<Vec3u> for OffsetDimensionedSlice<T>
where
DimensionedSlice<T>: IndexMut<Vec3u>
{
fn index_mut(&mut self, idx: Vec3u) -> &mut Self::Output {
&mut self.inner[idx - self.offset]
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn offset_dim_slice_index() {
let data = [
0, 1, 2,
3, 4, 5,
0, 10,20,
30,40,50,
];
let s = OffsetDimensionedSlice::new(Vec3u::new(1, 2, 3), Vec3u::new(3, 2, 2), &data);
assert_eq!(s[Vec3u::new(1, 2, 3)], 0);
assert_eq!(s[Vec3u::new(2, 2, 3)], 1);
assert_eq!(s[Vec3u::new(2, 3, 3)], 4);
assert_eq!(s[Vec3u::new(2, 3, 4)], 40);
assert_eq!(s[Vec3u::new(3, 3, 4)], 50);
}
#[test]
fn offset_dim_slice_index_mut() {
let mut data = [
0, 1, 2,
3, 4, 5,
0, 10,20,
30,40,50,
];
let mut s = OffsetDimensionedSlice::new(Vec3u::new(1, 2, 3), Vec3u::new(3, 2, 2), &mut data);
s[Vec3u::new(1, 2, 3)] = 100;
s[Vec3u::new(1, 3, 4)] = 300;
assert_eq!(data, [
100,1, 2,
3, 4, 5,
0, 10, 20,
300,40,50,
]);
}
}