Skip to content

Commit 0ec6ede

Browse files
Muthserabluss
andcommitted
implement DoubleEndedIterator for 1d lanes
This is especially useful when one wants to iterate over rows or columns of a 2d array in reverse. Co-authored-by: Ulrik Sverdrup <[email protected]>
1 parent cd0a956 commit 0ec6ede

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/iterators/mod.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -732,6 +732,15 @@ where
732732
}
733733
}
734734

735+
impl<'a, A> DoubleEndedIterator for LanesIter<'a, A, Ix1>
736+
{
737+
fn next_back(&mut self) -> Option<Self::Item> {
738+
self.iter.next_back().map(|ptr| unsafe {
739+
ArrayView::new_(ptr, Ix1(self.inner_len), Ix1(self.inner_stride as Ix))
740+
})
741+
}
742+
}
743+
735744
// NOTE: LanesIterMut is a mutable iterator and must not expose aliasing
736745
// pointers. Due to this we use an empty slice for the raw data (it's unused
737746
// anyway).
@@ -772,6 +781,15 @@ where
772781
}
773782
}
774783

784+
impl<'a, A> DoubleEndedIterator for LanesIterMut<'a, A, Ix1>
785+
{
786+
fn next_back(&mut self) -> Option<Self::Item> {
787+
self.iter.next_back().map(|ptr| unsafe {
788+
ArrayViewMut::new_(ptr, Ix1(self.inner_len), Ix1(self.inner_stride as Ix))
789+
})
790+
}
791+
}
792+
775793
#[derive(Debug)]
776794
pub struct AxisIterCore<A, D> {
777795
/// Index along the axis of the value of `.next()`, relative to the start

tests/iterators.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,22 @@ fn double_ended() {
3939
assert_equal(aview1(&[1, 2, 3]).into_iter().rev(), [1, 2, 3].iter().rev());
4040
}
4141

42+
#[test]
43+
fn double_ended_rows() {
44+
let a = ArcArray::from_iter(0..8).reshape((4, 2));
45+
let mut row_it = a.rows().into_iter();
46+
assert_equal(row_it.next_back().unwrap(), &[6, 7]);
47+
assert_equal(row_it.next().unwrap(), &[0, 1]);
48+
assert_equal(row_it.next_back().unwrap(), &[4, 5]);
49+
assert_equal(row_it.next_back().unwrap(), &[2, 3]);
50+
assert!(row_it.next().is_none());
51+
assert!(row_it.next_back().is_none());
52+
53+
for (row, check) in a.rows().into_iter().rev().zip(&[[6, 7], [4, 5], [2, 3], [0, 1]]) {
54+
assert_equal(row, check);
55+
}
56+
}
57+
4258
#[test]
4359
fn iter_size_hint() {
4460
// Check that the size hint is correctly computed

0 commit comments

Comments
 (0)