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() {
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::*, traversal_order::{BreadthFirst, DepthFirst}};
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(
251 1,
252 vec![TestTree::new(2), TestTree::new(3)],
253 );
254
255 // Double each value using mutable depth-first traversal
256 {
257 let mut iter = tree.iter_mut::<DepthFirst>();
258 while let Some(mut node) = iter.next() {
259 node.value = node.value * 2;
260 }
261 }
262
263 // Verify the values were modified correctly
264 let values: Vec<i32> = tree.iter::<DepthFirst>().map(|node| node.value).collect();
265 assert_eq!(values, vec![2, 4, 6]);
266 }
267
268 #[test]
269 fn test_mutable_breadth_first_traversal() {
270 // Create a test tree:
271 // 1
272 // / \
273 // 2 3
274 // /
275 // 4
276 let mut tree = TestTree::with_children(
277 1,
278 vec![
279 TestTree::with_children(2, vec![TestTree::new(4)]),
280 TestTree::new(3),
281 ],
282 );
283
284 // Add 10 to each value using mutable breadth-first traversal
285 {
286 let mut iter = tree.iter_mut::<BreadthFirst>();
287 while let Some(mut node) = iter.next() {
288 node.value += 10;
289 }
290 }
291
292 // Verify the values were modified correctly
293 let values: Vec<i32> = tree.iter::<BreadthFirst>().map(|node| node.value).collect();
294 assert_eq!(values, vec![11, 12, 13, 14]);
295 }
296
297 #[test]
298 fn test_forest_mutable_traversal() {
299 // Create two trees
300 let mut tree1 = TestTree::with_children(1, vec![TestTree::new(2)]);
301 let mut tree2 = TestTree::with_children(3, vec![TestTree::new(4)]);
302
303 // Create a vector to hold mutable references
304 let mut roots = Vec::new();
305 roots.push(&mut tree1);
306 roots.push(&mut tree2);
307
308 // Create a mutable iterator with multiple roots - modify one at a time
309 for tree in &mut roots {
310 let mut iter = tree.iter_mut::<DepthFirst>();
311 while let Some(mut node) = iter.next() {
312 node.value += 100;
313 }
314 }
315
316 // Verify the values were modified
317 let values1: Vec<i32> = tree1.iter::<DepthFirst>().map(|node| node.value).collect();
318 let values2: Vec<i32> = tree2.iter::<DepthFirst>().map(|node| node.value).collect();
319
320 assert_eq!(values1, vec![101, 102]);
321 assert_eq!(values2, vec![103, 104]);
322 }
323
324 #[test]
325 fn test_adding_children_during_traversal() {
326 // Create a simple tree
327 let mut tree = TestTree::new(1);
328
329 // Add children during traversal
330 {
331 let mut iter = tree.iter_mut::<DepthFirst>();
332 while let Some(mut node) = iter.next() {
333 // Only add children to the root node
334 if node.value == 1 {
335 node.children.push(TestTree::new(2));
336 node.children.push(TestTree::new(3));
337 }
338 }
339 }
340
341 // Verify the new structure
342 let values: Vec<i32> = tree.iter::<DepthFirst>().map(|node| node.value).collect();
343 assert_eq!(values, vec![1, 2, 3]);
344 }
345}