Skip to content

Commit 13b2736

Browse files
committed
Avoid index clone in next
There is an avoidable `clone` in `next`. This commit introduces `next_for_mut`, which is similar to `next_for`, but updates the key in-place, and uses it in `next` instead.
1 parent fd67f70 commit 13b2736

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/dimension/dimension_trait.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,6 @@ pub trait Dimension:
195195
#[doc(hidden)]
196196
/// Iteration -- Use self as size, and return next index after `index`
197197
/// or None if there are no more.
198-
// FIXME: use &Self for index or even &mut?
199198
#[inline]
200199
fn next_for(&self, index: Self) -> Option<Self>
201200
{
@@ -217,6 +216,24 @@ pub trait Dimension:
217216
}
218217
}
219218

219+
#[doc(hidden)]
220+
/// Iteration -- Similar to `next_for`, but addresses the index as mutable reference.
221+
#[inline]
222+
fn next_for_mut(&self, index: &mut Self) -> bool
223+
{
224+
let mut end_iteration = true;
225+
for (&dim, ix) in zip(self.slice(), index.slice_mut()).rev() {
226+
*ix += 1;
227+
if *ix == dim {
228+
*ix = 0;
229+
} else {
230+
end_iteration = false;
231+
break;
232+
}
233+
}
234+
!end_iteration
235+
}
236+
220237
#[doc(hidden)]
221238
/// Iteration -- Use self as size, and create the next index after `index`
222239
/// Return false if iteration is done

src/iterators/mod.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,12 @@ impl<A, D: Dimension> Iterator for Baseiter<A, D>
7474
{
7575
let index = match self.index {
7676
None => return None,
77-
Some(ref ix) => ix.clone(),
77+
Some(ref mut ix) => ix,
7878
};
7979
let offset = D::stride_offset(&index, &self.strides);
80-
self.index = self.dim.next_for(index);
80+
if !self.dim.next_for_mut(index) {
81+
self.index = None;
82+
}
8183
unsafe { Some(self.ptr.offset(offset)) }
8284
}
8385

0 commit comments

Comments
 (0)