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