File tree Expand file tree Collapse file tree 1 file changed +12
-5
lines changed
library/core/src/iter/traits Expand file tree Collapse file tree 1 file changed +12
-5
lines changed Original file line number Diff line number Diff 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.
You can’t perform that action at this time.
0 commit comments