standard_lib/collections/cons/tree/
iter.rs1use std::{mem, rc::Rc};
2
3use super::{ConsBranch, ConsNode};
4
5pub struct Iter<'a, T> {
7 pub(crate) inner: Option<&'a ConsNode<T>>,
8}
9
10impl<'a, T> Iterator for Iter<'a, T> {
11 type Item = &'a T;
12
13 fn next(&mut self) -> Option<Self::Item> {
14 let ConsNode { value, next } = self.inner?;
15 self.inner = next.inner.as_deref();
16 Some(value)
17 }
18}
19
20impl<'a, T> Clone for Iter<'a, T> {
21 fn clone(&self) -> Self {
22 Self {
23 inner: self.inner.clone(),
24 }
25 }
26}
27
28pub struct OwnedIter<T: Clone> {
30 pub(crate) inner: ConsBranch<T>,
31}
32
33impl<T: Clone> OwnedIter<T> {
34 pub fn remainder(self) -> ConsBranch<T> {
36 self.inner
37 }
38}
39
40impl<T: Clone> Iterator for OwnedIter<T> {
41 type Item = T;
42
43 fn next(&mut self) -> Option<Self::Item> {
44 self.inner.pop_to_owned()
45 }
46}
47
48pub struct UniqueIter<T> {
50 pub(crate) inner: ConsBranch<T>,
51}
52
53impl<T> UniqueIter<T> {
54 pub fn remainder(self) -> ConsBranch<T> {
58 self.inner
59 }
60}
61
62impl<T> Iterator for UniqueIter<T> {
63 type Item = T;
64
65 fn next(&mut self) -> Option<Self::Item> {
66 self.inner.pop_if_unique()
67 }
68}
69
70pub struct RcIter<T> {
72 pub(crate) inner: ConsBranch<T>,
73}
74
75impl<T> RcIter<T> {
76 pub fn remainder(self) -> ConsBranch<T> {
78 self.inner
79 }
80}
81
82impl<T> Iterator for RcIter<T> {
83 type Item = Rc<ConsNode<T>>;
84
85 fn next(&mut self) -> Option<Self::Item> {
86 let inner = mem::take(&mut self.inner.inner);
87
88 match inner {
89 Some(rc) => {
90 self.inner = rc.next.clone();
91 Some(rc)
92 },
93 None => {
94 self.inner.inner = inner;
95 None
96 },
97 }
98 }
99}