#![warn(missing_docs)]
#![cfg_attr(feature = "unstable", feature(core, zero_one))]
#![crate_name="itertools"]
use std::iter::{self, IntoIterator};
use std::fmt::Write;
use std::cmp::Ordering;
use std::fmt;
use std::hash::Hash;
pub use adaptors::{
Interleave,
InterleaveShortest,
Product,
PutBack,
PutBackN,
FnMap,
Batching,
GroupBy,
Step,
Merge,
MultiPeek,
TakeWhileRef,
WhileSome,
Coalesce,
CoalesceFn,
Combinations,
Unique,
UniqueBy,
};
#[cfg(feature = "unstable")]
pub use adaptors::EnumerateFrom;
pub use intersperse::Intersperse;
pub use islice::{ISlice};
pub use pad_tail::PadUsing;
pub use repeatn::RepeatN;
pub use rciter::RcIter;
pub use stride::Stride;
pub use stride::StrideMut;
pub use tee::Tee;
pub use times::Times;
pub use times::times;
pub use linspace::{linspace, Linspace};
pub use sources::{
RepeatCall,
Unfold,
};
pub use zip_longest::{ZipLongest, EitherOrBoth};
pub use ziptuple::{Zip};
#[cfg(feature = "unstable")]
pub use ziptrusted::{ZipTrusted, TrustedIterator};
mod adaptors;
mod intersperse;
mod islice;
mod linspace;
pub mod misc;
mod pad_tail;
mod rciter;
mod repeatn;
mod sources;
pub mod size_hint;
mod stride;
mod tee;
mod times;
mod zip_longest;
mod ziptuple;
#[cfg(feature = "unstable")]
mod ziptrusted;
pub type MapFn<I, B> where I: Iterator = iter::Map<I, fn(I::Item) -> B>;
pub type MergeAscend<I, J> where I: Iterator = Merge<I, J, fn(&I::Item, &I::Item) -> Ordering>;
#[macro_export]
macro_rules! iproduct {
($I:expr) => (
(::std::iter::IntoIterator::into_iter($I))
);
($I:expr, $J:expr) => (
$crate::Product::new(iproduct!($I), iproduct!($J))
);
($I:expr, $J:expr, $($K:expr),+) => (
{
let it = iproduct!($I, $J);
$(
let it = $crate::misc::FlatTuples::new(iproduct!(it, $K));
)*
it
}
);
}
#[macro_export]
macro_rules! izip {
($I:expr) => (
(::std::iter::IntoIterator::into_iter($I))
);
($($I:expr),*) => (
{
$crate::Zip::new(($(izip!($I)),*))
}
);
}
#[macro_export]
macro_rules! icompr {
($r:expr, $x:pat, $J:expr, $pred:expr) => (
($J).filter_map(|$x| if $pred { Some($r) } else { None })
);
($r:expr, $x:pat, $J:expr) => (
($J).filter_map(|$x| Some($r))
);
}
pub trait Itertools : Iterator {
fn interleave<J>(self, other: J) -> Interleave<Self, J::IntoIter> where
J: IntoIterator<Item=Self::Item>,
Self: Sized
{
Interleave::new(self, other.into_iter())
}
fn interleave_shortest<J>(self, other: J) -> InterleaveShortest<Self, J::IntoIter> where
J: IntoIterator<Item=Self::Item>,
Self: Sized
{
InterleaveShortest::new(self, other.into_iter())
}
fn intersperse(self, element: Self::Item) -> Intersperse<Self> where
Self: Sized,
Self::Item: Clone
{
Intersperse::new(self, element)
}
#[inline]
fn zip_longest<J>(self, other: J) -> ZipLongest<Self, J::IntoIter> where
J: IntoIterator,
Self: Sized,
{
ZipLongest::new(self, other.into_iter())
}
fn batching<B, F>(self, f: F) -> Batching<Self, F> where
F: FnMut(&mut Self) -> Option<B>,
Self: Sized,
{
Batching::new(self, f)
}
fn group_by<K, F: FnMut(&Self::Item) -> K>(self, key: F) -> GroupBy<K, Self, F> where
Self: Sized,
{
GroupBy::new(self, key)
}
fn tee(self) -> (Tee<Self>, Tee<Self>) where
Self: Sized,
Self::Item: Clone
{
tee::new(self)
}
fn slice<R>(self, range: R) -> ISlice<Self> where
R: misc::GenericRange,
Self: Sized,
{
ISlice::new(self, range)
}
fn into_rc(self) -> RcIter<Self> where
Self: Sized,
{
RcIter::new(self)
}
fn step(self, n: usize) -> Step<Self> where
Self: Sized,
{
Step::new(self, n)
}
fn merge<J>(self, other: J) -> MergeAscend<Self, J::IntoIter> where
Self: Sized,
Self::Item: PartialOrd,
J: IntoIterator<Item=Self::Item>,
{
fn wrapper<A: PartialOrd>(a: &A, b: &A) -> Ordering {
a.partial_cmp(b).unwrap_or(Ordering::Less)
};
self.merge_by(other, wrapper)
}
fn merge_by<J, F>(self, other: J, cmp: F) -> Merge<Self, J::IntoIter, F> where
Self: Sized,
J: IntoIterator<Item=Self::Item>,
F: FnMut(&Self::Item, &Self::Item) -> Ordering
{
Merge::new(self, other.into_iter(), cmp)
}
fn cartesian_product<J>(self, other: J) -> Product<Self, J::IntoIter> where
Self: Sized,
Self::Item: Clone,
J: IntoIterator,
J::IntoIter: Clone,
{
Product::new(self, other.into_iter())
}
#[cfg(feature = "unstable")]
fn enumerate_from<K>(self, start: K) -> EnumerateFrom<Self, K> where
Self: Sized,
{
EnumerateFrom::new(self, start)
}
fn multipeek(self) -> MultiPeek<Self> where
Self: Sized
{
MultiPeek::new(self)
}
fn coalesce<F>(self, f: F) -> Coalesce<Self, F> where
Self: Sized,
F: FnMut(Self::Item, Self::Item) -> Result<Self::Item, (Self::Item, Self::Item)>
{
Coalesce::new(self, f)
}
fn dedup(self) -> CoalesceFn<Self> where
Self: Sized,
Self::Item: PartialEq,
{
fn eq<T: PartialEq>(x: T, y: T) -> Result<T, (T, T)>
{
if x == y { Ok(x) } else { Err((x, y)) }
}
Coalesce::new(self, eq)
}
fn unique(self) -> Unique<Self> where
Self: Sized,
Self::Item: Clone + Eq + Hash,
{
self.unique_by(Clone::clone)
}
fn unique_by<V, F>(self, f: F) -> UniqueBy<Self, V, F> where
Self: Sized,
V: Eq + Hash,
F: FnMut(&Self::Item) -> V
{
UniqueBy::new(self, f)
}
fn mend_slices(self) -> CoalesceFn<Self> where
Self: Sized,
Self::Item: misc::MendSlice
{
Coalesce::new(self, misc::MendSlice::mend)
}
fn take_while_ref<'a, F>(&'a mut self, f: F) -> TakeWhileRef<'a, Self, F> where
Self: Clone,
F: FnMut(&Self::Item) -> bool,
{
TakeWhileRef::new(self, f)
}
fn while_some<A>(self) -> WhileSome<Self> where
Self: Sized + Iterator<Item=Option<A>>,
{
WhileSome::new(self)
}
fn combinations(self) -> Combinations<Self> where
Self: Sized + Clone, Self::Item: Clone
{
Combinations::new(self)
}
fn pad_using<F>(self, min: usize, f: F) -> PadUsing<Self, F> where
Self: Sized,
F: FnMut(usize) -> Self::Item,
{
PadUsing::new(self, min, f)
}
fn map_fn<B>(self, f: fn(Self::Item) -> B) -> MapFn<Self, B> where
Self: Sized
{
self.map(f)
}
fn fn_map<B>(self, map: fn(Self::Item) -> B) -> FnMap<B, Self> where
Self: Sized
{
FnMap::new(self, map)
}
fn find_position<P>(&mut self, mut pred: P) -> Option<(usize, Self::Item)> where
P: FnMut(&Self::Item) -> bool,
{
let mut index = 0usize;
for elt in self {
if pred(&elt) {
return Some((index, elt))
}
index += 1;
}
None
}
fn dropn(&mut self, mut n: usize) -> usize
{
let start = n;
while n > 0 {
match self.next() {
Some(..) => n -= 1,
None => break
}
}
start - n
}
fn dropping(mut self, n: usize) -> Self where
Self: Sized,
{
self.dropn(n);
self
}
fn dropping_back(mut self, n: usize) -> Self where
Self: Sized,
Self: DoubleEndedIterator,
{
self.by_ref().rev().dropn(n);
self
}
fn foreach<F>(&mut self, mut f: F) where
F: FnMut(Self::Item),
{
for elt in self { f(elt) }
}
fn collect_vec(self) -> Vec<Self::Item> where
Self: Sized,
{
self.collect()
}
#[inline]
fn set_from<'a, A: 'a, J>(&mut self, from: J) -> usize where
Self: Iterator<Item=&'a mut A>,
J: IntoIterator<Item=A>,
{
let mut count = 0;
for elt in from {
match self.next() {
None => break,
Some(ptr) => *ptr = elt
}
count += 1;
}
count
}
fn join(&mut self, sep: &str) -> String where
Self::Item: std::fmt::Display,
{
match self.next() {
None => String::new(),
Some(first_elt) => {
let (lower, _) = self.size_hint();
let mut result = String::with_capacity(sep.len() * lower);
write!(&mut result, "{}", first_elt).unwrap();
for elt in self {
result.push_str(sep);
write!(&mut result, "{}", elt).unwrap();
}
result
}
}
}
fn fold_results<A, E, B, F>(&mut self, mut start: B, mut f: F) -> Result<B, E> where
Self: Iterator<Item=Result<A, E>>,
F: FnMut(B, A) -> B,
{
for elt in self {
match elt {
Ok(v) => start = f(start, v),
Err(u) => return Err(u),
}
}
Ok(start)
}
fn fold1<F>(&mut self, mut f: F) -> Option<Self::Item> where
F: FnMut(Self::Item, Self::Item) -> Self::Item,
{
match self.next() {
None => None,
Some(mut x) => {
for y in self {
x = f(x, y);
}
Some(x)
}
}
}
fn is_empty_hint(&self) -> Option<bool>
{
let (low, opt_hi) = self.size_hint();
if let Some(hi) = opt_hi {
if hi < low { return None }
}
if opt_hi == Some(0) {
Some(true)
} else if low > 0 {
Some(false)
} else {
None
}
}
fn sort_by<F: FnMut(&Self::Item, &Self::Item) -> Ordering>(self, cmp: F) -> Vec<Self::Item> where
Self: Sized
{
let mut v: Vec<Self::Item> = self.collect();
v.sort_by(cmp);
v
}
}
impl<T: ?Sized> Itertools for T where T: Iterator { }
pub fn equal<I, J>(a: I, b: J) -> bool where
I: IntoIterator,
J: IntoIterator,
I::Item: PartialEq<J::Item>,
{
let mut ia = a.into_iter();
let mut ib = b.into_iter();
loop {
match (ia.next(), ib.next()) {
(Some(ref x), Some(ref y)) if x == y => { }
(None, None) => return true,
_ => return false,
}
}
}
pub fn assert_equal<I, J>(a: I, b: J)
where I: IntoIterator,
J: IntoIterator,
I::Item: fmt::Debug + PartialEq<J::Item>,
J::Item: fmt::Debug,
{
let mut ia = a.into_iter();
let mut ib = b.into_iter();
let mut i = 0;
loop {
match (ia.next(), ib.next()) {
(None, None) => return,
(a, b) => {
let equal = match (&a, &b) {
(&Some(ref a), &Some(ref b)) => a == b,
_ => false,
};
assert!(equal, "Failed assertion {a:?} == {b:?} for iteration {i}",
i=i, a=a, b=b);
i += 1;
}
}
}
}
pub fn partition<'a, A: 'a, I, F>(iter: I, mut pred: F) -> usize where
I: IntoIterator<Item=&'a mut A>,
I::IntoIter: DoubleEndedIterator,
F: FnMut(&A) -> bool,
{
let mut split_index = 0;
let mut iter = iter.into_iter();
'main: while let Some(front) = iter.next() {
if !pred(front) {
loop {
match iter.next_back() {
Some(back) => if pred(back) {
std::mem::swap(front, back);
break;
},
None => break 'main,
}
}
}
split_index += 1;
}
split_index
}