Skip to content

Commit

Permalink
Replace custom advance_by with Iterator::nth
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bryanhitc committed Jun 9, 2024
1 parent 30aef07 commit 9677e6c
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 24 deletions.
14 changes: 2 additions & 12 deletions src/iter/iter_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,28 31,18 @@ impl<'a, T> Iterator for IterMut<'a, T> {
fn next(&mut self) -> Option<Self::Item> {
// Get the next index and update all cursors
let index = self.occupied.next()?;
let skip = match self.prev_index {
let relative_index = match self.prev_index.replace(index) {
None => 0,
Some(prev_index) => index - prev_index - 1,
};
self.prev_index = Some(index);
advance_by(&mut self.entries, skip);

// SAFETY: we just confirmed that there was in fact an entry at this index
self.entries
.next()
.nth(relative_index)
.map(|t| (index.into(), unsafe { t.assume_init_mut() }))
}
}

// TODO: Waiting for `Iterator::advance_by` to be stabilized
// https://github.com/rust-lang/rust/issues/77404
fn advance_by(iter: &mut impl Iterator, n: usize) {
for _ in 0..n {
iter.next();
}
}

#[cfg(test)]
mod test {
use super::*;
Expand Down
16 changes: 4 additions & 12 deletions src/iter/values_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 31,15 @@ impl<'a, T> Iterator for ValuesMut<'a, T> {
fn next(&mut self) -> Option<Self::Item> {
// Get the next index and update all cursors
let index = self.occupied.next()?;
let skip = match self.prev_index {
let relative_index = match self.prev_index.replace(index) {
None => 0,
Some(prev_index) => index - prev_index - 1,
};
self.prev_index = Some(index);
advance_by(&mut self.entries, skip);

// SAFETY: we just confirmed that there was in fact an entry at this index
self.entries.next().map(|t| unsafe { t.assume_init_mut() })
}
}

// TODO: Waiting for `Iterator::advance_by` to be stabilized
// https://github.com/rust-lang/rust/issues/77404
fn advance_by(iter: &mut impl Iterator, n: usize) {
for _ in 0..n {
iter.next();
self.entries
.nth(relative_index)
.map(|t| unsafe { t.assume_init_mut() })
}
}

Expand Down

0 comments on commit 9677e6c

Please sign in to comment.