orx_tree/traversal/depth_first/
iter_ptr.rs

1use super::dfs_enumeration::DepthFirstEnumeration;
2use super::stack::Item;
3use crate::TreeVariant;
4use crate::tree_variant::RefsChildren;
5use alloc::vec::Vec;
6use core::marker::PhantomData;
7use orx_self_or::SoM;
8use orx_selfref_col::NodePtr;
9
10pub struct DfsIterPtr<V, E, S = Vec<Item<V, E>>>
11where
12    E: DepthFirstEnumeration,
13    V: TreeVariant,
14    S: SoM<Vec<Item<V, E>>>,
15{
16    stack: S,
17    phantom: PhantomData<(V, E)>,
18}
19
20impl<V, E, S> From<(S, NodePtr<V>)> for DfsIterPtr<V, E, S>
21where
22    E: DepthFirstEnumeration,
23    V: TreeVariant,
24    S: SoM<Vec<Item<V, E>>>,
25{
26    fn from((mut stack, root): (S, NodePtr<V>)) -> Self {
27        stack.get_mut().clear();
28        stack.get_mut().push(E::from_root(root));
29        Self {
30            stack,
31            phantom: PhantomData,
32        }
33    }
34}
35
36impl<V, E> Default for DfsIterPtr<V, E, Vec<Item<V, E>>>
37where
38    E: DepthFirstEnumeration,
39    V: TreeVariant,
40{
41    fn default() -> Self {
42        Self {
43            stack: Vec::default(),
44            phantom: PhantomData,
45        }
46    }
47}
48
49impl<V, E> Clone for DfsIterPtr<V, E, Vec<Item<V, E>>>
50where
51    E: DepthFirstEnumeration,
52    V: TreeVariant,
53    Item<V, E>: Clone,
54{
55    fn clone(&self) -> Self {
56        Self {
57            stack: self.stack.clone(),
58            phantom: PhantomData,
59        }
60    }
61}
62
63impl<V, E, S> Iterator for DfsIterPtr<V, E, S>
64where
65    E: DepthFirstEnumeration,
66    V: TreeVariant,
67    S: SoM<Vec<Item<V, E>>>,
68{
69    type Item = Item<V, E>;
70
71    fn next(&mut self) -> Option<Self::Item> {
72        self.stack.get_mut().pop().inspect(|element| {
73            let node_ptr = E::node_value(element);
74            let parent = unsafe { &*node_ptr.ptr() };
75            let children_ptr = parent.next().children_ptr().cloned();
76            let children = E::children(element, children_ptr).rev();
77            self.stack.get_mut().extend(children);
78        })
79    }
80}