Skip to content
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

Add Itertools::intersperse_with #381

Merged
merged 3 commits into from
Jun 18, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Add Itertools::intersperse_with
  • Loading branch information
gin-ahirsch committed May 4, 2020
commit 80c9487a771b5e6642ee9bdee88b49fea07c3b81
80 changes: 79 additions & 1 deletion src/intersperse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl<I> Iterator for Intersperse<I>
Self: Sized, F: FnMut(B, Self::Item) -> B,
{
let mut accum = init;

if let Some(x) = self.peek.take() {
accum = f(accum, x);
}
Expand All @@ -77,3 +77,81 @@ impl<I> Iterator for Intersperse<I>
})
}
}

/// An iterator adaptor to insert a particular value created by a function
/// between each element of the adapted iterator.
///
/// Iterator element type is `I::Item`
///
/// This iterator is *fused*.
///
/// See [`.intersperse_with()`](../trait.Itertools.html#method.intersperse_with) for more information.
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[derive(Debug)]
pub struct IntersperseWith<I, ElemF>
where I: Iterator,
ElemF: FnMut() -> I::Item,
{
element: ElemF,
iter: Fuse<I>,
peek: Option<I::Item>,
}

/// Create a new IntersperseWith iterator
pub fn intersperse_with<I, ElemF>(iter: I, elt: ElemF) -> IntersperseWith<I, ElemF>
where I: Iterator,
ElemF: FnMut() -> I::Item
{
let mut iter = iter.fuse();
IntersperseWith {
peek: iter.next(),
iter: iter,
element: elt,
}
}

impl<I, ElemF> Iterator for IntersperseWith<I, ElemF>
where I: Iterator,
ElemF: FnMut() -> I::Item
{
type Item = I::Item;
#[inline]
fn next(&mut self) -> Option<I::Item> {
if self.peek.is_some() {
self.peek.take()
} else {
self.peek = self.iter.next();
if self.peek.is_some() {
Some((self.element)())
} else {
None
}
}
}

fn size_hint(&self) -> (usize, Option<usize>) {
// 2 * SH + { 1 or 0 }
let has_peek = self.peek.is_some() as usize;
let sh = self.iter.size_hint();
size_hint::add_scalar(size_hint::add(sh, sh), has_peek)
}

fn fold<B, F>(mut self, init: B, mut f: F) -> B where
Self: Sized, F: FnMut(B, Self::Item) -> B,
{
let mut accum = init;

if let Some(x) = self.peek.take() {
accum = f(accum, x);
}

let element = &mut self.element;

self.iter.fold(accum,
|accum, x| {
let accum = f(accum, (element)());
let accum = f(accum, x);
accum
})
}
}
22 changes: 21 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub mod structs {
pub use crate::format::{Format, FormatWith};
#[cfg(feature = "use_std")]
pub use crate::groupbylazy::{IntoChunks, Chunk, Chunks, GroupBy, Group, Groups};
pub use crate::intersperse::Intersperse;
pub use crate::intersperse::{Intersperse, IntersperseWith};
#[cfg(feature = "use_std")]
pub use crate::kmerge_impl::{KMerge, KMergeBy};
pub use crate::merge_join::MergeJoinBy;
Expand Down Expand Up @@ -390,6 +390,26 @@ pub trait Itertools : Iterator {
intersperse::intersperse(self, element)
}

/// An iterator adaptor to insert a particular value created by a function
/// between each element of the adapted iterator.
///
/// Iterator element type is `Self::Item`.
///
/// This iterator is *fused*.
///
/// ```
/// use itertools::Itertools;
///
/// let mut i = 10;
/// itertools::assert_equal((0..3).intersperse_with(|| { i -= 1; i }), vec![0, 9, 1, 8, 2]);
/// ```
fn intersperse_with<F>(self, element: F) -> IntersperseWith<Self, F>
where Self: Sized,
F: FnMut() -> Self::Item
{
intersperse::intersperse_with(self, element)
}

/// Create an iterator which iterates over both this and the specified
/// iterator simultaneously, yielding pairs of two optional elements.
///
Expand Down