1 //! Licensed under the Apache License, Version 2.0
2 //! http://www.apache.org/licenses/LICENSE-2.0 or the MIT license
3 //! http://opensource.org/licenses/MIT, at your
4 //! option. This file may not be copied, modified, or distributed
5 //! except according to those terms.
6 
7 mod coalesce;
8 mod map;
9 mod multi_product;
10 pub use self::coalesce::*;
11 pub use self::map::{map_into, map_ok, MapInto, MapOk};
12 #[allow(deprecated)]
13 pub use self::map::MapResults;
14 #[cfg(feature = "use_alloc")]
15 pub use self::multi_product::*;
16 
17 use std::fmt;
18 use std::iter::{Fuse, Peekable, FromIterator};
19 use std::marker::PhantomData;
20 use crate::size_hint;
21 
22 /// An iterator adaptor that alternates elements from two iterators until both
23 /// run out.
24 ///
25 /// This iterator is *fused*.
26 ///
27 /// See [`.interleave()`](../trait.Itertools.html#method.interleave) for more information.
28 #[derive(Clone, Debug)]
29 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
30 pub struct Interleave<I, J> {
31     a: Fuse<I>,
32     b: Fuse<J>,
33     flag: bool,
34 }
35 
36 /// Create an iterator that interleaves elements in `i` and `j`.
37 ///
38 /// `IntoIterator` enabled version of `i.interleave(j)`.
39 ///
40 /// See [`.interleave()`](trait.Itertools.html#method.interleave) for more information.
interleave<I, J>(i: I, j: J) -> Interleave<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter> where I: IntoIterator, J: IntoIterator<Item = I::Item>41 pub fn interleave<I, J>(i: I, j: J) -> Interleave<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter>
42     where I: IntoIterator,
43           J: IntoIterator<Item = I::Item>
44 {
45     Interleave {
46         a: i.into_iter().fuse(),
47         b: j.into_iter().fuse(),
48         flag: false,
49     }
50 }
51 
52 impl<I, J> Iterator for Interleave<I, J>
53     where I: Iterator,
54           J: Iterator<Item = I::Item>
55 {
56     type Item = I::Item;
57     #[inline]
next(&mut self) -> Option<Self::Item>58     fn next(&mut self) -> Option<Self::Item> {
59         self.flag = !self.flag;
60         if self.flag {
61             match self.a.next() {
62                 None => self.b.next(),
63                 r => r,
64             }
65         } else {
66             match self.b.next() {
67                 None => self.a.next(),
68                 r => r,
69             }
70         }
71     }
72 
size_hint(&self) -> (usize, Option<usize>)73     fn size_hint(&self) -> (usize, Option<usize>) {
74         size_hint::add(self.a.size_hint(), self.b.size_hint())
75     }
76 }
77 
78 /// An iterator adaptor that alternates elements from the two iterators until
79 /// one of them runs out.
80 ///
81 /// This iterator is *fused*.
82 ///
83 /// See [`.interleave_shortest()`](../trait.Itertools.html#method.interleave_shortest)
84 /// for more information.
85 #[derive(Clone, Debug)]
86 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
87 pub struct InterleaveShortest<I, J>
88     where I: Iterator,
89           J: Iterator<Item = I::Item>
90 {
91     it0: I,
92     it1: J,
93     phase: bool, // false ==> it0, true ==> it1
94 }
95 
96 /// Create a new `InterleaveShortest` iterator.
interleave_shortest<I, J>(a: I, b: J) -> InterleaveShortest<I, J> where I: Iterator, J: Iterator<Item = I::Item>97 pub fn interleave_shortest<I, J>(a: I, b: J) -> InterleaveShortest<I, J>
98     where I: Iterator,
99           J: Iterator<Item = I::Item>
100 {
101     InterleaveShortest {
102         it0: a,
103         it1: b,
104         phase: false,
105     }
106 }
107 
108 impl<I, J> Iterator for InterleaveShortest<I, J>
109     where I: Iterator,
110           J: Iterator<Item = I::Item>
111 {
112     type Item = I::Item;
113 
114     #[inline]
next(&mut self) -> Option<Self::Item>115     fn next(&mut self) -> Option<Self::Item> {
116         let e = if self.phase { self.it1.next() } else { self.it0.next() };
117         if e.is_some() {
118             self.phase = !self.phase;
119         }
120         e
121     }
122 
123     #[inline]
size_hint(&self) -> (usize, Option<usize>)124     fn size_hint(&self) -> (usize, Option<usize>) {
125         let (curr_hint, next_hint) = {
126             let it0_hint = self.it0.size_hint();
127             let it1_hint = self.it1.size_hint();
128             if self.phase {
129                 (it1_hint, it0_hint)
130             } else {
131                 (it0_hint, it1_hint)
132             }
133         };
134         let (curr_lower, curr_upper) = curr_hint;
135         let (next_lower, next_upper) = next_hint;
136         let (combined_lower, combined_upper) =
137             size_hint::mul_scalar(size_hint::min(curr_hint, next_hint), 2);
138         let lower =
139             if curr_lower > next_lower {
140                 combined_lower + 1
141             } else {
142                 combined_lower
143             };
144         let upper = {
145             let extra_elem = match (curr_upper, next_upper) {
146                 (_, None) => false,
147                 (None, Some(_)) => true,
148                 (Some(curr_max), Some(next_max)) => curr_max > next_max,
149             };
150             if extra_elem {
151                 combined_upper.and_then(|x| x.checked_add(1))
152             } else {
153                 combined_upper
154             }
155         };
156         (lower, upper)
157     }
158 }
159 
160 #[derive(Clone, Debug)]
161 /// An iterator adaptor that allows putting back a single
162 /// item to the front of the iterator.
163 ///
164 /// Iterator element type is `I::Item`.
165 pub struct PutBack<I>
166     where I: Iterator
167 {
168     top: Option<I::Item>,
169     iter: I,
170 }
171 
172 /// Create an iterator where you can put back a single item
put_back<I>(iterable: I) -> PutBack<I::IntoIter> where I: IntoIterator173 pub fn put_back<I>(iterable: I) -> PutBack<I::IntoIter>
174     where I: IntoIterator
175 {
176     PutBack {
177         top: None,
178         iter: iterable.into_iter(),
179     }
180 }
181 
182 impl<I> PutBack<I>
183     where I: Iterator
184 {
185     /// put back value `value` (builder method)
with_value(mut self, value: I::Item) -> Self186     pub fn with_value(mut self, value: I::Item) -> Self {
187         self.put_back(value);
188         self
189     }
190 
191     /// Split the `PutBack` into its parts.
192     #[inline]
into_parts(self) -> (Option<I::Item>, I)193     pub fn into_parts(self) -> (Option<I::Item>, I) {
194         let PutBack{top, iter} = self;
195         (top, iter)
196     }
197 
198     /// Put back a single value to the front of the iterator.
199     ///
200     /// If a value is already in the put back slot, it is overwritten.
201     #[inline]
put_back(&mut self, x: I::Item)202     pub fn put_back(&mut self, x: I::Item) {
203         self.top = Some(x)
204     }
205 }
206 
207 impl<I> Iterator for PutBack<I>
208     where I: Iterator
209 {
210     type Item = I::Item;
211     #[inline]
next(&mut self) -> Option<Self::Item>212     fn next(&mut self) -> Option<Self::Item> {
213         match self.top {
214             None => self.iter.next(),
215             ref mut some => some.take(),
216         }
217     }
218     #[inline]
size_hint(&self) -> (usize, Option<usize>)219     fn size_hint(&self) -> (usize, Option<usize>) {
220         // Not ExactSizeIterator because size may be larger than usize
221         size_hint::add_scalar(self.iter.size_hint(), self.top.is_some() as usize)
222     }
223 
count(self) -> usize224     fn count(self) -> usize {
225         self.iter.count() + (self.top.is_some() as usize)
226     }
227 
last(self) -> Option<Self::Item>228     fn last(self) -> Option<Self::Item> {
229         self.iter.last().or(self.top)
230     }
231 
nth(&mut self, n: usize) -> Option<Self::Item>232     fn nth(&mut self, n: usize) -> Option<Self::Item> {
233         match self.top {
234             None => self.iter.nth(n),
235             ref mut some => {
236                 if n == 0 {
237                     some.take()
238                 } else {
239                     *some = None;
240                     self.iter.nth(n - 1)
241                 }
242             }
243         }
244     }
245 
all<G>(&mut self, mut f: G) -> bool where G: FnMut(Self::Item) -> bool246     fn all<G>(&mut self, mut f: G) -> bool
247         where G: FnMut(Self::Item) -> bool
248     {
249         if let Some(elt) = self.top.take() {
250             if !f(elt) {
251                 return false;
252             }
253         }
254         self.iter.all(f)
255     }
256 
fold<Acc, G>(mut self, init: Acc, mut f: G) -> Acc where G: FnMut(Acc, Self::Item) -> Acc,257     fn fold<Acc, G>(mut self, init: Acc, mut f: G) -> Acc
258         where G: FnMut(Acc, Self::Item) -> Acc,
259     {
260         let mut accum = init;
261         if let Some(elt) = self.top.take() {
262             accum = f(accum, elt);
263         }
264         self.iter.fold(accum, f)
265     }
266 }
267 
268 #[derive(Debug, Clone)]
269 /// An iterator adaptor that iterates over the cartesian product of
270 /// the element sets of two iterators `I` and `J`.
271 ///
272 /// Iterator element type is `(I::Item, J::Item)`.
273 ///
274 /// See [`.cartesian_product()`](../trait.Itertools.html#method.cartesian_product) for more information.
275 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
276 pub struct Product<I, J>
277     where I: Iterator
278 {
279     a: I,
280     a_cur: Option<I::Item>,
281     b: J,
282     b_orig: J,
283 }
284 
285 /// Create a new cartesian product iterator
286 ///
287 /// Iterator element type is `(I::Item, J::Item)`.
cartesian_product<I, J>(mut i: I, j: J) -> Product<I, J> where I: Iterator, J: Clone + Iterator, I::Item: Clone288 pub fn cartesian_product<I, J>(mut i: I, j: J) -> Product<I, J>
289     where I: Iterator,
290           J: Clone + Iterator,
291           I::Item: Clone
292 {
293     Product {
294         a_cur: i.next(),
295         a: i,
296         b: j.clone(),
297         b_orig: j,
298     }
299 }
300 
301 impl<I, J> Iterator for Product<I, J>
302     where I: Iterator,
303           J: Clone + Iterator,
304           I::Item: Clone
305 {
306     type Item = (I::Item, J::Item);
307 
next(&mut self) -> Option<Self::Item>308     fn next(&mut self) -> Option<Self::Item> {
309         let elt_b = match self.b.next() {
310             None => {
311                 self.b = self.b_orig.clone();
312                 match self.b.next() {
313                     None => return None,
314                     Some(x) => {
315                         self.a_cur = self.a.next();
316                         x
317                     }
318                 }
319             }
320             Some(x) => x
321         };
322         match self.a_cur {
323             None => None,
324             Some(ref a) => {
325                 Some((a.clone(), elt_b))
326             }
327         }
328     }
329 
size_hint(&self) -> (usize, Option<usize>)330     fn size_hint(&self) -> (usize, Option<usize>) {
331         let has_cur = self.a_cur.is_some() as usize;
332         // Not ExactSizeIterator because size may be larger than usize
333         let (b_min, b_max) = self.b.size_hint();
334 
335         // Compute a * b_orig + b for both lower and upper bound
336         size_hint::add(
337             size_hint::mul(self.a.size_hint(), self.b_orig.size_hint()),
338             (b_min * has_cur, b_max.map(move |x| x * has_cur)))
339     }
340 
fold<Acc, G>(mut self, mut accum: Acc, mut f: G) -> Acc where G: FnMut(Acc, Self::Item) -> Acc,341     fn fold<Acc, G>(mut self, mut accum: Acc, mut f: G) -> Acc
342         where G: FnMut(Acc, Self::Item) -> Acc,
343     {
344         // use a split loop to handle the loose a_cur as well as avoiding to
345         // clone b_orig at the end.
346         if let Some(mut a) = self.a_cur.take() {
347             let mut b = self.b;
348             loop {
349                 accum = b.fold(accum, |acc, elt| f(acc, (a.clone(), elt)));
350 
351                 // we can only continue iterating a if we had a first element;
352                 if let Some(next_a) = self.a.next() {
353                     b = self.b_orig.clone();
354                     a = next_a;
355                 } else {
356                     break;
357                 }
358             }
359         }
360         accum
361     }
362 }
363 
364 /// A “meta iterator adaptor”. Its closure receives a reference to the iterator
365 /// and may pick off as many elements as it likes, to produce the next iterator element.
366 ///
367 /// Iterator element type is *X*, if the return type of `F` is *Option\<X\>*.
368 ///
369 /// See [`.batching()`](../trait.Itertools.html#method.batching) for more information.
370 #[derive(Clone)]
371 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
372 pub struct Batching<I, F> {
373     f: F,
374     iter: I,
375 }
376 
377 impl<I, F> fmt::Debug for Batching<I, F> where I: fmt::Debug {
378     debug_fmt_fields!(Batching, iter);
379 }
380 
381 /// Create a new Batching iterator.
batching<I, F>(iter: I, f: F) -> Batching<I, F>382 pub fn batching<I, F>(iter: I, f: F) -> Batching<I, F> {
383     Batching { f, iter }
384 }
385 
386 impl<B, F, I> Iterator for Batching<I, F>
387     where I: Iterator,
388           F: FnMut(&mut I) -> Option<B>
389 {
390     type Item = B;
391     #[inline]
next(&mut self) -> Option<Self::Item>392     fn next(&mut self) -> Option<Self::Item> {
393         (self.f)(&mut self.iter)
394     }
395 }
396 
397 /// An iterator adaptor that steps a number elements in the base iterator
398 /// for each iteration.
399 ///
400 /// The iterator steps by yielding the next element from the base iterator,
401 /// then skipping forward *n-1* elements.
402 ///
403 /// See [`.step()`](../trait.Itertools.html#method.step) for more information.
404 #[deprecated(note="Use std .step_by() instead", since="0.8.0")]
405 #[allow(deprecated)]
406 #[derive(Clone, Debug)]
407 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
408 pub struct Step<I> {
409     iter: Fuse<I>,
410     skip: usize,
411 }
412 
413 /// Create a `Step` iterator.
414 ///
415 /// **Panics** if the step is 0.
416 #[allow(deprecated)]
step<I>(iter: I, step: usize) -> Step<I> where I: Iterator417 pub fn step<I>(iter: I, step: usize) -> Step<I>
418     where I: Iterator
419 {
420     assert!(step != 0);
421     Step {
422         iter: iter.fuse(),
423         skip: step - 1,
424     }
425 }
426 
427 #[allow(deprecated)]
428 impl<I> Iterator for Step<I>
429     where I: Iterator
430 {
431     type Item = I::Item;
432     #[inline]
next(&mut self) -> Option<Self::Item>433     fn next(&mut self) -> Option<Self::Item> {
434         let elt = self.iter.next();
435         if self.skip > 0 {
436             self.iter.nth(self.skip - 1);
437         }
438         elt
439     }
440 
size_hint(&self) -> (usize, Option<usize>)441     fn size_hint(&self) -> (usize, Option<usize>) {
442         let (low, high) = self.iter.size_hint();
443         let div = |x: usize| {
444             if x == 0 {
445                 0
446             } else {
447                 1 + (x - 1) / (self.skip + 1)
448             }
449         };
450         (div(low), high.map(div))
451     }
452 }
453 
454 // known size
455 #[allow(deprecated)]
456 impl<I> ExactSizeIterator for Step<I>
457     where I: ExactSizeIterator
458 {}
459 
460 pub trait MergePredicate<T> {
merge_pred(&mut self, a: &T, b: &T) -> bool461     fn merge_pred(&mut self, a: &T, b: &T) -> bool;
462 }
463 
464 #[derive(Clone)]
465 pub struct MergeLte;
466 
467 impl<T: PartialOrd> MergePredicate<T> for MergeLte {
merge_pred(&mut self, a: &T, b: &T) -> bool468     fn merge_pred(&mut self, a: &T, b: &T) -> bool {
469         a <= b
470     }
471 }
472 
473 /// An iterator adaptor that merges the two base iterators in ascending order.
474 /// If both base iterators are sorted (ascending), the result is sorted.
475 ///
476 /// Iterator element type is `I::Item`.
477 ///
478 /// See [`.merge()`](../trait.Itertools.html#method.merge_by) for more information.
479 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
480 pub type Merge<I, J> = MergeBy<I, J, MergeLte>;
481 
482 /// Create an iterator that merges elements in `i` and `j`.
483 ///
484 /// `IntoIterator` enabled version of `i.merge(j)`.
485 ///
486 /// ```
487 /// use itertools::merge;
488 ///
489 /// for elt in merge(&[1, 2, 3], &[2, 3, 4]) {
490 ///     /* loop body */
491 /// }
492 /// ```
merge<I, J>(i: I, j: J) -> Merge<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter> where I: IntoIterator, J: IntoIterator<Item = I::Item>, I::Item: PartialOrd493 pub fn merge<I, J>(i: I, j: J) -> Merge<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter>
494     where I: IntoIterator,
495           J: IntoIterator<Item = I::Item>,
496           I::Item: PartialOrd
497 {
498     merge_by_new(i, j, MergeLte)
499 }
500 
501 /// An iterator adaptor that merges the two base iterators in ascending order.
502 /// If both base iterators are sorted (ascending), the result is sorted.
503 ///
504 /// Iterator element type is `I::Item`.
505 ///
506 /// See [`.merge_by()`](../trait.Itertools.html#method.merge_by) for more information.
507 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
508 pub struct MergeBy<I, J, F>
509     where I: Iterator,
510           J: Iterator<Item = I::Item>
511 {
512     a: Peekable<I>,
513     b: Peekable<J>,
514     fused: Option<bool>,
515     cmp: F,
516 }
517 
518 impl<I, J, F> fmt::Debug for MergeBy<I, J, F>
519     where I: Iterator + fmt::Debug, J: Iterator<Item = I::Item> + fmt::Debug,
520           I::Item: fmt::Debug,
521 {
522     debug_fmt_fields!(MergeBy, a, b);
523 }
524 
525 impl<T, F: FnMut(&T, &T)->bool> MergePredicate<T> for F {
merge_pred(&mut self, a: &T, b: &T) -> bool526     fn merge_pred(&mut self, a: &T, b: &T) -> bool {
527         self(a, b)
528     }
529 }
530 
531 /// Create a `MergeBy` iterator.
merge_by_new<I, J, F>(a: I, b: J, cmp: F) -> MergeBy<I::IntoIter, J::IntoIter, F> where I: IntoIterator, J: IntoIterator<Item = I::Item>, F: MergePredicate<I::Item>,532 pub fn merge_by_new<I, J, F>(a: I, b: J, cmp: F) -> MergeBy<I::IntoIter, J::IntoIter, F>
533     where I: IntoIterator,
534           J: IntoIterator<Item = I::Item>,
535           F: MergePredicate<I::Item>,
536 {
537     MergeBy {
538         a: a.into_iter().peekable(),
539         b: b.into_iter().peekable(),
540         fused: None,
541         cmp,
542     }
543 }
544 
545 impl<I, J, F> Clone for MergeBy<I, J, F>
546     where I: Iterator,
547           J: Iterator<Item = I::Item>,
548           Peekable<I>: Clone,
549           Peekable<J>: Clone,
550           F: Clone
551 {
552     clone_fields!(a, b, fused, cmp);
553 }
554 
555 impl<I, J, F> Iterator for MergeBy<I, J, F>
556     where I: Iterator,
557           J: Iterator<Item = I::Item>,
558           F: MergePredicate<I::Item>
559 {
560     type Item = I::Item;
561 
next(&mut self) -> Option<Self::Item>562     fn next(&mut self) -> Option<Self::Item> {
563         let less_than = match self.fused {
564             Some(lt) => lt,
565             None => match (self.a.peek(), self.b.peek()) {
566                 (Some(a), Some(b)) => self.cmp.merge_pred(a, b),
567                 (Some(_), None) => {
568                     self.fused = Some(true);
569                     true
570                 }
571                 (None, Some(_)) => {
572                     self.fused = Some(false);
573                     false
574                 }
575                 (None, None) => return None,
576             }
577         };
578         if less_than {
579             self.a.next()
580         } else {
581             self.b.next()
582         }
583     }
584 
size_hint(&self) -> (usize, Option<usize>)585     fn size_hint(&self) -> (usize, Option<usize>) {
586         // Not ExactSizeIterator because size may be larger than usize
587         size_hint::add(self.a.size_hint(), self.b.size_hint())
588     }
589 }
590 
591 /// An iterator adaptor that borrows from a `Clone`-able iterator
592 /// to only pick off elements while the predicate returns `true`.
593 ///
594 /// See [`.take_while_ref()`](../trait.Itertools.html#method.take_while_ref) for more information.
595 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
596 pub struct TakeWhileRef<'a, I: 'a, F> {
597     iter: &'a mut I,
598     f: F,
599 }
600 
601 impl<'a, I, F> fmt::Debug for TakeWhileRef<'a, I, F>
602     where I: Iterator + fmt::Debug,
603 {
604     debug_fmt_fields!(TakeWhileRef, iter);
605 }
606 
607 /// Create a new `TakeWhileRef` from a reference to clonable iterator.
take_while_ref<I, F>(iter: &mut I, f: F) -> TakeWhileRef<I, F> where I: Iterator + Clone608 pub fn take_while_ref<I, F>(iter: &mut I, f: F) -> TakeWhileRef<I, F>
609     where I: Iterator + Clone
610 {
611     TakeWhileRef { iter, f }
612 }
613 
614 impl<'a, I, F> Iterator for TakeWhileRef<'a, I, F>
615     where I: Iterator + Clone,
616           F: FnMut(&I::Item) -> bool
617 {
618     type Item = I::Item;
619 
next(&mut self) -> Option<Self::Item>620     fn next(&mut self) -> Option<Self::Item> {
621         let old = self.iter.clone();
622         match self.iter.next() {
623             None => None,
624             Some(elt) => {
625                 if (self.f)(&elt) {
626                     Some(elt)
627                 } else {
628                     *self.iter = old;
629                     None
630                 }
631             }
632         }
633     }
634 
size_hint(&self) -> (usize, Option<usize>)635     fn size_hint(&self) -> (usize, Option<usize>) {
636         (0, self.iter.size_hint().1)
637     }
638 }
639 
640 /// An iterator adaptor that filters `Option<A>` iterator elements
641 /// and produces `A`. Stops on the first `None` encountered.
642 ///
643 /// See [`.while_some()`](../trait.Itertools.html#method.while_some) for more information.
644 #[derive(Clone, Debug)]
645 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
646 pub struct WhileSome<I> {
647     iter: I,
648 }
649 
650 /// Create a new `WhileSome<I>`.
while_some<I>(iter: I) -> WhileSome<I>651 pub fn while_some<I>(iter: I) -> WhileSome<I> {
652     WhileSome { iter }
653 }
654 
655 impl<I, A> Iterator for WhileSome<I>
656     where I: Iterator<Item = Option<A>>
657 {
658     type Item = A;
659 
next(&mut self) -> Option<Self::Item>660     fn next(&mut self) -> Option<Self::Item> {
661         match self.iter.next() {
662             None | Some(None) => None,
663             Some(elt) => elt,
664         }
665     }
666 
size_hint(&self) -> (usize, Option<usize>)667     fn size_hint(&self) -> (usize, Option<usize>) {
668         (0, self.iter.size_hint().1)
669     }
670 }
671 
672 /// An iterator to iterate through all combinations in a `Clone`-able iterator that produces tuples
673 /// of a specific size.
674 ///
675 /// See [`.tuple_combinations()`](../trait.Itertools.html#method.tuple_combinations) for more
676 /// information.
677 #[derive(Clone, Debug)]
678 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
679 pub struct TupleCombinations<I, T>
680     where I: Iterator,
681           T: HasCombination<I>
682 {
683     iter: T::Combination,
684     _mi: PhantomData<I>,
685     _mt: PhantomData<T>
686 }
687 
688 pub trait HasCombination<I>: Sized {
689     type Combination: From<I> + Iterator<Item = Self>;
690 }
691 
692 /// Create a new `TupleCombinations` from a clonable iterator.
tuple_combinations<T, I>(iter: I) -> TupleCombinations<I, T> where I: Iterator + Clone, I::Item: Clone, T: HasCombination<I>,693 pub fn tuple_combinations<T, I>(iter: I) -> TupleCombinations<I, T>
694     where I: Iterator + Clone,
695           I::Item: Clone,
696           T: HasCombination<I>,
697 {
698     TupleCombinations {
699         iter: T::Combination::from(iter),
700         _mi: PhantomData,
701         _mt: PhantomData,
702     }
703 }
704 
705 impl<I, T> Iterator for TupleCombinations<I, T>
706     where I: Iterator,
707           T: HasCombination<I>,
708 {
709     type Item = T;
710 
next(&mut self) -> Option<Self::Item>711     fn next(&mut self) -> Option<Self::Item> {
712         self.iter.next()
713     }
714 }
715 
716 #[derive(Clone, Debug)]
717 pub struct Tuple1Combination<I> {
718     iter: I,
719 }
720 
721 impl<I> From<I> for Tuple1Combination<I> {
from(iter: I) -> Self722     fn from(iter: I) -> Self {
723         Tuple1Combination { iter }
724     }
725 }
726 
727 impl<I: Iterator> Iterator for Tuple1Combination<I> {
728     type Item = (I::Item,);
729 
next(&mut self) -> Option<Self::Item>730     fn next(&mut self) -> Option<Self::Item> {
731         self.iter.next().map(|x| (x,))
732     }
733 }
734 
735 impl<I: Iterator> HasCombination<I> for (I::Item,) {
736     type Combination = Tuple1Combination<I>;
737 }
738 
739 macro_rules! impl_tuple_combination {
740     ($C:ident $P:ident ; $A:ident, $($I:ident),* ; $($X:ident)*) => (
741         #[derive(Clone, Debug)]
742         pub struct $C<I: Iterator> {
743             item: Option<I::Item>,
744             iter: I,
745             c: $P<I>,
746         }
747 
748         impl<I: Iterator + Clone> From<I> for $C<I> {
749             fn from(mut iter: I) -> Self {
750                 $C {
751                     item: iter.next(),
752                     iter: iter.clone(),
753                     c: $P::from(iter),
754                 }
755             }
756         }
757 
758         impl<I: Iterator + Clone> From<I> for $C<Fuse<I>> {
759             fn from(iter: I) -> Self {
760                 let mut iter = iter.fuse();
761                 $C {
762                     item: iter.next(),
763                     iter: iter.clone(),
764                     c: $P::from(iter),
765                 }
766             }
767         }
768 
769         impl<I, $A> Iterator for $C<I>
770             where I: Iterator<Item = $A> + Clone,
771                   I::Item: Clone
772         {
773             type Item = ($($I),*);
774 
775             fn next(&mut self) -> Option<Self::Item> {
776                 if let Some(($($X),*,)) = self.c.next() {
777                     let z = self.item.clone().unwrap();
778                     Some((z, $($X),*))
779                 } else {
780                     self.item = self.iter.next();
781                     self.item.clone().and_then(|z| {
782                         self.c = $P::from(self.iter.clone());
783                         self.c.next().map(|($($X),*,)| (z, $($X),*))
784                     })
785                 }
786             }
787         }
788 
789         impl<I, $A> HasCombination<I> for ($($I),*)
790             where I: Iterator<Item = $A> + Clone,
791                   I::Item: Clone
792         {
793             type Combination = $C<Fuse<I>>;
794         }
795     )
796 }
797 
798 // This snippet generates the twelve `impl_tuple_combination!` invocations:
799 //    use core::iter;
800 //    use itertools::Itertools;
801 //
802 //    for i in 2..=12 {
803 //        println!("impl_tuple_combination!(Tuple{arity}Combination Tuple{prev}Combination; {tys}; {idents});",
804 //            arity = i,
805 //            prev = i - 1,
806 //            tys = iter::repeat("A").take(i + 1).join(", "),
807 //            idents = ('a'..'z').take(i - 1).join(" "),
808 //        );
809 //    }
810 // It could probably be replaced by a bit more macro cleverness.
811 impl_tuple_combination!(Tuple2Combination Tuple1Combination; A, A, A; a);
812 impl_tuple_combination!(Tuple3Combination Tuple2Combination; A, A, A, A; a b);
813 impl_tuple_combination!(Tuple4Combination Tuple3Combination; A, A, A, A, A; a b c);
814 impl_tuple_combination!(Tuple5Combination Tuple4Combination; A, A, A, A, A, A; a b c d);
815 impl_tuple_combination!(Tuple6Combination Tuple5Combination; A, A, A, A, A, A, A; a b c d e);
816 impl_tuple_combination!(Tuple7Combination Tuple6Combination; A, A, A, A, A, A, A, A; a b c d e f);
817 impl_tuple_combination!(Tuple8Combination Tuple7Combination; A, A, A, A, A, A, A, A, A; a b c d e f g);
818 impl_tuple_combination!(Tuple9Combination Tuple8Combination; A, A, A, A, A, A, A, A, A, A; a b c d e f g h);
819 impl_tuple_combination!(Tuple10Combination Tuple9Combination; A, A, A, A, A, A, A, A, A, A, A; a b c d e f g h i);
820 impl_tuple_combination!(Tuple11Combination Tuple10Combination; A, A, A, A, A, A, A, A, A, A, A, A; a b c d e f g h i j);
821 impl_tuple_combination!(Tuple12Combination Tuple11Combination; A, A, A, A, A, A, A, A, A, A, A, A, A; a b c d e f g h i j k);
822 
823 /// An iterator adapter to filter values within a nested `Result::Ok`.
824 ///
825 /// See [`.filter_ok()`](../trait.Itertools.html#method.filter_ok) for more information.
826 #[derive(Clone)]
827 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
828 pub struct FilterOk<I, F> {
829     iter: I,
830     f: F
831 }
832 
833 /// Create a new `FilterOk` iterator.
filter_ok<I, F, T, E>(iter: I, f: F) -> FilterOk<I, F> where I: Iterator<Item = Result<T, E>>, F: FnMut(&T) -> bool,834 pub fn filter_ok<I, F, T, E>(iter: I, f: F) -> FilterOk<I, F>
835     where I: Iterator<Item = Result<T, E>>,
836           F: FnMut(&T) -> bool,
837 {
838     FilterOk {
839         iter,
840         f,
841     }
842 }
843 
844 impl<I, F, T, E> Iterator for FilterOk<I, F>
845     where I: Iterator<Item = Result<T, E>>,
846           F: FnMut(&T) -> bool,
847 {
848     type Item = Result<T, E>;
849 
next(&mut self) -> Option<Self::Item>850     fn next(&mut self) -> Option<Self::Item> {
851         loop {
852             match self.iter.next() {
853                 Some(Ok(v)) => {
854                     if (self.f)(&v) {
855                         return Some(Ok(v));
856                     }
857                 },
858                 Some(Err(e)) => return Some(Err(e)),
859                 None => return None,
860             }
861         }
862     }
863 
size_hint(&self) -> (usize, Option<usize>)864     fn size_hint(&self) -> (usize, Option<usize>) {
865         (0, self.iter.size_hint().1)
866     }
867 
fold<Acc, Fold>(self, init: Acc, fold_f: Fold) -> Acc where Fold: FnMut(Acc, Self::Item) -> Acc,868     fn fold<Acc, Fold>(self, init: Acc, fold_f: Fold) -> Acc
869         where Fold: FnMut(Acc, Self::Item) -> Acc,
870     {
871         let mut f = self.f;
872         self.iter.filter(|v| {
873             v.as_ref().map(&mut f).unwrap_or(true)
874         }).fold(init, fold_f)
875     }
876 
collect<C>(self) -> C where C: FromIterator<Self::Item>877     fn collect<C>(self) -> C
878         where C: FromIterator<Self::Item>
879     {
880         let mut f = self.f;
881         self.iter.filter(|v| {
882             v.as_ref().map(&mut f).unwrap_or(true)
883         }).collect()
884     }
885 }
886 
887 /// An iterator adapter to filter and apply a transformation on values within a nested `Result::Ok`.
888 ///
889 /// See [`.filter_map_ok()`](../trait.Itertools.html#method.filter_map_ok) for more information.
890 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
891 pub struct FilterMapOk<I, F> {
892     iter: I,
893     f: F
894 }
895 
transpose_result<T, E>(result: Result<Option<T>, E>) -> Option<Result<T, E>>896 fn transpose_result<T, E>(result: Result<Option<T>, E>) -> Option<Result<T, E>> {
897     match result {
898         Ok(Some(v)) => Some(Ok(v)),
899         Ok(None) => None,
900         Err(e) => Some(Err(e)),
901     }
902 }
903 
904 /// Create a new `FilterOk` iterator.
filter_map_ok<I, F, T, U, E>(iter: I, f: F) -> FilterMapOk<I, F> where I: Iterator<Item = Result<T, E>>, F: FnMut(T) -> Option<U>,905 pub fn filter_map_ok<I, F, T, U, E>(iter: I, f: F) -> FilterMapOk<I, F>
906     where I: Iterator<Item = Result<T, E>>,
907           F: FnMut(T) -> Option<U>,
908 {
909     FilterMapOk {
910         iter,
911         f,
912     }
913 }
914 
915 impl<I, F, T, U, E> Iterator for FilterMapOk<I, F>
916     where I: Iterator<Item = Result<T, E>>,
917           F: FnMut(T) -> Option<U>,
918 {
919     type Item = Result<U, E>;
920 
next(&mut self) -> Option<Self::Item>921     fn next(&mut self) -> Option<Self::Item> {
922         loop {
923             match self.iter.next() {
924                 Some(Ok(v)) => {
925                     if let Some(v) = (self.f)(v) {
926                         return Some(Ok(v));
927                     }
928                 },
929                 Some(Err(e)) => return Some(Err(e)),
930                 None => return None,
931             }
932         }
933     }
934 
size_hint(&self) -> (usize, Option<usize>)935     fn size_hint(&self) -> (usize, Option<usize>) {
936         (0, self.iter.size_hint().1)
937     }
938 
fold<Acc, Fold>(self, init: Acc, fold_f: Fold) -> Acc where Fold: FnMut(Acc, Self::Item) -> Acc,939     fn fold<Acc, Fold>(self, init: Acc, fold_f: Fold) -> Acc
940         where Fold: FnMut(Acc, Self::Item) -> Acc,
941     {
942         let mut f = self.f;
943         self.iter.filter_map(|v| {
944             transpose_result(v.map(&mut f))
945         }).fold(init, fold_f)
946     }
947 
collect<C>(self) -> C where C: FromIterator<Self::Item>948     fn collect<C>(self) -> C
949         where C: FromIterator<Self::Item>
950     {
951         let mut f = self.f;
952         self.iter.filter_map(|v| {
953             transpose_result(v.map(&mut f))
954         }).collect()
955     }
956 }
957 
958 /// An iterator adapter to get the positions of each element that matches a predicate.
959 ///
960 /// See [`.positions()`](../trait.Itertools.html#method.positions) for more information.
961 #[derive(Clone)]
962 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
963 pub struct Positions<I, F> {
964     iter: I,
965     f: F,
966     count: usize,
967 }
968 
969 /// Create a new `Positions` iterator.
positions<I, F>(iter: I, f: F) -> Positions<I, F> where I: Iterator, F: FnMut(I::Item) -> bool,970 pub fn positions<I, F>(iter: I, f: F) -> Positions<I, F>
971     where I: Iterator,
972           F: FnMut(I::Item) -> bool,
973 {
974     Positions {
975         iter,
976         f,
977         count: 0
978     }
979 }
980 
981 impl<I, F> Iterator for Positions<I, F>
982     where I: Iterator,
983           F: FnMut(I::Item) -> bool,
984 {
985     type Item = usize;
986 
next(&mut self) -> Option<Self::Item>987     fn next(&mut self) -> Option<Self::Item> {
988         while let Some(v) = self.iter.next() {
989             let i = self.count;
990             self.count = i + 1;
991             if (self.f)(v) {
992                 return Some(i);
993             }
994         }
995         None
996     }
997 
size_hint(&self) -> (usize, Option<usize>)998     fn size_hint(&self) -> (usize, Option<usize>) {
999         (0, self.iter.size_hint().1)
1000     }
1001 }
1002 
1003 impl<I, F> DoubleEndedIterator for Positions<I, F>
1004     where I: DoubleEndedIterator + ExactSizeIterator,
1005           F: FnMut(I::Item) -> bool,
1006 {
next_back(&mut self) -> Option<Self::Item>1007     fn next_back(&mut self) -> Option<Self::Item> {
1008         while let Some(v) = self.iter.next_back() {
1009             if (self.f)(v) {
1010                 return Some(self.count + self.iter.len())
1011             }
1012         }
1013         None
1014     }
1015 }
1016 
1017 /// An iterator adapter to apply a mutating function to each element before yielding it.
1018 ///
1019 /// See [`.update()`](../trait.Itertools.html#method.update) for more information.
1020 #[derive(Clone)]
1021 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1022 pub struct Update<I, F> {
1023     iter: I,
1024     f: F,
1025 }
1026 
1027 /// Create a new `Update` iterator.
update<I, F>(iter: I, f: F) -> Update<I, F> where I: Iterator, F: FnMut(&mut I::Item),1028 pub fn update<I, F>(iter: I, f: F) -> Update<I, F>
1029 where
1030     I: Iterator,
1031     F: FnMut(&mut I::Item),
1032 {
1033     Update { iter, f }
1034 }
1035 
1036 impl<I, F> Iterator for Update<I, F>
1037 where
1038     I: Iterator,
1039     F: FnMut(&mut I::Item),
1040 {
1041     type Item = I::Item;
1042 
next(&mut self) -> Option<Self::Item>1043     fn next(&mut self) -> Option<Self::Item> {
1044         if let Some(mut v) = self.iter.next() {
1045             (self.f)(&mut v);
1046             Some(v)
1047         } else {
1048             None
1049         }
1050     }
1051 
size_hint(&self) -> (usize, Option<usize>)1052     fn size_hint(&self) -> (usize, Option<usize>) {
1053         self.iter.size_hint()
1054     }
1055 
fold<Acc, G>(self, init: Acc, mut g: G) -> Acc where G: FnMut(Acc, Self::Item) -> Acc,1056     fn fold<Acc, G>(self, init: Acc, mut g: G) -> Acc
1057         where G: FnMut(Acc, Self::Item) -> Acc,
1058     {
1059         let mut f = self.f;
1060         self.iter.fold(init, move |acc, mut v| { f(&mut v); g(acc, v) })
1061     }
1062 
1063     // if possible, re-use inner iterator specializations in collect
collect<C>(self) -> C where C: FromIterator<Self::Item>1064     fn collect<C>(self) -> C
1065         where C: FromIterator<Self::Item>
1066     {
1067         let mut f = self.f;
1068         self.iter.map(move |mut v| { f(&mut v); v }).collect()
1069     }
1070 }
1071 
1072 impl<I, F> ExactSizeIterator for Update<I, F>
1073 where
1074     I: ExactSizeIterator,
1075     F: FnMut(&mut I::Item),
1076 {}
1077 
1078 impl<I, F> DoubleEndedIterator for Update<I, F>
1079 where
1080     I: DoubleEndedIterator,
1081     F: FnMut(&mut I::Item),
1082 {
next_back(&mut self) -> Option<Self::Item>1083     fn next_back(&mut self) -> Option<Self::Item> {
1084         if let Some(mut v) = self.iter.next_back() {
1085             (self.f)(&mut v);
1086             Some(v)
1087         } else {
1088             None
1089         }
1090     }
1091 }
1092