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![Node::new(2), Node::new(3)],
28/// };
29///
30/// // Mutably iterate and modify values
31/// let mut iter = tree.iter_mut::<DepthFirst>();
32/// while let Some(mut node) = iter.next() {
33///     node.value *= 2;
34/// }
35///
36/// // Values have been doubled
37/// assert_eq!(tree.value, 2);
38/// ```
39pub trait TreeNodeMut {
40    /// Returns a mutable iterator over the children of this node.
41    ///
42    /// This method must be implemented by all types implementing `TreeNodeMut`.
43    fn children_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut Self>;
44
45    /// Creates a mutable iterator that traverses the tree starting from this node.
46    ///
47    /// # Type Parameters
48    ///
49    /// * `T` - The traversal order strategy to use (e.g., `DepthFirst` or `BreadthFirst`).
50    fn iter_mut<T: TraversalOrder>(&mut self) -> TreeIterMut<'_, Self, T>
51    where
52        Self: Sized,
53    {
54        TreeIterMut::new([self])
55    }
56}
57
58/// A mutable iterator over tree nodes in a specified traversal order.
59///
60/// This struct provides the implementation for traversing a tree structure
61/// with mutable access to nodes implementing the `TreeNodeMut` trait.
62///
63/// # Type Parameters
64///
65/// * `'a` - The lifetime of the tree nodes being traversed.
66/// * `N` - The type of tree node.
67/// * `T` - The traversal order strategy (e.g., `DepthFirst` or `BreadthFirst`).
68#[derive(Debug)]
69pub struct TreeIterMut<'a, N, T> {
70    /// Queue of nodes to be visited.
71    nodes: VecDeque<&'a mut N>,
72    /// Phantom data to track the traversal order type.
73    _order: PhantomData<T>,
74}
75
76impl<'a, N, T> TreeIterMut<'a, N, T> {
77    /// Creates a new mutable tree iterator from a collection of root nodes.
78    ///
79    /// # Parameters
80    ///
81    /// * `roots` - An iterator yielding mutable references to the root nodes to start traversal from.
82    pub fn new(roots: impl IntoIterator<Item = &'a mut N>) -> Self {
83        Self {
84            nodes: roots.into_iter().collect(),
85            _order: PhantomData,
86        }
87    }
88}
89
90/// A guard for mutable node references in breadth-first traversal.
91///
92/// This guard ensures that when a mutable reference is dropped, the node's children
93/// are correctly added to the traversal queue in breadth-first order.
94///
95/// The guard implements `Deref` and `DerefMut` to allow direct access to the underlying node.
96#[derive(Debug)]
97pub struct BFSRefMutGuard<'a: 'b, 'b, N: TreeNodeMut> {
98    /// Reference to the tree iterator.
99    iter: &'b mut TreeIterMut<'a, N, BreadthFirst>,
100    /// The current node being visited (wrapped in Option to allow taking ownership in drop).
101    node: Option<&'a mut N>,
102}
103
104impl<N: TreeNodeMut> Drop for BFSRefMutGuard<'_, '_, N> {
105    /// When the guard is dropped, add the node's children to the traversal queue.
106    ///
107    /// This is where the breadth-first traversal logic is implemented - children are
108    /// added to the back of the queue to be processed after all nodes at the current level.
109    fn drop(&mut self) {
110        let node = self.node.take().unwrap();
111        self.iter.nodes.extend(node.children_mut());
112    }
113}
114
115impl<N: TreeNodeMut> Deref for BFSRefMutGuard<'_, '_, N> {
116    type Target = N;
117
118    /// Provides immutable access to the wrapped node.
119    fn deref(&self) -> &Self::Target {
120        self.node.as_ref().unwrap()
121    }
122}
123
124impl<N: TreeNodeMut> DerefMut for BFSRefMutGuard<'_, '_, N> {
125    /// Provides mutable access to the wrapped node.
126    fn deref_mut(&mut self) -> &mut Self::Target {
127        self.node.as_mut().unwrap()
128    }
129}
130
131impl<'a, N: TreeNodeMut> TreeIterMut<'a, N, BreadthFirst> {
132    /// Returns the next node in breadth-first order.
133    ///
134    /// This method returns a guard that implements `DerefMut` to provide
135    /// mutable access to the node. When the guard is dropped, the node's children
136    /// are added to the traversal queue in breadth-first order.
137    pub fn next(&mut self) -> Option<BFSRefMutGuard<'a, '_, N>> {
138        self.nodes.pop_front().map(|node| BFSRefMutGuard {
139            iter: self,
140            node: Some(node),
141        })
142    }
143}
144
145/// A guard for mutable node references in depth-first traversal.
146///
147/// This guard ensures that when a mutable reference is dropped, the node's children
148/// are correctly added to the traversal queue in depth-first order.
149///
150/// The guard implements `Deref` and `DerefMut` to allow direct access to the underlying node.
151#[derive(Debug)]
152pub struct DFSRefMutGuard<'a: 'b, 'b, N: TreeNodeMut> {
153    /// Reference to the tree iterator.
154    iter: &'b mut TreeIterMut<'a, N, DepthFirst>,
155    /// The current node being visited (wrapped in Option to allow taking ownership in drop).
156    node: Option<&'a mut N>,
157}
158
159impl<N: TreeNodeMut> Drop for DFSRefMutGuard<'_, '_, N> {
160    /// When the guard is dropped, add the node's children to the traversal queue.
161    ///
162    /// This is where the depth-first traversal logic is implemented - children are
163    /// added to the front of the queue in reverse order to ensure the leftmost child
164    /// is processed first.
165    fn drop(&mut self) {
166        let node = self.node.take().unwrap();
167        for child in node.children_mut().rev() {
168            self.iter.nodes.push_front(child);
169        }
170    }
171}
172
173impl<N: TreeNodeMut> Deref for DFSRefMutGuard<'_, '_, N> {
174    type Target = N;
175
176    /// Provides immutable access to the wrapped node.
177    fn deref(&self) -> &Self::Target {
178        self.node.as_ref().unwrap()
179    }
180}
181
182impl<N: TreeNodeMut> DerefMut for DFSRefMutGuard<'_, '_, N> {
183    /// Provides mutable access to the wrapped node.
184    fn deref_mut(&mut self) -> &mut Self::Target {
185        self.node.as_mut().unwrap()
186    }
187}
188
189impl<'a, N: TreeNodeMut> TreeIterMut<'a, N, DepthFirst> {
190    /// Returns the next node in depth-first order.
191    ///
192    /// This method returns a guard that implements `DerefMut` to provide
193    /// mutable access to the node. When the guard is dropped, the node's children
194    /// are added to the traversal queue in depth-first order.
195    pub fn next(&mut self) -> Option<DFSRefMutGuard<'a, '_, N>> {
196        self.nodes.pop_front().map(|node| DFSRefMutGuard {
197            iter: self,
198            node: Some(node),
199        })
200    }
201}