Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions library/core/src/iter/adapters/fuse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::iter::adapters::zip::try_get_unchecked;
use crate::iter::{
FusedIterator, TrustedFused, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce,
};
use crate::num::NonZero;
use crate::ops::Try;

/// An iterator that yields `None` forever after the underlying iterator
Expand Down Expand Up @@ -50,6 +51,10 @@ where
FuseImpl::next(self)
}

fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
FuseImpl::advance_by(self, n)
}

#[inline]
fn nth(&mut self, n: usize) -> Option<I::Item> {
FuseImpl::nth(self, n)
Expand Down Expand Up @@ -259,6 +264,7 @@ trait FuseImpl<I> {

// Functions specific to any normal Iterators
fn next(&mut self) -> Option<Self::Item>;
fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>>;
fn nth(&mut self, n: usize) -> Option<Self::Item>;
fn try_fold<Acc, Fold, R>(&mut self, acc: Acc, fold: Fold) -> R
where
Expand Down Expand Up @@ -301,6 +307,22 @@ where
and_then_or_clear(&mut self.iter, Iterator::next)
}

#[inline]
default fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let Some(iter) = &mut self.iter else {
return match NonZero::new(n) {
Some(n) => Err(n),
None => Ok(()),
};
};

let res = iter.advance_by(n);
if res.is_err() {
self.iter = None;
}
res
}

#[inline]
default fn nth(&mut self, n: usize) -> Option<I::Item> {
and_then_or_clear(&mut self.iter, |iter| iter.nth(n))
Expand Down Expand Up @@ -381,6 +403,17 @@ where
self.iter.as_mut()?.next()
}

#[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
match &mut self.iter {
Some(iter) => iter.advance_by(n),
None => match NonZero::new(n) {
Some(n) => Err(n),
None => Ok(()),
},
}
}

#[inline]
fn nth(&mut self, n: usize) -> Option<I::Item> {
self.iter.as_mut()?.nth(n)
Expand Down
Loading