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