diff --git a/crates/cross/src/dim/mod.rs b/crates/cross/src/dim/mod.rs index d905c2d..d835112 100644 --- a/crates/cross/src/dim/mod.rs +++ b/crates/cross/src/dim/mod.rs @@ -1,5 +1,7 @@ mod dim_slice; +mod offset_dim_slice; pub use dim_slice::{ DimensionedSlice, DimIter, }; +pub use offset_dim_slice::OffsetDimensionedSlice; diff --git a/crates/cross/src/dim/offset_dim_slice.rs b/crates/cross/src/dim/offset_dim_slice.rs new file mode 100644 index 0000000..daa2300 --- /dev/null +++ b/crates/cross/src/dim/offset_dim_slice.rs @@ -0,0 +1,80 @@ +use core::ops::{Index, IndexMut}; + +use crate::dim::DimensionedSlice; +use crate::vec::Vec3u; + + +pub struct OffsetDimensionedSlice { + offset: Vec3u, + inner: DimensionedSlice, +} + +impl OffsetDimensionedSlice { + pub fn new(offset: Vec3u, dim: Vec3u, items: T) -> Self { + Self { offset, inner: DimensionedSlice::new(dim, items) } + } +} + +impl Index for OffsetDimensionedSlice +where + DimensionedSlice: Index +{ + type Output= as Index>::Output; + + fn index(&self, idx: Vec3u) -> &Self::Output { + &self.inner[idx - self.offset] + } +} + +impl IndexMut for OffsetDimensionedSlice +where + DimensionedSlice: IndexMut +{ + 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, + ]); + } +}