Feature idea: Add `peek_back` method on `Peekable<I> ` when `I: DoubleEndedIterator`

let iter = vec![1, 2, 3].into_iter().peekable();

assert_eq!(Some(1), iter.peek());
assert_eq!(Some(3), iter.peek_back());


This seems easy to implement, but a naive implementation would add a new internal field on Peekable which would store the back value, which would be unused in cases where I: !DoubleEndedIterator. Is there any way to avoid that?

If you only needed to peek the back but not the front could also do:

let mut iter = vec![1, 2, 3].into_iter().rev().peekable();

assert_eq!(Some(3), iter.peek());

To have double-ended peeking without overhead, you'd need a new adapter, but double_ended_peekable() is a bit of a mouthful!

It would also be unused in all existing cases peeking some I: DoubleEndedIterator, where the user only cares about forward iteration.

There's precedent for that though -- e.g. FlatMap has a field for reverse state that might never get used.

In my specific case, I did need to peek the front and back

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.