tree_iter/
iter_mut.rs

1use std::{
2    collections::VecDeque,
3    marker::PhantomData,
4    ops::{Deref, DerefMut},
5};
6
7use crate::traversal_order::{BreadthFirst, DepthFirst, TraversalOrder};
8
9/// Trait for mutable tree traversal.
10///
11/// This trait defines the interface required to iterate over a tree structure
12/// with mutable access to the nodes. Any type that implements this trait can be
13/// traversed using the provided mutable iterators.
14///
15/// Implementing this trait requires providing a way to access the children of a node
16/// mutably, which enables the iterator to traverse the tree structure.
17///
18/// # Examples
19///
20/// ```rust
21/// use tree_iter::prelude::*;
22/// use tree_iter::tree::Node;
23///
24/// // Create a simple tree
25/// let mut tree = Node {
26///     value: 1,
27///     children: vec![
28///         Node { value: 2, children: vec![] },
29///         Node { value: 3, children: vec![] },
30///     ],
31/// };
32///
33/// // Mutably iterate and modify values
34/// let mut iter = tree.iter_mut::<DepthFirst>();
35/// while let Some(mut node) = iter.next() {
36///     node.value *= 2;
37/// }
38///
39/// // Values have been doubled
40/// assert_eq!(tree.value, 2);
41/// ```
42pub trait TreeNodeMut {
43    /// Returns a mutable iterator over the children of this node.
44    ///
45    /// This method must be implemented by all types implementing `TreeNodeMut`.
46    fn children_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut Self>;
47
48    /// Creates a mutable iterator that traverses the tree starting from this node.
49    ///
50    /// # Type Parameters
51    ///
52    /// * `T` - The traversal order strategy to use (e.g., `DepthFirst` or `BreadthFirst`).
53    fn iter_mut<T: TraversalOrder>(&mut self) -> TreeMutIter<'_, Self, T>
54    where
55        Self: Sized,
56    {
57        TreeMutIter::new([self])
58    }
59}
60
61/// A mutable iterator over tree nodes in a specified traversal order.
62///
63/// This struct provides the implementation for traversing a tree structure
64/// with mutable access to nodes implementing the `TreeNodeMut` trait.
65///
66/// # Type Parameters
67///
68/// * `'a` - The lifetime of the tree nodes being traversed.
69/// * `N` - The type of tree node.
70/// * `T` - The traversal order strategy (e.g., `DepthFirst` or `BreadthFirst`).
71#[derive(Debug)]
72pub struct TreeMutIter<'a, N, T> {
73    /// Queue of nodes to be visited.
74    nodes: VecDeque<&'a mut N>,
75    /// Phantom data to track the traversal order type.
76    _order: PhantomData<T>,
77}
78
79impl<'a, N, T> TreeMutIter<'a, N, T> {
80    /// Creates a new mutable tree iterator from a collection of root nodes.
81    ///
82    /// # Parameters
83    ///
84    /// * `roots` - An iterator yielding mutable references to the root nodes to start traversal from.
85    pub fn new(roots: impl IntoIterator<Item = &'a mut N>) -> Self {
86        Self {
87            nodes: roots.into_iter().collect(),
88            _order: PhantomData,
89        }
90    }
91}
92
93/// A guard for mutable node references in breadth-first traversal.
94///
95/// This guard ensures that when a mutable reference is dropped, the node's children
96/// are correctly added to the traversal queue in breadth-first order.
97///
98/// The guard implements `Deref` and `DerefMut` to allow direct access to the underlying node.
99pub struct MutRefBFSGuard<'a: 'b, 'b, N: TreeNodeMut> {
100    /// Reference to the tree iterator.
101    iter: &'b mut TreeMutIter<'a, N, BreadthFirst>,
102    /// The current node being visited (wrapped in Option to allow taking ownership in drop).
103    node: Option<&'a mut N>,
104}
105
106impl<N: TreeNodeMut> Drop for MutRefBFSGuard<'_, '_, N> {
107    /// When the guard is dropped, add the node's children to the traversal queue.
108    ///
109    /// This is where the breadth-first traversal logic is implemented - children are
110    /// added to the back of the queue to be processed after all nodes at the current level.
111    fn drop(&mut self) {
112        let node = self.node.take().unwrap();
113        self.iter.nodes.extend(node.children_mut());
114    }
115}
116
117impl<N: TreeNodeMut> Deref for MutRefBFSGuard<'_, '_, N> {
118    type Target = N;
119
120    /// Provides immutable access to the wrapped node.
121    fn deref(&self) -> &Self::Target {
122        self.node.as_ref().unwrap()
123    }
124}
125
126impl<N: TreeNodeMut> DerefMut for MutRefBFSGuard<'_, '_, N> {
127    /// Provides mutable access to the wrapped node.
128    fn deref_mut(&mut self) -> &mut Self::Target {
129        self.node.as_mut().unwrap()
130    }
131}
132
133impl<'a, N: TreeNodeMut> TreeMutIter<'a, N, BreadthFirst> {
134    /// Returns the next node in breadth-first order.
135    ///
136    /// This method returns a guard that implements `DerefMut` to provide
137    /// mutable access to the node. When the guard is dropped, the node's children
138    /// are added to the traversal queue in breadth-first order.
139    pub fn next<'b>(&'b mut self) -> Option<MutRefBFSGuard<'a, 'b, N>> {
140        self.nodes.pop_front().map(|node| MutRefBFSGuard {
141            iter: self,
142            node: Some(node),
143        })
144    }
145}
146
147/// A guard for mutable node references in depth-first traversal.
148///
149/// This guard ensures that when a mutable reference is dropped, the node's children
150/// are correctly added to the traversal queue in depth-first order.
151///
152/// The guard implements `Deref` and `DerefMut` to allow direct access to the underlying node.
153pub struct MutRefDFSGuard<'a: 'b, 'b, N: TreeNodeMut> {
154    /// Reference to the tree iterator.
155    iter: &'b mut TreeMutIter<'a, N, DepthFirst>,
156    /// The current node being visited (wrapped in Option to allow taking ownership in drop).
157    node: Option<&'a mut N>,
158}
159
160impl<N: TreeNodeMut> Drop for MutRefDFSGuard<'_, '_, N> {
161    /// When the guard is dropped, add the node's children to the traversal queue.
162    ///
163    /// This is where the depth-first traversal logic is implemented - children are
164    /// added to the front of the queue in reverse order to ensure the leftmost child
165    /// is processed first.
166    fn drop(&mut self) {
167        let node = self.node.take().unwrap();
168        for child in node.children_mut().rev() {
169            self.iter.nodes.push_front(child);
170        }
171    }
172}
173
174impl<N: TreeNodeMut> Deref for MutRefDFSGuard<'_, '_, N> {
175    type Target = N;
176
177    /// Provides immutable access to the wrapped node.
178    fn deref(&self) -> &Self::Target {
179        self.node.as_ref().unwrap()
180    }
181}
182
183impl<N: TreeNodeMut> DerefMut for MutRefDFSGuard<'_, '_, N> {
184    /// Provides mutable access to the wrapped node.
185    fn deref_mut(&mut self) -> &mut Self::Target {
186        self.node.as_mut().unwrap()
187    }
188}
189
190impl<'a, N: TreeNodeMut> TreeMutIter<'a, N, DepthFirst> {
191    /// Returns the next node in depth-first order.
192    ///
193    /// This method returns a guard that implements `DerefMut` to provide
194    /// mutable access to the node. When the guard is dropped, the node's children
195    /// are added to the traversal queue in depth-first order.
196    pub fn next<'b>(&'b mut self) -> Option<MutRefDFSGuard<'a, 'b, N>> {
197        self.nodes.pop_front().map(|node| MutRefDFSGuard {
198            iter: self,
199            node: Some(node),
200        })
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use crate::prelude::*;
207    use crate::tree::Node;
208
209    #[test]
210    fn test_mutable_depth_first_traversal() {
211        // Create a test tree:
212        //      1
213        //     / \
214        //    2   3
215        let mut tree = Node {
216            value: 1,
217            children: vec![Node::new(2), Node::new(3)],
218        };
219
220        // Double each value using mutable depth-first traversal
221        {
222            let mut iter = tree.iter_mut::<DepthFirst>();
223            while let Some(mut node) = iter.next() {
224                node.value = node.value * 2;
225            }
226        }
227
228        // Verify the values were modified correctly
229        let values: Vec<i32> = tree.iter::<DepthFirst>().map(|node| node.value).collect();
230        assert_eq!(values, vec![2, 4, 6]);
231    }
232
233    #[test]
234    fn test_mutable_breadth_first_traversal() {
235        // Create a test tree:
236        //      1
237        //     / \
238        //    2   3
239        //   /
240        //  4
241        let mut tree = Node {
242            value: 1,
243            children: vec![
244                Node {
245                    value: 2,
246                    children: vec![Node::new(4)],
247                },
248                Node::new(3),
249            ],
250        };
251
252        // Add 10 to each value using mutable breadth-first traversal
253        {
254            let mut iter = tree.iter_mut::<BreadthFirst>();
255            while let Some(mut node) = iter.next() {
256                node.value += 10;
257            }
258        }
259
260        // Verify the values were modified correctly
261        let values: Vec<i32> = tree.iter::<BreadthFirst>().map(|node| node.value).collect();
262        assert_eq!(values, vec![11, 12, 13, 14]);
263    }
264
265    #[test]
266    fn test_forest_mutable_traversal() {
267        // Create two trees
268        let mut tree1 = Node {
269            value: 1,
270            children: vec![Node::new(2)],
271        };
272        let mut tree2 = Node {
273            value: 3,
274            children: vec![Node::new(4)],
275        };
276
277        // Create a vector to hold mutable references
278        let mut roots = Vec::new();
279        roots.push(&mut tree1);
280        roots.push(&mut tree2);
281
282        // Create a mutable iterator with multiple roots - modify one at a time
283        for tree in &mut roots {
284            let mut iter = tree.iter_mut::<DepthFirst>();
285            while let Some(mut node) = iter.next() {
286                node.value += 100;
287            }
288        }
289
290        // Verify the values were modified
291        let values1: Vec<i32> = tree1.iter::<DepthFirst>().map(|node| node.value).collect();
292        let values2: Vec<i32> = tree2.iter::<DepthFirst>().map(|node| node.value).collect();
293
294        assert_eq!(values1, vec![101, 102]);
295        assert_eq!(values2, vec![103, 104]);
296    }
297
298    #[test]
299    fn test_adding_children_during_traversal() {
300        // Create a simple tree
301        let mut tree = Node::new(1);
302
303        // Add children during traversal
304        {
305            let mut iter = tree.iter_mut::<DepthFirst>();
306            while let Some(mut node) = iter.next() {
307                // Only add children to the root node
308                if node.value == 1 {
309                    node.children.push(Node::new(2));
310                    node.children.push(Node::new(3));
311                }
312            }
313        }
314
315        // Verify the new structure
316        let values: Vec<i32> = tree.iter::<DepthFirst>().map(|node| node.value).collect();
317        assert_eq!(values, vec![1, 2, 3]);
318    }
319}