syntree/node/
children.rs

1use core::iter::FusedIterator;
2
3use crate::flavor::Flavor;
4use crate::links::Links;
5use crate::node::{Node, SkipTokens};
6use crate::pointer::Pointer;
7
8/// An iterator that iterates over the [`Node::next`] elements of a node. This is
9/// typically used for iterating over the children of a tree.
10///
11/// Note that this iterator also implements [Default], allowing it to
12/// effectively create an empty iterator in case a particular sibling is not
13/// available:
14///
15/// ```
16/// let mut tree = syntree::tree! {
17///     "root" => {
18///         "child1" => {
19///             "child2" => {
20///                 "token1"
21///             }
22///         },
23///         "child3" => {}
24///     }
25/// };
26///
27/// let mut it = tree.first().and_then(|n| n.last()).map(|n| n.children()).unwrap_or_default();
28/// assert_eq!(it.next().map(|n| n.value()), None);
29/// # Ok::<_, Box<dyn core::error::Error>>(())
30/// ```
31///
32/// See [`Tree::children`][crate::Tree::children] or [`Node::children`].
33///
34/// # Examples
35///
36/// ```
37/// let mut tree = syntree::tree! {
38///     "root" => {
39///         "child1" => {
40///             "child2" => {}
41///         },
42///         "child3" => {}
43///     },
44///     "root2" => {
45///         "child4" => {}
46///     }
47/// };
48///
49/// assert_eq!(
50///     tree.children().map(|n| n.value()).collect::<Vec<_>>(),
51///     ["root", "root2"]
52/// );
53///
54/// assert_eq!(
55///     tree.children().rev().map(|n| n.value()).collect::<Vec<_>>(),
56///     ["root2", "root"]
57/// );
58///
59/// let root = tree.first().ok_or("missing root node")?;
60///
61/// assert_eq!(
62///     root.children().map(|n| n.value()).collect::<Vec<_>>(),
63///     ["child1", "child3"]
64/// );
65///
66/// assert_eq!(
67///     root.children().rev().map(|n| n.value()).collect::<Vec<_>>(),
68///     ["child3", "child1"]
69/// );
70/// # Ok::<_, Box<dyn core::error::Error>>(())
71/// ```
72pub struct Children<'a, T, F>
73where
74    T: Copy,
75    F: Flavor,
76{
77    tree: &'a [Links<T, F::Index, F::Pointer>],
78    first: Option<F::Pointer>,
79    last: Option<F::Pointer>,
80}
81
82impl<'a, T, F> Children<'a, T, F>
83where
84    T: Copy,
85    F: Flavor,
86{
87    /// Construct a new child iterator.
88    #[inline]
89    pub(crate) const fn new(
90        tree: &'a [Links<T, F::Index, F::Pointer>],
91        first: Option<F::Pointer>,
92        last: Option<F::Pointer>,
93    ) -> Self {
94        Self { tree, first, last }
95    }
96
97    /// Construct a [`SkipTokens`] iterator from the remainder of this iterator.
98    /// This filters out childless nodes, also known as tokens.
99    ///
100    /// See [`SkipTokens`] for documentation.
101    #[must_use]
102    pub const fn skip_tokens(self) -> SkipTokens<Self> {
103        SkipTokens::new(self)
104    }
105
106    /// Get the next node from the iterator. This advances past all non-node
107    /// data.
108    ///
109    /// # Examples
110    ///
111    /// ```
112    /// let tree = syntree::tree! {
113    ///     ("token1", 1),
114    ///     "child1" => {
115    ///         "token2"
116    ///     },
117    ///     ("token3", 1),
118    ///     "child2" => {
119    ///         "token4"
120    ///     },
121    ///     ("token5", 1),
122    ///     "child3" => {
123    ///         "token6"
124    ///     },
125    ///     ("token7", 1)
126    /// };
127    ///
128    /// let mut it = tree.children();
129    /// let mut out = Vec::new();
130    ///
131    /// while let Some(n) = it.next_node() {
132    ///     out.push(n.value());
133    /// }
134    ///
135    /// assert_eq!(out, ["child1", "child2", "child3"]);
136    ///
137    /// let mut it = tree.children();
138    ///
139    /// let c1 = it.next_node().ok_or("missing child1")?;
140    /// let c2 = it.next_node().ok_or("missing child2")?;
141    /// let c3 = it.next_node().ok_or("missing child3")?;
142    ///
143    /// assert_eq!([c1.value(), c2.value(), c3.value()], ["child1", "child2", "child3"]);
144    /// # Ok::<_, Box<dyn core::error::Error>>(())
145    /// ```
146    #[inline]
147    pub fn next_node(&mut self) -> Option<Node<'a, T, F>> {
148        self.find(|n| n.has_children())
149    }
150}
151
152impl<'a, T, F> Iterator for Children<'a, T, F>
153where
154    T: Copy,
155    F: Flavor,
156{
157    type Item = Node<'a, T, F>;
158
159    #[inline]
160    fn next(&mut self) -> Option<Self::Item> {
161        let first = self.first.take()?;
162        let node = self.tree.get(first.get())?;
163
164        if first != self.last? {
165            self.first = node.next;
166        }
167
168        Some(Node::new(node, self.tree))
169    }
170}
171
172impl<T, F> DoubleEndedIterator for Children<'_, T, F>
173where
174    T: Copy,
175    F: Flavor,
176{
177    #[inline]
178    fn next_back(&mut self) -> Option<Self::Item> {
179        let last = self.last.take()?;
180        let node = self.tree.get(last.get())?;
181
182        if last != self.first? {
183            self.last = node.prev;
184        }
185
186        Some(Node::new(node, self.tree))
187    }
188}
189
190impl<T, F> FusedIterator for Children<'_, T, F>
191where
192    T: Copy,
193    F: Flavor,
194{
195}
196
197impl<T, F> Clone for Children<'_, T, F>
198where
199    T: Copy,
200    F: Flavor,
201{
202    #[inline]
203    fn clone(&self) -> Self {
204        Self {
205            tree: self.tree,
206            first: self.first,
207            last: self.last,
208        }
209    }
210}
211
212impl<T, F> Default for Children<'_, T, F>
213where
214    T: Copy,
215    F: Flavor,
216{
217    #[inline]
218    fn default() -> Self {
219        Self {
220            tree: &[],
221            first: None,
222            last: None,
223        }
224    }
225}