Skip to content
Closed
Show file tree
Hide file tree
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
39 changes: 39 additions & 0 deletions src/adaptors/map.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use core::iter::Peekable;
use std::iter::FromIterator;
use std::marker::PhantomData;

Expand Down Expand Up @@ -122,3 +123,41 @@ pub fn map_into<I, R>(iter: I) -> MapInto<I, R> {
f: MapSpecialCaseFnInto(PhantomData),
}
}

#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct PeekMap<I, F, U>
where
I: Iterator,
F: FnMut(I::Item, Option<&I::Item>) -> U,
{
iter: Peekable<I>,
f: F,
}

impl<I, F, U> Iterator for PeekMap<I, F, U>
where
I: Iterator,
F: FnMut(I::Item, Option<&I::Item>) -> U,
{
type Item = U;

fn next(&mut self) -> Option<Self::Item> {
Some((self.f)(self.iter.next()?, self.iter.peek()))
}

fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}

/// Create a new `PeekMap` iterator.
pub fn peek_map<I, F, U>(iter: I, f: F) -> PeekMap<I, F, U>
where
I: Iterator,
F: FnMut(I::Item, Option<&I::Item>) -> U,
{
PeekMap {
iter: iter.peekable(),
f,
}
}
2 changes: 1 addition & 1 deletion src/adaptors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ mod multi_product;
pub use self::coalesce::*;
#[allow(deprecated)]
pub use self::map::MapResults;
pub use self::map::{map_into, map_ok, MapInto, MapOk};
pub use self::map::{map_into, map_ok, peek_map, MapInto, MapOk, PeekMap};
#[cfg(feature = "use_alloc")]
pub use self::multi_product::*;

Expand Down
12 changes: 10 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ pub mod structs {
pub use crate::adaptors::MultiProduct;
pub use crate::adaptors::{
Batching, Coalesce, Dedup, DedupBy, DedupByWithCount, DedupWithCount, FilterMapOk,
FilterOk, Interleave, InterleaveShortest, MapInto, MapOk, Positions, Product, PutBack,
TakeWhileRef, TupleCombinations, Update, WhileSome,
FilterOk, Interleave, InterleaveShortest, MapInto, MapOk, PeekMap, Positions, Product,
PutBack, TakeWhileRef, TupleCombinations, Update, WhileSome,
};
#[allow(deprecated)]
pub use crate::adaptors::{MapResults, Step};
Expand Down Expand Up @@ -3964,6 +3964,14 @@ pub trait Itertools: Iterator {
_ => Err(sh),
}
}

fn peek_map<B, F>(self, f: F) -> PeekMap<Self, F, B>
where
Self: Sized,
F: FnMut(Self::Item, Option<&Self::Item>) -> B,
{
adaptors::peek_map(self, f)
}
}

impl<T: ?Sized> Itertools for T where T: Iterator {}
Expand Down