itertools/adaptors/
mod.rs

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
7mod multi_product;
8#[cfg(feature = "use_std")]
9pub use self::multi_product::*;
10
11use std::fmt;
12use std::mem::replace;
13use std::iter::{Fuse, Peekable, FromIterator};
14use std::marker::PhantomData;
15use size_hint;
16
17macro_rules! clone_fields {
18    ($name:ident, $base:expr, $($field:ident),+) => (
19        $name {
20            $(
21                $field : $base . $field .clone()
22            ),*
23        }
24    );
25}
26
27/// An iterator adaptor that alternates elements from two iterators until both
28/// run out.
29///
30/// This iterator is *fused*.
31///
32/// See [`.interleave()`](../trait.Itertools.html#method.interleave) for more information.
33#[derive(Clone, Debug)]
34#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
35pub struct Interleave<I, J> {
36    a: Fuse<I>,
37    b: Fuse<J>,
38    flag: bool,
39}
40
41/// Create an iterator that interleaves elements in `i` and `j`.
42///
43/// `IntoIterator` enabled version of `i.interleave(j)`.
44///
45/// ```
46/// use itertools::interleave;
47///
48/// for elt in interleave(&[1, 2, 3], &[2, 3, 4]) {
49///     /* loop body */
50/// }
51/// ```
52pub fn interleave<I, J>(i: I, j: J) -> Interleave<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter>
53    where I: IntoIterator,
54          J: IntoIterator<Item = I::Item>
55{
56    Interleave {
57        a: i.into_iter().fuse(),
58        b: j.into_iter().fuse(),
59        flag: false,
60    }
61}
62
63impl<I, J> Iterator for Interleave<I, J>
64    where I: Iterator,
65          J: Iterator<Item = I::Item>
66{
67    type Item = I::Item;
68    #[inline]
69    fn next(&mut self) -> Option<I::Item> {
70        self.flag = !self.flag;
71        if self.flag {
72            match self.a.next() {
73                None => self.b.next(),
74                r => r,
75            }
76        } else {
77            match self.b.next() {
78                None => self.a.next(),
79                r => r,
80            }
81        }
82    }
83
84    fn size_hint(&self) -> (usize, Option<usize>) {
85        size_hint::add(self.a.size_hint(), self.b.size_hint())
86    }
87}
88
89/// An iterator adaptor that alternates elements from the two iterators until
90/// one of them runs out.
91///
92/// This iterator is *fused*.
93///
94/// See [`.interleave_shortest()`](../trait.Itertools.html#method.interleave_shortest)
95/// for more information.
96#[derive(Clone, Debug)]
97#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
98pub struct InterleaveShortest<I, J>
99    where I: Iterator,
100          J: Iterator<Item = I::Item>
101{
102    it0: I,
103    it1: J,
104    phase: bool, // false ==> it0, true ==> it1
105}
106
107/// Create a new `InterleaveShortest` iterator.
108pub fn interleave_shortest<I, J>(a: I, b: J) -> InterleaveShortest<I, J>
109    where I: Iterator,
110          J: Iterator<Item = I::Item>
111{
112    InterleaveShortest {
113        it0: a,
114        it1: b,
115        phase: false,
116    }
117}
118
119impl<I, J> Iterator for InterleaveShortest<I, J>
120    where I: Iterator,
121          J: Iterator<Item = I::Item>
122{
123    type Item = I::Item;
124
125    #[inline]
126    fn next(&mut self) -> Option<I::Item> {
127        match self.phase {
128            false => match self.it0.next() {
129                None => None,
130                e => {
131                    self.phase = true;
132                    e
133                }
134            },
135            true => match self.it1.next() {
136                None => None,
137                e => {
138                    self.phase = false;
139                    e
140                }
141            },
142        }
143    }
144
145    #[inline]
146    fn size_hint(&self) -> (usize, Option<usize>) {
147        let (curr_hint, next_hint) = {
148            let it0_hint = self.it0.size_hint();
149            let it1_hint = self.it1.size_hint();
150            if self.phase {
151                (it1_hint, it0_hint)
152            } else {
153                (it0_hint, it1_hint)
154            }
155        };
156        let (curr_lower, curr_upper) = curr_hint;
157        let (next_lower, next_upper) = next_hint;
158        let (combined_lower, combined_upper) =
159            size_hint::mul_scalar(size_hint::min(curr_hint, next_hint), 2);
160        let lower =
161            if curr_lower > next_lower {
162                combined_lower + 1
163            } else {
164                combined_lower
165            };
166        let upper = {
167            let extra_elem = match (curr_upper, next_upper) {
168                (_, None) => false,
169                (None, Some(_)) => true,
170                (Some(curr_max), Some(next_max)) => curr_max > next_max,
171            };
172            if extra_elem {
173                combined_upper.and_then(|x| x.checked_add(1))
174            } else {
175                combined_upper
176            }
177        };
178        (lower, upper)
179    }
180}
181
182#[derive(Clone, Debug)]
183/// An iterator adaptor that allows putting back a single
184/// item to the front of the iterator.
185///
186/// Iterator element type is `I::Item`.
187pub struct PutBack<I>
188    where I: Iterator
189{
190    top: Option<I::Item>,
191    iter: I,
192}
193
194/// Create an iterator where you can put back a single item
195pub fn put_back<I>(iterable: I) -> PutBack<I::IntoIter>
196    where I: IntoIterator
197{
198    PutBack {
199        top: None,
200        iter: iterable.into_iter(),
201    }
202}
203
204impl<I> PutBack<I>
205    where I: Iterator
206{
207    /// put back value `value` (builder method)
208    pub fn with_value(mut self, value: I::Item) -> Self {
209        self.put_back(value);
210        self
211    }
212
213    /// Split the `PutBack` into its parts.
214    #[inline]
215    pub fn into_parts(self) -> (Option<I::Item>, I) {
216        let PutBack{top, iter} = self;
217        (top, iter)
218    }
219
220    /// Put back a single value to the front of the iterator.
221    ///
222    /// If a value is already in the put back slot, it is overwritten.
223    #[inline]
224    pub fn put_back(&mut self, x: I::Item) {
225        self.top = Some(x)
226    }
227}
228
229impl<I> Iterator for PutBack<I>
230    where I: Iterator
231{
232    type Item = I::Item;
233    #[inline]
234    fn next(&mut self) -> Option<I::Item> {
235        match self.top {
236            None => self.iter.next(),
237            ref mut some => some.take(),
238        }
239    }
240    #[inline]
241    fn size_hint(&self) -> (usize, Option<usize>) {
242        // Not ExactSizeIterator because size may be larger than usize
243        size_hint::add_scalar(self.iter.size_hint(), self.top.is_some() as usize)
244    }
245
246    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
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"]
276pub 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)`.
288pub 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
302impl<I, J> Iterator for Product<I, J>
303    where I: Iterator,
304          J: Clone + Iterator,
305          I::Item: Clone
306{
307    type Item = (I::Item, J::Item);
308    fn next(&mut self) -> Option<(I::Item, J::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
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
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"]
372pub struct Batching<I, F> {
373    f: F,
374    iter: I,
375}
376
377impl<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.
382pub fn batching<I, F>(iter: I, f: F) -> Batching<I, F> {
383    Batching { f: f, iter: iter }
384}
385
386impl<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]
392    fn next(&mut self) -> Option<B> {
393        (self.f)(&mut self.iter)
394    }
395
396    #[inline]
397    fn size_hint(&self) -> (usize, Option<usize>) {
398        // No information about closue behavior
399        (0, None)
400    }
401}
402
403/// An iterator adaptor that steps a number elements in the base iterator
404/// for each iteration.
405///
406/// The iterator steps by yielding the next element from the base iterator,
407/// then skipping forward *n-1* elements.
408///
409/// See [`.step()`](../trait.Itertools.html#method.step) for more information.
410#[deprecated(note="Use std .step_by() instead", since="0.8")]
411#[allow(deprecated)]
412#[derive(Clone, Debug)]
413#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
414pub struct Step<I> {
415    iter: Fuse<I>,
416    skip: usize,
417}
418
419/// Create a `Step` iterator.
420///
421/// **Panics** if the step is 0.
422#[allow(deprecated)]
423pub fn step<I>(iter: I, step: usize) -> Step<I>
424    where I: Iterator
425{
426    assert!(step != 0);
427    Step {
428        iter: iter.fuse(),
429        skip: step - 1,
430    }
431}
432
433#[allow(deprecated)]
434impl<I> Iterator for Step<I>
435    where I: Iterator
436{
437    type Item = I::Item;
438    #[inline]
439    fn next(&mut self) -> Option<I::Item> {
440        let elt = self.iter.next();
441        if self.skip > 0 {
442            self.iter.nth(self.skip - 1);
443        }
444        elt
445    }
446
447    fn size_hint(&self) -> (usize, Option<usize>) {
448        let (low, high) = self.iter.size_hint();
449        let div = |x: usize| {
450            if x == 0 {
451                0
452            } else {
453                1 + (x - 1) / (self.skip + 1)
454            }
455        };
456        (div(low), high.map(div))
457    }
458}
459
460// known size
461#[allow(deprecated)]
462impl<I> ExactSizeIterator for Step<I>
463    where I: ExactSizeIterator
464{}
465
466
467struct MergeCore<I, J>
468    where I: Iterator,
469          J: Iterator<Item = I::Item>
470{
471    a: Peekable<I>,
472    b: Peekable<J>,
473    fused: Option<bool>,
474}
475
476
477impl<I, J> Clone for MergeCore<I, J>
478    where I: Iterator,
479          J: Iterator<Item = I::Item>,
480          Peekable<I>: Clone,
481          Peekable<J>: Clone
482{
483    fn clone(&self) -> Self {
484        clone_fields!(MergeCore, self, a, b, fused)
485    }
486}
487
488impl<I, J> MergeCore<I, J>
489    where I: Iterator,
490          J: Iterator<Item = I::Item>
491{
492    fn next_with<F>(&mut self, mut less_than: F) -> Option<I::Item>
493        where F: FnMut(&I::Item, &I::Item) -> bool
494    {
495        let less_than = match self.fused {
496            Some(lt) => lt,
497            None => match (self.a.peek(), self.b.peek()) {
498                (Some(a), Some(b)) => less_than(a, b),
499                (Some(_), None) => {
500                    self.fused = Some(true);
501                    true
502                }
503                (None, Some(_)) => {
504                    self.fused = Some(false);
505                    false
506                }
507                (None, None) => return None,
508            }
509        };
510
511        if less_than {
512            self.a.next()
513        } else {
514            self.b.next()
515        }
516    }
517
518    fn size_hint(&self) -> (usize, Option<usize>) {
519        // Not ExactSizeIterator because size may be larger than usize
520        size_hint::add(self.a.size_hint(), self.b.size_hint())
521    }
522}
523
524/// An iterator adaptor that merges the two base iterators in ascending order.
525/// If both base iterators are sorted (ascending), the result is sorted.
526///
527/// Iterator element type is `I::Item`.
528///
529/// See [`.merge()`](../trait.Itertools.html#method.merge_by) for more information.
530#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
531pub struct Merge<I, J>
532    where I: Iterator,
533          J: Iterator<Item = I::Item>
534{
535    merge: MergeCore<I, J>,
536}
537
538impl<I, J> Clone for Merge<I, J>
539    where I: Iterator,
540          J: Iterator<Item = I::Item>,
541          Peekable<I>: Clone,
542          Peekable<J>: Clone
543{
544    fn clone(&self) -> Self {
545        clone_fields!(Merge, self, merge)
546    }
547}
548
549impl<I, J> fmt::Debug for Merge<I, J>
550    where I: Iterator + fmt::Debug, J: Iterator<Item = I::Item> + fmt::Debug,
551          I::Item: fmt::Debug,
552{
553    debug_fmt_fields!(Merge, merge.a, merge.b);
554}
555
556/// Create an iterator that merges elements in `i` and `j`.
557///
558/// `IntoIterator` enabled version of `i.merge(j)`.
559///
560/// ```
561/// use itertools::merge;
562///
563/// for elt in merge(&[1, 2, 3], &[2, 3, 4]) {
564///     /* loop body */
565/// }
566/// ```
567pub fn merge<I, J>(i: I, j: J) -> Merge<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter>
568    where I: IntoIterator,
569          J: IntoIterator<Item = I::Item>,
570          I::Item: PartialOrd
571{
572    Merge {
573        merge: MergeCore {
574            a: i.into_iter().peekable(),
575            b: j.into_iter().peekable(),
576            fused: None,
577        },
578    }
579}
580
581impl<I, J> Iterator for Merge<I, J>
582    where I: Iterator,
583          J: Iterator<Item = I::Item>,
584          I::Item: PartialOrd
585{
586    type Item = I::Item;
587
588    fn next(&mut self) -> Option<I::Item> {
589        self.merge.next_with(|a, b| a <= b)
590    }
591
592    fn size_hint(&self) -> (usize, Option<usize>) {
593        self.merge.size_hint()
594    }
595}
596
597/// An iterator adaptor that merges the two base iterators in ascending order.
598/// If both base iterators are sorted (ascending), the result is sorted.
599///
600/// Iterator element type is `I::Item`.
601///
602/// See [`.merge_by()`](../trait.Itertools.html#method.merge_by) for more information.
603#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
604pub struct MergeBy<I, J, F>
605    where I: Iterator,
606          J: Iterator<Item = I::Item>
607{
608    merge: MergeCore<I, J>,
609    cmp: F,
610}
611
612impl<I, J, F> fmt::Debug for MergeBy<I, J, F>
613    where I: Iterator + fmt::Debug, J: Iterator<Item = I::Item> + fmt::Debug,
614          I::Item: fmt::Debug,
615{
616    debug_fmt_fields!(MergeBy, merge.a, merge.b);
617}
618
619/// Create a `MergeBy` iterator.
620pub fn merge_by_new<I, J, F>(a: I, b: J, cmp: F) -> MergeBy<I, J, F>
621    where I: Iterator,
622          J: Iterator<Item = I::Item>
623{
624    MergeBy {
625        merge: MergeCore {
626            a: a.peekable(),
627            b: b.peekable(),
628            fused: None,
629        },
630        cmp: cmp,
631    }
632}
633
634impl<I, J, F> Clone for MergeBy<I, J, F>
635    where I: Iterator,
636          J: Iterator<Item = I::Item>,
637          Peekable<I>: Clone,
638          Peekable<J>: Clone,
639          F: Clone
640{
641    fn clone(&self) -> Self {
642        clone_fields!(MergeBy, self, merge, cmp)
643    }
644}
645
646impl<I, J, F> Iterator for MergeBy<I, J, F>
647    where I: Iterator,
648          J: Iterator<Item = I::Item>,
649          F: FnMut(&I::Item, &I::Item) -> bool
650{
651    type Item = I::Item;
652
653    fn next(&mut self) -> Option<I::Item> {
654        self.merge.next_with(&mut self.cmp)
655    }
656
657    fn size_hint(&self) -> (usize, Option<usize>) {
658        self.merge.size_hint()
659    }
660}
661
662#[derive(Clone, Debug)]
663pub struct CoalesceCore<I>
664    where I: Iterator
665{
666    iter: I,
667    last: Option<I::Item>,
668}
669
670impl<I> CoalesceCore<I>
671    where I: Iterator
672{
673    fn next_with<F>(&mut self, mut f: F) -> Option<I::Item>
674        where F: FnMut(I::Item, I::Item) -> Result<I::Item, (I::Item, I::Item)>
675    {
676        // this fuses the iterator
677        let mut last = match self.last.take() {
678            None => return None,
679            Some(x) => x,
680        };
681        for next in &mut self.iter {
682            match f(last, next) {
683                Ok(joined) => last = joined,
684                Err((last_, next_)) => {
685                    self.last = Some(next_);
686                    return Some(last_);
687                }
688            }
689        }
690
691        Some(last)
692    }
693
694    fn size_hint(&self) -> (usize, Option<usize>) {
695        let (low, hi) = size_hint::add_scalar(self.iter.size_hint(),
696                                              self.last.is_some() as usize);
697        ((low > 0) as usize, hi)
698    }
699}
700
701/// An iterator adaptor that may join together adjacent elements.
702///
703/// See [`.coalesce()`](../trait.Itertools.html#method.coalesce) for more information.
704#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
705pub struct Coalesce<I, F>
706    where I: Iterator
707{
708    iter: CoalesceCore<I>,
709    f: F,
710}
711
712impl<I: Clone, F: Clone> Clone for Coalesce<I, F>
713    where I: Iterator,
714          I::Item: Clone
715{
716    fn clone(&self) -> Self {
717        clone_fields!(Coalesce, self, iter, f)
718    }
719}
720
721impl<I, F> fmt::Debug for Coalesce<I, F>
722    where I: Iterator + fmt::Debug,
723          I::Item: fmt::Debug,
724{
725    debug_fmt_fields!(Coalesce, iter);
726}
727
728/// Create a new `Coalesce`.
729pub fn coalesce<I, F>(mut iter: I, f: F) -> Coalesce<I, F>
730    where I: Iterator
731{
732    Coalesce {
733        iter: CoalesceCore {
734            last: iter.next(),
735            iter: iter,
736        },
737        f: f,
738    }
739}
740
741impl<I, F> Iterator for Coalesce<I, F>
742    where I: Iterator,
743          F: FnMut(I::Item, I::Item) -> Result<I::Item, (I::Item, I::Item)>
744{
745    type Item = I::Item;
746
747    fn next(&mut self) -> Option<I::Item> {
748        self.iter.next_with(&mut self.f)
749    }
750
751    fn size_hint(&self) -> (usize, Option<usize>) {
752        self.iter.size_hint()
753    }
754}
755
756/// An iterator adaptor that removes repeated duplicates.
757///
758/// See [`.dedup()`](../trait.Itertools.html#method.dedup) for more information.
759#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
760pub struct Dedup<I>
761    where I: Iterator
762{
763    iter: CoalesceCore<I>,
764}
765
766impl<I: Clone> Clone for Dedup<I>
767    where I: Iterator,
768          I::Item: Clone
769{
770    fn clone(&self) -> Self {
771        clone_fields!(Dedup, self, iter)
772    }
773}
774
775/// Create a new `Dedup`.
776pub fn dedup<I>(mut iter: I) -> Dedup<I>
777    where I: Iterator
778{
779    Dedup {
780        iter: CoalesceCore {
781            last: iter.next(),
782            iter: iter,
783        },
784    }
785}
786
787impl<I> fmt::Debug for Dedup<I>
788    where I: Iterator + fmt::Debug,
789          I::Item: fmt::Debug,
790{
791    debug_fmt_fields!(Dedup, iter);
792}
793
794impl<I> Iterator for Dedup<I>
795    where I: Iterator,
796          I::Item: PartialEq
797{
798    type Item = I::Item;
799
800    fn next(&mut self) -> Option<I::Item> {
801        self.iter.next_with(|x, y| {
802            if x == y { Ok(x) } else { Err((x, y)) }
803        })
804    }
805
806    fn size_hint(&self) -> (usize, Option<usize>) {
807        self.iter.size_hint()
808    }
809
810    fn fold<Acc, G>(self, mut accum: Acc, mut f: G) -> Acc
811        where G: FnMut(Acc, Self::Item) -> Acc,
812    {
813        if let Some(mut last) = self.iter.last {
814            accum = self.iter.iter.fold(accum, |acc, elt| {
815                if elt == last {
816                    acc
817                } else {
818                    f(acc, replace(&mut last, elt))
819                }
820            });
821            f(accum, last)
822        } else {
823            accum
824        }
825    }
826}
827
828/// An iterator adaptor that borrows from a `Clone`-able iterator
829/// to only pick off elements while the predicate returns `true`.
830///
831/// See [`.take_while_ref()`](../trait.Itertools.html#method.take_while_ref) for more information.
832#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
833pub struct TakeWhileRef<'a, I: 'a, F> {
834    iter: &'a mut I,
835    f: F,
836}
837
838impl<'a, I, F> fmt::Debug for TakeWhileRef<'a, I, F>
839    where I: Iterator + fmt::Debug,
840{
841    debug_fmt_fields!(TakeWhileRef, iter);
842}
843
844/// Create a new `TakeWhileRef` from a reference to clonable iterator.
845pub fn take_while_ref<I, F>(iter: &mut I, f: F) -> TakeWhileRef<I, F>
846    where I: Iterator + Clone
847{
848    TakeWhileRef { iter: iter, f: f }
849}
850
851impl<'a, I, F> Iterator for TakeWhileRef<'a, I, F>
852    where I: Iterator + Clone,
853          F: FnMut(&I::Item) -> bool
854{
855    type Item = I::Item;
856
857    fn next(&mut self) -> Option<I::Item> {
858        let old = self.iter.clone();
859        match self.iter.next() {
860            None => None,
861            Some(elt) => {
862                if (self.f)(&elt) {
863                    Some(elt)
864                } else {
865                    *self.iter = old;
866                    None
867                }
868            }
869        }
870    }
871
872    fn size_hint(&self) -> (usize, Option<usize>) {
873        let (_, hi) = self.iter.size_hint();
874        (0, hi)
875    }
876}
877
878/// An iterator adaptor that filters `Option<A>` iterator elements
879/// and produces `A`. Stops on the first `None` encountered.
880///
881/// See [`.while_some()`](../trait.Itertools.html#method.while_some) for more information.
882#[derive(Clone, Debug)]
883#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
884pub struct WhileSome<I> {
885    iter: I,
886}
887
888/// Create a new `WhileSome<I>`.
889pub fn while_some<I>(iter: I) -> WhileSome<I> {
890    WhileSome { iter: iter }
891}
892
893impl<I, A> Iterator for WhileSome<I>
894    where I: Iterator<Item = Option<A>>
895{
896    type Item = A;
897
898    fn next(&mut self) -> Option<A> {
899        match self.iter.next() {
900            None | Some(None) => None,
901            Some(elt) => elt,
902        }
903    }
904
905    fn size_hint(&self) -> (usize, Option<usize>) {
906        let sh = self.iter.size_hint();
907        (0, sh.1)
908    }
909}
910
911/// An iterator to iterate through all combinations in a `Clone`-able iterator that produces tuples
912/// of a specific size.
913///
914/// See [`.tuple_combinations()`](../trait.Itertools.html#method.tuple_combinations) for more
915/// information.
916#[derive(Debug)]
917#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
918pub struct TupleCombinations<I, T>
919    where I: Iterator,
920          T: HasCombination<I>
921{
922    iter: T::Combination,
923    _mi: PhantomData<I>,
924    _mt: PhantomData<T>
925}
926
927pub trait HasCombination<I>: Sized {
928    type Combination: From<I> + Iterator<Item = Self>;
929}
930
931/// Create a new `TupleCombinations` from a clonable iterator.
932pub fn tuple_combinations<T, I>(iter: I) -> TupleCombinations<I, T>
933    where I: Iterator + Clone,
934          I::Item: Clone,
935          T: HasCombination<I>,
936{
937    TupleCombinations {
938        iter: T::Combination::from(iter),
939        _mi: PhantomData,
940        _mt: PhantomData,
941    }
942}
943
944impl<I, T> Iterator for TupleCombinations<I, T>
945    where I: Iterator,
946          T: HasCombination<I>,
947{
948    type Item = T;
949
950    fn next(&mut self) -> Option<Self::Item> {
951        self.iter.next()
952    }
953}
954
955#[derive(Debug)]
956pub struct Tuple1Combination<I> {
957    iter: I,
958}
959
960impl<I> From<I> for Tuple1Combination<I> {
961    fn from(iter: I) -> Self {
962        Tuple1Combination { iter: iter }
963    }
964}
965
966impl<I: Iterator> Iterator for Tuple1Combination<I> {
967    type Item = (I::Item,);
968
969    fn next(&mut self) -> Option<Self::Item> {
970        self.iter.next().map(|x| (x,))
971    }
972}
973
974impl<I: Iterator> HasCombination<I> for (I::Item,) {
975    type Combination = Tuple1Combination<I>;
976}
977
978macro_rules! impl_tuple_combination {
979    ($C:ident $P:ident ; $A:ident, $($I:ident),* ; $($X:ident)*) => (
980        #[derive(Debug)]
981        pub struct $C<I: Iterator> {
982            item: Option<I::Item>,
983            iter: I,
984            c: $P<I>,
985        }
986
987        impl<I: Iterator + Clone> From<I> for $C<I> {
988            fn from(mut iter: I) -> Self {
989                $C {
990                    item: iter.next(),
991                    iter: iter.clone(),
992                    c: $P::from(iter),
993                }
994            }
995        }
996
997        impl<I: Iterator + Clone> From<I> for $C<Fuse<I>> {
998            fn from(iter: I) -> Self {
999                let mut iter = iter.fuse();
1000                $C {
1001                    item: iter.next(),
1002                    iter: iter.clone(),
1003                    c: $P::from(iter),
1004                }
1005            }
1006        }
1007
1008        impl<I, $A> Iterator for $C<I>
1009            where I: Iterator<Item = $A> + Clone,
1010                  I::Item: Clone
1011        {
1012            type Item = ($($I),*);
1013
1014            fn next(&mut self) -> Option<Self::Item> {
1015                if let Some(($($X),*,)) = self.c.next() {
1016                    let z = self.item.clone().unwrap();
1017                    Some((z, $($X),*))
1018                } else {
1019                    self.item = self.iter.next();
1020                    self.item.clone().and_then(|z| {
1021                        self.c = $P::from(self.iter.clone());
1022                        self.c.next().map(|($($X),*,)| (z, $($X),*))
1023                    })
1024                }
1025            }
1026        }
1027
1028        impl<I, $A> HasCombination<I> for ($($I),*)
1029            where I: Iterator<Item = $A> + Clone,
1030                  I::Item: Clone
1031        {
1032            type Combination = $C<Fuse<I>>;
1033        }
1034    )
1035}
1036
1037impl_tuple_combination!(Tuple2Combination Tuple1Combination ; A, A, A ; a);
1038impl_tuple_combination!(Tuple3Combination Tuple2Combination ; A, A, A, A ; a b);
1039impl_tuple_combination!(Tuple4Combination Tuple3Combination ; A, A, A, A, A; a b c);
1040
1041/// An iterator adapter to apply `Into` conversion to each element.
1042///
1043/// See [`.map_into()`](../trait.Itertools.html#method.map_into) for more information.
1044#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1045pub struct MapInto<I, R> {
1046    iter: I,
1047    _res: PhantomData<fn() -> R>,
1048}
1049
1050/// Create a new [`MapInto`](struct.MapInto.html) iterator.
1051pub fn map_into<I, R>(iter: I) -> MapInto<I, R> {
1052    MapInto {
1053        iter: iter,
1054        _res: PhantomData,
1055    }
1056}
1057
1058impl<I, R> Iterator for MapInto<I, R>
1059    where I: Iterator,
1060          I::Item: Into<R>,
1061{
1062    type Item = R;
1063
1064    fn next(&mut self) -> Option<R> {
1065        self.iter
1066            .next()
1067            .map(|i| i.into())
1068    }
1069
1070    fn size_hint(&self) -> (usize, Option<usize>) {
1071        self.iter.size_hint()
1072    }
1073
1074    fn fold<Acc, Fold>(self, init: Acc, mut fold_f: Fold) -> Acc
1075        where Fold: FnMut(Acc, Self::Item) -> Acc,
1076    {
1077        self.iter.fold(init, move |acc, v| fold_f(acc, v.into()))
1078    }
1079}
1080
1081impl<I, R> DoubleEndedIterator for MapInto<I, R>
1082    where I: DoubleEndedIterator,
1083          I::Item: Into<R>,
1084{
1085    fn next_back(&mut self) -> Option<Self::Item> {
1086        self.iter
1087            .next_back()
1088            .map(|i| i.into())
1089    }
1090}
1091
1092impl<I, R> ExactSizeIterator for MapInto<I, R>
1093where
1094    I: ExactSizeIterator,
1095    I::Item: Into<R>,
1096{}
1097
1098/// An iterator adapter to apply a transformation within a nested `Result`.
1099///
1100/// See [`.map_results()`](../trait.Itertools.html#method.map_results) for more information.
1101#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1102pub struct MapResults<I, F> {
1103    iter: I,
1104    f: F
1105}
1106
1107/// Create a new `MapResults` iterator.
1108pub fn map_results<I, F, T, U, E>(iter: I, f: F) -> MapResults<I, F>
1109    where I: Iterator<Item = Result<T, E>>,
1110          F: FnMut(T) -> U,
1111{
1112    MapResults {
1113        iter: iter,
1114        f: f,
1115    }
1116}
1117
1118impl<I, F, T, U, E> Iterator for MapResults<I, F>
1119    where I: Iterator<Item = Result<T, E>>,
1120          F: FnMut(T) -> U,
1121{
1122    type Item = Result<U, E>;
1123
1124    fn next(&mut self) -> Option<Self::Item> {
1125        self.iter.next().map(|v| v.map(&mut self.f))
1126    }
1127
1128    fn size_hint(&self) -> (usize, Option<usize>) {
1129        self.iter.size_hint()
1130    }
1131
1132    fn fold<Acc, Fold>(self, init: Acc, mut fold_f: Fold) -> Acc
1133        where Fold: FnMut(Acc, Self::Item) -> Acc,
1134    {
1135        let mut f = self.f;
1136        self.iter.fold(init, move |acc, v| fold_f(acc, v.map(&mut f)))
1137    }
1138
1139    fn collect<C>(self) -> C
1140        where C: FromIterator<Self::Item>
1141    {
1142        let mut f = self.f;
1143        self.iter.map(move |v| v.map(&mut f)).collect()
1144    }
1145}
1146
1147/// An iterator adapter to get the positions of each element that matches a predicate.
1148///
1149/// See [`.positions()`](../trait.Itertools.html#method.positions) for more information.
1150#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1151pub struct Positions<I, F> {
1152    iter: I,
1153    f: F,
1154    count: usize,
1155}
1156
1157/// Create a new `Positions` iterator.
1158pub fn positions<I, F>(iter: I, f: F) -> Positions<I, F>
1159    where I: Iterator,
1160          F: FnMut(I::Item) -> bool,
1161{
1162    Positions {
1163        iter: iter,
1164        f: f,
1165        count: 0
1166    }
1167}
1168
1169impl<I, F> Iterator for Positions<I, F>
1170    where I: Iterator,
1171          F: FnMut(I::Item) -> bool,
1172{
1173    type Item = usize;
1174
1175    fn next(&mut self) -> Option<Self::Item> {
1176        while let Some(v) = self.iter.next() {
1177            let i = self.count;
1178            self.count = i + 1;
1179            if (self.f)(v) {
1180                return Some(i);
1181            }
1182        }
1183        None
1184    }
1185
1186    fn size_hint(&self) -> (usize, Option<usize>) {
1187        (0, self.iter.size_hint().1)
1188    }
1189}
1190
1191impl<I, F> DoubleEndedIterator for Positions<I, F>
1192    where I: DoubleEndedIterator + ExactSizeIterator,
1193          F: FnMut(I::Item) -> bool,
1194{
1195    fn next_back(&mut self) -> Option<Self::Item> {
1196        while let Some(v) = self.iter.next_back() {
1197            if (self.f)(v) {
1198                return Some(self.count + self.iter.len())
1199            }
1200        }
1201        None
1202    }
1203}
1204
1205/// An iterator adapter to apply a mutating function to each element before yielding it.
1206///
1207/// See [`.update()`](../trait.Itertools.html#method.update) for more information.
1208#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1209pub struct Update<I, F> {
1210    iter: I,
1211    f: F,
1212}
1213
1214/// Create a new `Update` iterator.
1215pub fn update<I, F>(iter: I, f: F) -> Update<I, F>
1216where
1217    I: Iterator,
1218    F: FnMut(&mut I::Item),
1219{
1220    Update { iter: iter, f: f }
1221}
1222
1223impl<I, F> Iterator for Update<I, F>
1224where
1225    I: Iterator,
1226    F: FnMut(&mut I::Item),
1227{
1228    type Item = I::Item;
1229
1230    fn next(&mut self) -> Option<Self::Item> {
1231        if let Some(mut v) = self.iter.next() {
1232            (self.f)(&mut v);
1233            Some(v)
1234        } else {
1235            None
1236        }
1237    }
1238
1239    fn size_hint(&self) -> (usize, Option<usize>) {
1240        self.iter.size_hint()
1241    }
1242
1243    fn fold<Acc, G>(self, init: Acc, mut g: G) -> Acc
1244        where G: FnMut(Acc, Self::Item) -> Acc,
1245    {
1246        let mut f = self.f;
1247        self.iter.fold(init, move |acc, mut v| { f(&mut v); g(acc, v) })
1248    }
1249
1250    // if possible, re-use inner iterator specializations in collect
1251    fn collect<C>(self) -> C
1252        where C: FromIterator<Self::Item>
1253    {
1254        let mut f = self.f;
1255        self.iter.map(move |mut v| { f(&mut v); v }).collect()
1256    }
1257}
1258
1259impl<I, F> ExactSizeIterator for Update<I, F>
1260where
1261    I: ExactSizeIterator,
1262    F: FnMut(&mut I::Item),
1263{}
1264
1265impl<I, F> DoubleEndedIterator for Update<I, F>
1266where
1267    I: DoubleEndedIterator,
1268    F: FnMut(&mut I::Item),
1269{
1270    fn next_back(&mut self) -> Option<Self::Item> {
1271        if let Some(mut v) = self.iter.next_back() {
1272            (self.f)(&mut v);
1273            Some(v)
1274        } else {
1275            None
1276        }
1277    }
1278}