Skip to content

Commit 9677e6c

Browse files
committed
Replace custom advance_by with Iterator::nth
Previously, there was a comment stating that we must wait for [`Iterator::advance_by` to be stabilizied](rust-lang/rust#77404), but it makes more sense to use the [existing `Iterator::nth` method](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.nth) anyway, so I updated all callsites to use it. Depending on the iterator implementation, this could result in a performance improvement.
1 parent 30aef07 commit 9677e6c

File tree

2 files changed

+6
-24
lines changed

2 files changed

+6
-24
lines changed

src/iter/iter_mut.rs

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,28 +31,18 @@ impl<'a, T> Iterator for IterMut<'a, T> {
3131
fn next(&mut self) -> Option<Self::Item> {
3232
// Get the next index and update all cursors
3333
let index = self.occupied.next()?;
34-
let skip = match self.prev_index {
34+
let relative_index = match self.prev_index.replace(index) {
3535
None => 0,
3636
Some(prev_index) => index - prev_index - 1,
3737
};
38-
self.prev_index = Some(index);
39-
advance_by(&mut self.entries, skip);
4038

4139
// SAFETY: we just confirmed that there was in fact an entry at this index
4240
self.entries
43-
.next()
41+
.nth(relative_index)
4442
.map(|t| (index.into(), unsafe { t.assume_init_mut() }))
4543
}
4644
}
4745

48-
// TODO: Waiting for `Iterator::advance_by` to be stabilized
49-
// https://github.com/rust-lang/rust/issues/77404
50-
fn advance_by(iter: &mut impl Iterator, n: usize) {
51-
for _ in 0..n {
52-
iter.next();
53-
}
54-
}
55-
5646
#[cfg(test)]
5747
mod test {
5848
use super::*;

src/iter/values_mut.rs

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,23 +31,15 @@ impl<'a, T> Iterator for ValuesMut<'a, T> {
3131
fn next(&mut self) -> Option<Self::Item> {
3232
// Get the next index and update all cursors
3333
let index = self.occupied.next()?;
34-
let skip = match self.prev_index {
34+
let relative_index = match self.prev_index.replace(index) {
3535
None => 0,
3636
Some(prev_index) => index - prev_index - 1,
3737
};
38-
self.prev_index = Some(index);
39-
advance_by(&mut self.entries, skip);
4038

4139
// SAFETY: we just confirmed that there was in fact an entry at this index
42-
self.entries.next().map(|t| unsafe { t.assume_init_mut() })
43-
}
44-
}
45-
46-
// TODO: Waiting for `Iterator::advance_by` to be stabilized
47-
// https://github.com/rust-lang/rust/issues/77404
48-
fn advance_by(iter: &mut impl Iterator, n: usize) {
49-
for _ in 0..n {
50-
iter.next();
40+
self.entries
41+
.nth(relative_index)
42+
.map(|t| unsafe { t.assume_init_mut() })
5143
}
5244
}
5345

0 commit comments

Comments
 (0)