Skip to content

Commit c4a1d3b

Browse files
committed
core: implement advance_by with try_fold
This can be faster for iterators where an optimized `try_fold` implementation is available.
1 parent be73c1f commit c4a1d3b

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

library/core/src/iter/traits/iterator.rs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -294,13 +294,20 @@ pub trait Iterator {
294294
#[inline]
295295
#[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
296296
fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
297-
for i in 0..n {
298-
if self.next().is_none() {
299-
// SAFETY: `i` is always less than `n`.
300-
return Err(unsafe { NonZero::new_unchecked(n - i) });
297+
if let Some(n) = NonZero::new(n) {
298+
// Drop all items until the count is zero.
299+
match self.try_fold(n, |n, item| {
300+
drop(item);
301+
NonZero::new(n.get() - 1)
302+
}) {
303+
// The count is zero, so we've advanced by n items.
304+
None => Ok(()),
305+
// There are still n steps remaining.
306+
Some(n) => Err(n),
301307
}
308+
} else {
309+
Ok(())
302310
}
303-
Ok(())
304311
}
305312

306313
/// Returns the `n`th element of the iterator.

0 commit comments

Comments
 (0)