Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::fmt;
- use std::iter::FusedIterator;
- #[derive(Clone)]
- pub struct MapWithSelf<I, F> {
- iter: I,
- f: F,
- }
- impl<I: fmt::Debug, F> fmt::Debug for MapWithSelf<I, F> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- f.debug_struct("MapWithSelf")
- .field("iter", &self.iter)
- .finish()
- }
- }
- impl<B, I: Iterator, F> Iterator for MapWithSelf<I, F>
- where
- F: FnMut(&I, I::Item) -> B,
- {
- type Item = B;
- #[inline]
- fn next(&mut self) -> Option<B> {
- self.iter.next().map(|n| (self.f)(&self.iter, n))
- }
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
- }
- }
- impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for MapWithSelf<I, F>
- where
- F: FnMut(&I, I::Item) -> B,
- {
- #[inline]
- fn next_back(&mut self) -> Option<B> {
- self.iter.next_back().map(|n| (self.f)(&self.iter, n))
- }
- }
- impl<B, I: ExactSizeIterator, F> ExactSizeIterator for MapWithSelf<I, F>
- where
- F: FnMut(&I, I::Item) -> B,
- {
- fn len(&self) -> usize {
- self.iter.len()
- }
- }
- impl<B, I: FusedIterator, F> FusedIterator for MapWithSelf<I, F> where F: FnMut(&I, I::Item) -> B {}
- pub trait MapWithSelfExt: Iterator {
- fn map_with_self<F, B>(self, f: F) -> MapWithSelf<Self, F>
- where
- Self: Sized,
- F: FnMut(&Self, Self::Item) -> B,
- {
- MapWithSelf { iter: self, f: f }
- }
- }
- impl<I: Iterator> MapWithSelfExt for I {}
Add Comment
Please, Sign In to add comment