cross: OffsetDimSlice: implement enumeration

This commit is contained in:
2022-08-17 21:41:26 -07:00
parent a34363122b
commit a0d4a39a66
2 changed files with 51 additions and 0 deletions

View File

@@ -17,6 +17,9 @@ impl<T> DimSlice<T> {
pub fn indices(&self) -> DimIter {
DimIter::new(self.dim)
}
pub fn dim(&self) -> Vec3u {
self.dim
}
}
#[cfg(feature = "iter")]

View File

@@ -1,3 +1,4 @@
use core::iter::Zip;
use core::ops::{Index, IndexMut};
use crate::dim::{DimIter, DimSlice};
@@ -18,6 +19,13 @@ impl<T> OffsetDimSlice<T> {
}
}
#[cfg(feature = "iter")]
impl<T: IntoIterator> OffsetDimSlice<T> {
pub fn enumerated(self) -> Zip<OffsetDimIter, T::IntoIter> {
self.indices().zip(self.into_iter())
}
}
impl<T> Index<Vec3u> for OffsetDimSlice<T>
where
DimSlice<T>: Index<Vec3u>
@@ -144,6 +152,46 @@ mod test {
assert_eq!(i.next().unwrap(), Vec3u::new(10, 20, 31));
assert_eq!(i.next().unwrap(), Vec3u::new(11, 20, 31));
assert_eq!(i.next(), None);
}
#[test]
fn offset_dim_slice_enumerated() {
let data = [
10, 11,
20, 21,
30, 31,
];
let s = OffsetDimSlice::new(Vec3u::new(10, 20, 30), Vec3u::new(1, 2, 2), &data);
let mut i = s.enumerated();
assert_eq!(i.next().unwrap(), (Vec3u::new(10, 20, 30), &10));
assert_eq!(i.next().unwrap(), (Vec3u::new(10, 21, 30), &11));
assert_eq!(i.next().unwrap(), (Vec3u::new(10, 20, 31), &20));
assert_eq!(i.next().unwrap(), (Vec3u::new(10, 21, 31), &21));
assert_eq!(i.next(), None);
}
#[test]
fn offset_dim_slice_enumerated_mut() {
let mut data = [
10, 11,
20, 21,
];
let s = OffsetDimSlice::new(Vec3u::new(10, 20, 30), Vec3u::new(2, 1, 2), &mut data);
let mut i = s.enumerated();
let (idx, v) = i.next().unwrap();
assert_eq!(idx, Vec3u::new(10, 20, 30));
*v = 100;
i.next().unwrap();
i.next().unwrap();
let (idx, v) = i.next().unwrap();
assert_eq!(idx, Vec3u::new(11, 20, 31));
*v = 210;
assert_eq!(i.next(), None);
assert_eq!(data, [100, 11, 20, 210]);
}
}