From 9677e6c4024cbf3b75c43d20949f47312f093dbd Mon Sep 17 00:00:00 2001 From: Bryan Hitchcock Date: Sun, 9 Jun 2024 00:32:25 -0400 Subject: [PATCH] Replace custom `advance_by` with `Iterator::nth` Previously, there was a comment stating that we must wait for [`Iterator::advance_by` to be stabilizied](https://github.com/rust-lang/rust/issues/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. --- src/iter/iter_mut.rs | 14 ++------------ src/iter/values_mut.rs | 16 ++++------------ 2 files changed, 6 insertions(+), 24 deletions(-) diff --git a/src/iter/iter_mut.rs b/src/iter/iter_mut.rs index f7c0eb4..6080218 100644 --- a/src/iter/iter_mut.rs +++ b/src/iter/iter_mut.rs @@ -31,28 +31,18 @@ impl<'a, T> Iterator for IterMut<'a, T> { fn next(&mut self) -> Option { // 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::*; diff --git a/src/iter/values_mut.rs b/src/iter/values_mut.rs index 1354047..77a0b1a 100644 --- a/src/iter/values_mut.rs +++ b/src/iter/values_mut.rs @@ -31,23 +31,15 @@ impl<'a, T> Iterator for ValuesMut<'a, T> { fn next(&mut self) -> Option { // 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() }) } }