2 use std
::iter
::IntoIterator
;
4 use std
::cell
::RefCell
;
6 /// A wrapper for `Rc<RefCell<I>>`, that implements the `Iterator` trait.
8 /// The boxed iterator.
9 pub rciter
: Rc
<RefCell
<I
>>,
12 /// Return an iterator inside a `Rc<RefCell<_>>` wrapper.
14 /// The returned `RcIter` can be cloned, and each clone will refer back to the
15 /// same original iterator.
17 /// `RcIter` allows doing interesting things like using `.zip()` on an iterator with
18 /// itself, at the cost of runtime borrow checking which may have a performance
21 /// Iterator element type is `Self::Item`.
24 /// use itertools::rciter;
25 /// use itertools::zip;
27 /// // In this example a range iterator is created and we iterate it using
28 /// // three separate handles (two of them given to zip).
29 /// // We also use the IntoIterator implementation for `&RcIter`.
31 /// let mut iter = rciter(0..9);
32 /// let mut z = zip(&iter, &iter);
34 /// assert_eq!(z.next(), Some((0, 1)));
35 /// assert_eq!(z.next(), Some((2, 3)));
36 /// assert_eq!(z.next(), Some((4, 5)));
37 /// assert_eq!(iter.next(), Some(6));
38 /// assert_eq!(z.next(), Some((7, 8)));
39 /// assert_eq!(z.next(), None);
42 /// **Panics** in iterator methods if a borrow error is encountered in the
43 /// iterator methods. It can only happen if the `RcIter` is reentered in
44 /// `.next()`, i.e. if it somehow participates in an “iterator knot”
45 /// where it is an adaptor of itself.
46 pub fn rciter
<I
>(iterable
: I
) -> RcIter
<I
::IntoIter
>
49 RcIter { rciter: Rc::new(RefCell::new(iterable.into_iter())) }
52 impl<I
> Clone
for RcIter
<I
> {
54 fn clone(&self) -> RcIter
<I
> {
55 RcIter { rciter: self.rciter.clone() }
59 impl<A
, I
> Iterator
for RcIter
<I
>
60 where I
: Iterator
<Item
= A
>
64 fn next(&mut self) -> Option
<A
> {
65 self.rciter
.borrow_mut().next()
69 fn size_hint(&self) -> (usize, Option
<usize>) {
70 // To work sanely with other API that assume they own an iterator,
71 // so it can't change in other places, we can't guarantee as much
72 // in our size_hint. Other clones may drain values under our feet.
73 let (_
, hi
) = self.rciter
.borrow().size_hint();
78 impl<I
> DoubleEndedIterator
for RcIter
<I
>
79 where I
: DoubleEndedIterator
82 fn next_back(&mut self) -> Option
<I
::Item
> {
83 self.rciter
.borrow_mut().next_back()
87 /// Return an iterator from `&RcIter<I>` (by simply cloning it).
88 impl<'a
, I
> IntoIterator
for &'a RcIter
<I
>
92 type IntoIter
= RcIter
<I
>;
94 fn into_iter(self) -> RcIter
<I
> {