Alternative implementation std::iter::Peekable::peek_mut #79419
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is an alternative implementation for
std::iter::Peekable::peek_mut()
, which has been added as an unstable featurepeekable_peek_mut
, tracked in #78302. Instead of returning anOption<&mut Item>
, we return an&mut Option<Item>
.This allows us to control the iterator without advancing it. Namely, we can short-circuit the iterator (ending it) conditionally without advancing the underlying iterator during inspection. We can also rejuvenate an empty iterator after inspecting the next value. Both would not be possible without peeking, as there would be no way to place the new value back into the iterator if it doesn't fit the pattern. E.g.
Both use-cases are already possible by simply calling
peek()
on the iterator and conditionally replacing the whole iterator (either the binding or throughstd::mem::replace
) with a new iterator. This is cumbersome, though, as we need to know the exact type of the iterator in case it's unboxed (replacing withstd::iter::empty
or::once
won't do).Since it previously wasn't possible to modify the state of
Peekable
from the outside, more tests may be needed to ensure that it behaves properly after it'speeked
-member was modified?!