itertools/
rciter_impl.rs

1
2use std::iter::IntoIterator;
3use std::rc::Rc;
4use std::cell::RefCell;
5
6/// A wrapper for `Rc<RefCell<I>>`, that implements the `Iterator` trait.
7#[derive(Debug)]
8pub struct RcIter<I> {
9    /// The boxed iterator.
10    pub rciter: Rc<RefCell<I>>,
11}
12
13/// Return an iterator inside a `Rc<RefCell<_>>` wrapper.
14///
15/// The returned `RcIter` can be cloned, and each clone will refer back to the
16/// same original iterator.
17///
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
20/// penalty.
21///
22/// Iterator element type is `Self::Item`.
23///
24/// ```
25/// use itertools::rciter;
26/// use itertools::zip;
27///
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`.
31///
32/// let mut iter = rciter(0..9);
33/// let mut z = zip(&iter, &iter);
34///
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);
41/// ```
42///
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.
47pub fn rciter<I>(iterable: I) -> RcIter<I::IntoIter>
48    where I: IntoIterator
49{
50    RcIter { rciter: Rc::new(RefCell::new(iterable.into_iter())) }
51}
52
53impl<I> Clone for RcIter<I> {
54    #[inline]
55    fn clone(&self) -> RcIter<I> {
56        RcIter { rciter: self.rciter.clone() }
57    }
58}
59
60impl<A, I> Iterator for RcIter<I>
61    where I: Iterator<Item = A>
62{
63    type Item = A;
64    #[inline]
65    fn next(&mut self) -> Option<A> {
66        self.rciter.borrow_mut().next()
67    }
68
69    #[inline]
70    fn size_hint(&self) -> (usize, Option<usize>) {
71        // To work sanely with other API that assume they own an iterator,
72        // so it can't change in other places, we can't guarantee as much
73        // in our size_hint. Other clones may drain values under our feet.
74        let (_, hi) = self.rciter.borrow().size_hint();
75        (0, hi)
76    }
77}
78
79impl<I> DoubleEndedIterator for RcIter<I>
80    where I: DoubleEndedIterator
81{
82    #[inline]
83    fn next_back(&mut self) -> Option<I::Item> {
84        self.rciter.borrow_mut().next_back()
85    }
86}
87
88/// Return an iterator from `&RcIter<I>` (by simply cloning it).
89impl<'a, I> IntoIterator for &'a RcIter<I>
90    where I: Iterator
91{
92    type Item = I::Item;
93    type IntoIter = RcIter<I>;
94
95    fn into_iter(self) -> RcIter<I> {
96        self.clone()
97    }
98}