-
Notifications
You must be signed in to change notification settings - Fork 13k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Peekable's .peek() does not remember seeing a None
#37784
Comments
I'd definitely argue that this is a bug in Peekable. |
possible fix: https://is.gd/JOnbyZ pub struct Peekable<I: Iterator> {
iter: I,
peeked: Option<Option<I::Item>>,
}
impl<I: Iterator> Iterator for Peekable<I> {
type Item = I::Item;
#[inline]
fn next(&mut self) -> Option<I::Item> {
match self.peeked.take() {
Some(v) => v,
None => self.iter.next()
}
}
}
impl<I: Iterator> Peekable<I> {
fn peek(&mut self) -> Option<&I::Item> {
if self.peeked.is_none() {
self.peeked = Some(self.iter.next());
}
match self.peeked {
Some(Some(ref value)) => Some(value),
Some(None) => None,
_ => unreachable!()
}
}
} |
I disagree. |
@Stebalien That depends on what category the .peek method is placed in. If this is fine, then "peek" counts as driving the iterator forward, and the user must take care to not call .next() after None is returned from .peek(). So I think this is about not if the iterator should remember it, but in particular the |
Ah, I see. I agree. Also note, any fix for this could be specialized on the underlying iterator implementing |
None
None
Make Peekable remember peeking a None Peekable should remember if a None has been seen in the `.peek()` method. It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the underlying iterator at most once. This does not by itself make the iterator fused. Thanks to @s3bk for the code in `fn peek()` itself. Fixes #37784
If you use
iterator.peekable()
, call.peek()
and seeNone
, peekable does not remember that.This means that the next call to either
.peek()
or.next()
will query the underlying iterator again, making it easy to create fusing bugs. (A well behaved iterator user should not call.next()
on a generic iterator that has already returnedNone
once.)Example program which ends up being an infinite loop (the while let loop). (playground link)
The text was updated successfully, but these errors were encountered: