orx_tree/
node_ref.rs

1use crate::{
2    Dfs, Node, NodeIdx, Traverser, Tree, TreeVariant,
3    aliases::{Col, N},
4    iter::AncestorsIterPtr,
5    memory::MemoryPolicy,
6    pinned_storage::PinnedStorage,
7    subtrees::{ClonedSubTree, CopiedSubTree},
8    traversal::{
9        Over, OverData,
10        enumeration::Enumeration,
11        enumerations::Val,
12        over::{OverDepthPtr, OverItem},
13        traverser_core::TraverserCore,
14    },
15    tree_variant::RefsChildren,
16};
17use orx_selfref_col::{NodePtr, Refs};
18
19pub trait NodeRefCore<'a, V, M, P>
20where
21    V: TreeVariant + 'a,
22    M: MemoryPolicy,
23    P: PinnedStorage,
24{
25    fn col(&self) -> &Col<V, M, P>;
26
27    fn node_ptr(&self) -> &NodePtr<V>;
28
29    #[inline(always)]
30    fn node(&self) -> &'a N<V> {
31        unsafe { &*self.node_ptr().ptr() }
32    }
33}
34
35impl<'a, V, M, P, X> NodeRef<'a, V, M, P> for X
36where
37    V: TreeVariant + 'a,
38    M: MemoryPolicy,
39    P: PinnedStorage,
40    X: NodeRefCore<'a, V, M, P>,
41{
42}
43
44/// Reference to a tree node.
45pub trait NodeRef<'a, V, M, P>: NodeRefCore<'a, V, M, P>
46where
47    V: TreeVariant + 'a,
48    M: MemoryPolicy,
49    P: PinnedStorage,
50{
51    /// Returns the node index of this node.
52    ///
53    /// Note that a [`NodeIdx`] is used to provide safe and constant time access to any node in the tree.
54    ///
55    /// Validity of node indices is crucial, while it is conveniently possible to have complete control
56    /// on this.
57    /// Please see the documentation of [`NodeIdx`] and [`MemoryPolicy`] for details.
58    fn idx(&self) -> NodeIdx<V> {
59        NodeIdx(orx_selfref_col::NodeIdx::new(
60            self.col().memory_state(),
61            self.node_ptr(),
62        ))
63    }
64
65    /// Returns true if this is the root node; equivalently, if its [`parent`] is none.
66    ///
67    /// [`parent`]: NodeRef::parent
68    ///
69    /// # Examples
70    ///
71    /// ```
72    /// use orx_tree::*;
73    ///
74    /// let mut tree = BinaryTree::<char>::new('r');
75    ///
76    /// let mut root = tree.root_mut();
77    /// assert!(root.is_root());
78    ///
79    /// root.push_children(['a', 'b']);
80    /// for node in root.children() {
81    ///     assert!(!node.is_root());
82    /// }
83    /// ```
84    #[inline(always)]
85    fn is_root(&self) -> bool {
86        self.node().prev().get().is_none()
87    }
88
89    /// Returns true if this is a leaf node; equivalently, if [`num_children`] is zero.
90    ///
91    /// [`num_children`]: NodeRef::num_children
92    ///
93    /// ```
94    /// use orx_tree::*;
95    ///
96    /// //      1
97    /// //     ╱ ╲
98    /// //    ╱   ╲
99    /// //   2     3
100    /// //  ╱ ╲   ╱
101    /// // 4   5 6
102    ///
103    /// let mut tree = DynTree::new(1);
104    /// assert_eq!(tree.get_root().unwrap().is_leaf(), true); // both root & leaf
105    ///
106    /// let mut root = tree.root_mut();
107    /// let [id2, id3] = root.push_children([2, 3]);
108    ///
109    /// let mut n2 = tree.node_mut(&id2);
110    /// let [id4, id5] = n2.push_children([4, 5]);
111    ///
112    /// let mut n3 = tree.node_mut(&id3);
113    /// let [id6] = n3.push_children([6]);
114    ///
115    /// // walk over any subtree rooted at a selected node
116    /// // with different traversals
117    ///
118    /// assert_eq!(tree.get_root().unwrap().is_leaf(), false);
119    /// assert_eq!(tree.node(&id2).is_leaf(), false);
120    /// assert_eq!(tree.node(&id3).is_leaf(), false);
121    ///
122    /// assert_eq!(tree.node(&id4).is_leaf(), true);
123    /// assert_eq!(tree.node(&id5).is_leaf(), true);
124    /// assert_eq!(tree.node(&id6).is_leaf(), true);
125    /// ```
126    #[inline(always)]
127    fn is_leaf(&self) -> bool {
128        self.num_children() == 0
129    }
130
131    /// Returns a reference to the data of the node.
132    ///
133    /// # Examples
134    ///
135    /// ```
136    /// use orx_tree::*;
137    ///
138    /// let mut tree = DynTree::new(0);
139    ///
140    /// let mut root = tree.root_mut();
141    /// assert_eq!(root.data(), &0);
142    ///
143    /// let [id_a] = root.push_children([1]);
144    /// let a = tree.node(&id_a);
145    /// assert_eq!(a.data(), &1);
146    /// ```
147    #[inline(always)]
148    #[allow(clippy::missing_panics_doc)]
149    fn data(&self) -> &'a V::Item {
150        self.node()
151            .data()
152            .expect("node holding a tree reference must be active")
153    }
154
155    /// Returns the number of child nodes of this node.
156    ///
157    /// # Examples
158    ///
159    /// ```
160    /// use orx_tree::*;
161    ///
162    /// let mut tree = DynTree::new(0);
163    ///
164    /// let mut root = tree.root_mut();
165    /// assert_eq!(root.num_children(), 0);
166    ///
167    /// let [id_a, id_b] = root.push_children([1, 2]);
168    /// assert_eq!(root.num_children(), 2);
169    ///
170    /// let mut node = tree.node_mut(&id_a);
171    /// node.push_child(3);
172    /// node.push_children([4, 5, 6]);
173    /// assert_eq!(node.num_children(), 4);
174    ///
175    /// assert_eq!(tree.node(&id_b).num_children(), 0);
176    /// ```
177    #[inline(always)]
178    fn num_children(&self) -> usize {
179        self.node().next().num_children()
180    }
181
182    /// Returns the number of siblings **including this node**.
183    /// In other words, it returns the `num_children` of its parent;
184    /// or returns 1 if this is the root.
185    ///
186    /// # Examples
187    ///
188    /// ```
189    /// use orx_tree::*;
190    ///
191    /// let mut tree = DynTree::new(0);
192    /// let [id1, id2, id3] = tree.root_mut().push_children([1, 2, 3]);
193    /// let id4 = tree.node_mut(&id3).push_child(4);
194    ///
195    /// assert_eq!(tree.root().num_siblings(), 1);
196    /// assert_eq!(tree.node(&id1).num_siblings(), 3);
197    /// assert_eq!(tree.node(&id2).num_siblings(), 3);
198    /// assert_eq!(tree.node(&id3).num_siblings(), 3);
199    /// assert_eq!(tree.node(&id4).num_siblings(), 1);
200    /// ```
201    fn num_siblings(&self) -> usize {
202        match self.parent() {
203            Some(parent) => parent.num_children(),
204            None => 1,
205        }
206    }
207
208    /// Returns an exact-sized iterator of children nodes of this node.
209    ///
210    /// # Examples
211    ///
212    /// ```
213    /// use orx_tree::*;
214    ///
215    /// // build the tree:
216    /// // r
217    /// // |-- a
218    /// //     |-- c, d, e
219    /// // |-- b
220    /// let mut tree = DynTree::<char>::new('r');
221    ///
222    /// let mut root = tree.root_mut();
223    /// let [id_a] = root.push_children(['a']);
224    /// root.push_child('b');
225    ///
226    /// let mut a = tree.node_mut(&id_a);
227    /// a.push_children(['c', 'd', 'e']);
228    ///
229    /// // iterate over children of nodes
230    ///
231    /// let root = tree.root();
232    /// let depth1: Vec<_> = root.children().map(|x| *x.data()).collect();
233    /// assert_eq!(depth1, ['a', 'b']);
234    ///
235    /// let b = root.children().nth(0).unwrap();
236    /// let depth2: Vec<_> = b.children().map(|x| *x.data()).collect();
237    /// assert_eq!(depth2, ['c', 'd', 'e']);
238    ///
239    /// // depth first - two levels deep
240    /// let mut data = vec![];
241    /// for node in root.children() {
242    ///     data.push(*node.data());
243    ///
244    ///     for child in node.children() {
245    ///         data.push(*child.data());
246    ///     }
247    /// }
248    ///
249    /// assert_eq!(data, ['a', 'c', 'd', 'e', 'b']);
250    /// ```
251    fn children(&'a self) -> impl ExactSizeIterator<Item = Node<'a, V, M, P>> {
252        self.node()
253            .next()
254            .children_ptr()
255            .map(|ptr| Node::new(self.col(), ptr.clone()))
256    }
257
258    /// Returns the `child-index`-th child of the node; returns None if out of bounds.
259    ///
260    /// # Examples
261    ///
262    /// ```
263    /// use orx_tree::*;
264    ///
265    /// // build the tree:
266    /// // r
267    /// // |-- a
268    /// //     |-- c, d, e
269    /// // |-- b
270    /// let mut tree = DynTree::<char>::new('r');
271    ///
272    /// let mut root = tree.root_mut();
273    /// let [id_a] = root.push_children(['a']);
274    /// root.push_child('b');
275    ///
276    /// let mut a = tree.node_mut(&id_a);
277    /// a.push_children(['c', 'd', 'e']);
278    ///
279    /// // use child to access lower level nodes
280    ///
281    /// let root = tree.root();
282    ///
283    /// let a = root.get_child(0).unwrap();
284    /// assert_eq!(a.data(), &'a');
285    /// assert_eq!(a.num_children(), 3);
286    ///
287    /// assert_eq!(a.get_child(1).unwrap().data(), &'d');
288    /// assert_eq!(a.get_child(3), None);
289    /// ```
290    fn get_child(&self, child_index: usize) -> Option<Node<V, M, P>> {
291        self.node()
292            .next()
293            .get_ptr(child_index)
294            .map(|ptr| Node::new(self.col(), ptr.clone()))
295    }
296
297    /// Returns the `child-index`-th child of the node.
298    ///
299    /// # Panics
300    ///
301    /// Panics if the child index is out of bounds; i.e., `child_index >= self.num_children()`.
302    ///
303    /// # Examples
304    ///
305    /// ```
306    /// use orx_tree::*;
307    ///
308    /// // build the tree:
309    /// // r
310    /// // |-- a
311    /// //     |-- c, d, e
312    /// // |-- b
313    /// let mut tree = DynTree::<char>::new('r');
314    ///
315    /// let mut root = tree.root_mut();
316    /// let [id_a] = root.push_children(['a']);
317    /// root.push_child('b');
318    ///
319    /// let mut a = tree.node_mut(&id_a);
320    /// a.push_children(['c', 'd', 'e']);
321    ///
322    /// // use child to access lower level nodes
323    ///
324    /// let root = tree.root();
325    ///
326    /// let a = root.child(0);
327    /// assert_eq!(a.data(), &'a');
328    /// assert_eq!(a.num_children(), 3);
329    ///
330    /// assert_eq!(a.child(1).data(), &'d');
331    /// // let child = a.child(3); // out-of-bounds, panics!
332    /// ```
333    fn child(&self, child_index: usize) -> Node<V, M, P> {
334        self.get_child(child_index)
335            .expect("Given child_index is out of bounds; i.e., child_index >= self.num_children()")
336    }
337
338    /// Returns the parent of this node; returns None if this is the root node.
339    ///
340    /// # Examples
341    ///
342    /// ```
343    /// use orx_tree::*;
344    ///
345    /// let mut tree = BinaryTree::<char>::new('r');
346    ///
347    /// let mut root = tree.root_mut();
348    /// assert_eq!(root.parent(), None);
349    ///
350    /// root.push_children(['a', 'b']);
351    /// for node in root.children() {
352    ///     assert_eq!(node.parent().unwrap(), root);
353    /// }
354    /// ```
355    fn parent(&self) -> Option<Node<V, M, P>> {
356        self.node()
357            .prev()
358            .get()
359            .map(|ptr| Node::new(self.col(), ptr.clone()))
360    }
361
362    /// Returns the position of this node in the children collection of its parent;
363    /// returns 0 if this is the root node (root has no other siblings).
364    ///
365    /// **O(S)** where S is the number of siblings; i.e.,
366    /// requires linear search over the children of the parent of this node.
367    /// Therefore, S depends on the tree size. It bounded by 2 in a [`BinaryTree`],
368    /// by 4 in a [`DaryTree`] with D=4. In a [`DynTree`] the children list can grow
369    /// arbitrarily, therefore, it is not bounded.
370    ///
371    /// [`BinaryTree`]: crate::BinaryTree
372    /// [`DaryTree`]: crate::DaryTree
373    /// [`DynTree`]: crate::DynTree
374    ///
375    /// # Examples
376    ///
377    /// ```
378    /// use orx_tree::*;
379    ///
380    /// //      r
381    /// //     ╱ ╲
382    /// //    ╱   ╲
383    /// //   a     b
384    /// //  ╱|╲   ╱ ╲
385    /// // c d e f   g
386    /// //          ╱|╲
387    /// //         h i j
388    ///
389    /// let mut tree = DynTree::<char>::new('r');
390    ///
391    /// let mut root = tree.root_mut();
392    /// let [id_a, id_b] = root.push_children(['a', 'b']);
393    ///
394    /// let mut a = tree.node_mut(&id_a);
395    /// a.push_children(['c', 'd', 'e']);
396    ///
397    /// let mut b = tree.node_mut(&id_b);
398    /// let [_, id_g] = b.push_children(['f', 'g']);
399    ///
400    /// let mut g = tree.node_mut(&id_g);
401    /// let [id_h, id_i, id_j] = g.push_children(['h', 'i', 'j']);
402    ///
403    /// // check sibling positions
404    ///
405    /// let root = tree.root();
406    /// assert_eq!(root.sibling_idx(), 0);
407    ///
408    /// for (i, node) in root.children().enumerate() {
409    ///     assert_eq!(node.sibling_idx(), i);
410    /// }
411    ///
412    /// assert_eq!(tree.node(&id_h).sibling_idx(), 0);
413    /// assert_eq!(tree.node(&id_i).sibling_idx(), 1);
414    /// assert_eq!(tree.node(&id_j).sibling_idx(), 2);
415    /// ```
416    fn sibling_idx(&self) -> usize {
417        let parent = self.node().prev().get().map(|ptr| unsafe { ptr.node() });
418        parent
419            .map(|parent| {
420                let ptr = self.node_ptr();
421                let mut children = parent.next().children_ptr();
422                children.position(|x| x == ptr).expect("this node exists")
423            })
424            .unwrap_or(0)
425    }
426
427    /// Returns the depth of this node with respect to the root of the tree which has a
428    /// depth of 0.
429    ///
430    /// **O(D)** requires linear time in maximum depth of the tree.
431    ///
432    /// # Examples
433    ///
434    /// ```
435    /// use orx_tree::*;
436    ///
437    /// //      1
438    /// //     ╱ ╲
439    /// //    ╱   ╲
440    /// //   2     3
441    /// //  ╱ ╲   ╱ ╲
442    /// // 4   5 6   7
443    /// // |
444    /// // 8
445    ///
446    /// let mut tree = DynTree::new(1);
447    ///
448    /// let mut root = tree.root_mut();
449    /// let [id2, id3] = root.push_children([2, 3]);
450    ///
451    /// let mut n2 = tree.node_mut(&id2);
452    /// let [id4, id5] = n2.push_children([4, 5]);
453    ///
454    /// let [id8] = tree.node_mut(&id4).push_children([8]);
455    ///
456    /// let mut n3 = tree.node_mut(&id3);
457    /// let [id6, id7] = n3.push_children([6, 7]);
458    ///
459    /// // access the leaves in different orders that is determined by traversal
460    ///
461    /// assert_eq!(tree.root().depth(), 0);
462    ///
463    /// assert_eq!(tree.node(&id2).depth(), 1);
464    /// assert_eq!(tree.node(&id3).depth(), 1);
465    ///
466    /// assert_eq!(tree.node(&id4).depth(), 2);
467    /// assert_eq!(tree.node(&id5).depth(), 2);
468    /// assert_eq!(tree.node(&id6).depth(), 2);
469    /// assert_eq!(tree.node(&id7).depth(), 2);
470    ///
471    /// assert_eq!(tree.node(&id8).depth(), 3);
472    /// ```
473    fn depth(&self) -> usize {
474        let mut depth = 0;
475
476        let mut current = unsafe { &*self.node_ptr().ptr() };
477        while let Some(parent_ptr) = current.prev().get() {
478            depth += 1;
479            current = unsafe { &*parent_ptr.ptr() };
480        }
481
482        depth
483    }
484
485    /// Returns an iterator starting from this node moving upwards until the root:
486    ///
487    /// * yields all ancestors of this node including this node,
488    /// * the first element is always this node, and
489    /// * the last element is always the root node of the tree.
490    ///
491    /// # Examples
492    ///
493    /// ```
494    /// use orx_tree::*;
495    ///
496    /// //      1
497    /// //     ╱ ╲
498    /// //    ╱   ╲
499    /// //   2     3
500    /// //  ╱ ╲   ╱ ╲
501    /// // 4   5 6   7
502    /// // |     |  ╱ ╲
503    /// // 8     9 10  11
504    ///
505    /// let mut tree = DynTree::new(1);
506    ///
507    /// let mut root = tree.root_mut();
508    /// let [id2, id3] = root.push_children([2, 3]);
509    ///
510    /// let mut n2 = tree.node_mut(&id2);
511    /// let [id4, _] = n2.push_children([4, 5]);
512    ///
513    /// tree.node_mut(&id4).push_child(8);
514    ///
515    /// let mut n3 = tree.node_mut(&id3);
516    /// let [id6, id7] = n3.push_children([6, 7]);
517    ///
518    /// tree.node_mut(&id6).push_child(9);
519    /// let [id10, _] = tree.node_mut(&id7).push_children([10, 11]);
520    ///
521    /// // ancestors iterator over nodes
522    /// // upwards from the node to the root
523    ///
524    /// let root = tree.root();
525    /// let mut iter = root.ancestors();
526    /// assert_eq!(iter.next().as_ref(), Some(&root));
527    /// assert_eq!(iter.next(), None);
528    ///
529    /// let n10 = tree.node(&id10);
530    /// let ancestors_data: Vec<_> = n10.ancestors().map(|x| *x.data()).collect();
531    /// assert_eq!(ancestors_data, [10, 7, 3, 1]);
532    ///
533    /// let n4 = tree.node(&id4);
534    /// let ancestors_data: Vec<_> = n4.ancestors().map(|x| *x.data()).collect();
535    /// assert_eq!(ancestors_data, [4, 2, 1]);
536    /// ```
537    fn ancestors(&'a self) -> impl Iterator<Item = Node<'a, V, M, P>> {
538        let root_ptr = self.col().ends().get().expect("Tree is non-empty").clone();
539        AncestorsIterPtr::new(root_ptr, self.node_ptr().clone())
540            .map(|ptr| Node::new(self.col(), ptr))
541    }
542
543    /// Returns true if this node is an ancestor of the node with the given `idx`;
544    /// false otherwise.
545    ///
546    /// Searches in ***O(D)*** where D is the depth of the tree.
547    ///
548    /// Note that the node is **not** an ancestor of itself.
549    ///
550    /// # Examples
551    ///
552    /// ```
553    /// use orx_tree::*;
554    ///
555    /// //      1
556    /// //     ╱ ╲
557    /// //    ╱   ╲
558    /// //   2     3
559    /// //  ╱ ╲   ╱ ╲
560    /// // 4   5 6   7
561    ///
562    /// let mut tree = DynTree::new(1);
563    ///
564    /// let mut root = tree.root_mut();
565    /// let [id2, id3] = root.push_children([2, 3]);
566    ///
567    /// let mut n2 = tree.node_mut(&id2);
568    /// let [id4, id5] = n2.push_children([4, 5]);
569    ///
570    /// let mut n3 = tree.node_mut(&id3);
571    /// let [id6, id7] = n3.push_children([6, 7]);
572    ///
573    /// // ancestor tests
574    ///
575    /// assert!(tree.root().is_ancestor_of(&id4));
576    /// assert!(tree.root().is_ancestor_of(&id7));
577    ///
578    /// assert!(tree.node(&id2).is_ancestor_of(&id5));
579    /// assert!(tree.node(&id3).is_ancestor_of(&id6));
580    ///
581    /// // the other way around
582    /// assert!(!tree.node(&id6).is_ancestor_of(&id3));
583    ///
584    /// // a node is not an ancestor of itself
585    /// assert!(!tree.node(&id6).is_ancestor_of(&id6));
586    ///
587    /// // nodes belong to independent subtrees
588    /// assert!(!tree.node(&id2).is_ancestor_of(&id6));
589    /// ```
590    fn is_ancestor_of(&self, idx: &NodeIdx<V>) -> bool {
591        let root_ptr = self.col().ends().get().expect("Tree is non-empty").clone();
592        let descendant_ptr = idx.0.node_ptr();
593        let ancestor_ptr = self.node_ptr().clone();
594        AncestorsIterPtr::new(root_ptr, descendant_ptr)
595            .skip(1) // a node is not an ancestor of itself
596            .any(|ptr| ptr == ancestor_ptr)
597    }
598
599    /// Returns the height of this node relative to the deepest leaf of the subtree rooted at this node.
600    ///
601    /// Equivalently, returns the maximum of depths of leaf nodes belonging to the subtree rooted at this node.
602    ///
603    /// If this is a leaf node, height will be 0 which is the depth of the root (itself).
604    ///
605    /// # Examples
606    ///
607    /// ```
608    /// use orx_tree::*;
609    ///
610    /// //      1
611    /// //     ╱ ╲
612    /// //    ╱   ╲
613    /// //   2     3
614    /// //  ╱ ╲   ╱ ╲
615    /// // 4   5 6   7
616    /// //       |
617    /// //       8
618    ///
619    /// let mut tree = DynTree::new(1);
620    ///
621    /// let mut root = tree.root_mut();
622    /// let [id2, id3] = root.push_children([2, 3]);
623    /// let [id4, _] = tree.node_mut(&id2).push_children([4, 5]);
624    /// let [id6, _] = tree.node_mut(&id3).push_children([6, 7]);
625    /// tree.node_mut(&id6).push_child(8);
626    ///
627    /// assert_eq!(tree.root().height(), 3); // max depth of the tree
628    /// assert_eq!(tree.node(&id2).height(), 1);
629    /// assert_eq!(tree.node(&id3).height(), 2);
630    /// assert_eq!(tree.node(&id4).height(), 0); // subtree with only the root
631    /// assert_eq!(tree.node(&id6).height(), 1);
632    /// ```
633    fn height(&self) -> usize {
634        let mut traverser = Dfs::<OverDepthPtr>::new();
635        Dfs::<OverDepthPtr>::iter_ptr_with_storage(self.node_ptr().clone(), traverser.storage_mut())
636            .map(|(depth, _)| depth)
637            .max()
638            .expect("the iterator is not empty")
639    }
640
641    // traversal
642
643    /// Creates an iterator that yields references to data of all nodes belonging to the subtree rooted at this node.
644    ///
645    /// The order of the elements is determined by the generic [`Traverser`] parameter `T`.
646    /// Available implementations are:
647    /// * [`Bfs`] for breadth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search))
648    /// * [`Bfs`] for (pre-order) depth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search))
649    /// * [`PostOrder`] for post-order ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN))
650    ///
651    /// # See also
652    ///
653    /// See also [`walk_mut`] and [`into_walk`] for iterators over mutable references and owned (removed) values,
654    /// respectively.
655    ///
656    /// Note that tree traversing methods typically allocate a temporary data structure that is dropped once the
657    /// iterator is dropped.
658    /// In use cases where we repeatedly iterate using any of the **walk** methods over different nodes or different
659    /// trees, we can avoid the allocation by creating the traverser only once and using [`walk_with`], [`walk_mut_with`]
660    /// and [`into_walk_with`] methods instead.
661    /// These methods additionally allow for iterating over nodes rather than data; and yielding node depths and sibling
662    /// indices in addition to node data.
663    ///
664    /// [`Bfs`]: crate::Bfs
665    /// [`Dfs`]: crate::Dfs
666    /// [`PostOrder`]: crate::PostOrder
667    /// [`walk_mut`]: crate::NodeMut::walk_mut
668    /// [`into_walk`]: crate::NodeMut::into_walk
669    /// [`walk_with`]: crate::NodeRef::walk_with
670    /// [`walk_mut_with`]: crate::NodeMut::walk_mut_with
671    /// [`into_walk_with`]: crate::NodeMut::into_walk_with
672    ///
673    /// # Examples
674    ///
675    /// ```
676    /// use orx_tree::*;
677    ///
678    /// //      1
679    /// //     ╱ ╲
680    /// //    ╱   ╲
681    /// //   2     3
682    /// //  ╱ ╲   ╱ ╲
683    /// // 4   5 6   7
684    /// // |     |  ╱ ╲
685    /// // 8     9 10  11
686    ///
687    /// let mut tree = DynTree::new(1);
688    ///
689    /// let mut root = tree.root_mut();
690    /// let [id2, id3] = root.push_children([2, 3]);
691    /// let [id4, _] = tree.node_mut(&id2).push_children([4, 5]);
692    /// tree.node_mut(&id4).push_child(8);
693    /// let [id6, id7] = tree.node_mut(&id3).push_children([6, 7]);
694    /// tree.node_mut(&id6).push_child(9);
695    /// tree.node_mut(&id7).push_children([10, 11]);
696    ///
697    /// // walk over any subtree rooted at a selected node
698    /// // with different traversals
699    ///
700    /// let root = tree.root();
701    /// let bfs: Vec<_> = root.walk::<Bfs>().copied().collect();
702    /// assert_eq!(bfs, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
703    ///
704    /// let n3 = tree.node(&id3);
705    /// let dfs: Vec<_> = n3.walk::<Dfs>().copied().collect();
706    /// assert_eq!(dfs, [3, 6, 9, 7, 10, 11]);
707    ///
708    /// let n2 = tree.node(&id2);
709    /// let post_order: Vec<_> = n2.walk::<PostOrder>().copied().collect();
710    /// assert_eq!(post_order, [8, 4, 5, 2]);
711    /// ```
712    fn walk<T>(&'a self) -> impl Iterator<Item = &'a V::Item>
713    where
714        T: Traverser<OverData>,
715        Self: Sized,
716    {
717        T::iter_with_owned_storage::<V, M, P>(self)
718    }
719
720    /// Creates an iterator that traverses all nodes belonging to the subtree rooted at this node.
721    ///
722    /// The order of the elements is determined by the type of the `traverser` which implements [`Traverser`].
723    /// Available implementations are:
724    /// * [`Bfs`] for breadth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search))
725    /// * [`Dfs`] for (pre-order) depth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search))
726    /// * [`PostOrder`] for post-order ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN))
727    ///
728    /// As opposed to [`walk`], this method does require internal allocation.
729    /// Furthermore, it allows to iterate over nodes rather than data; and to attach node depths or sibling
730    /// indices to the yield values.
731    /// Please see the examples below.
732    ///
733    /// [`walk`]: crate::NodeRef::walk
734    /// [`Bfs`]: crate::Bfs
735    /// [`Dfs`]: crate::Dfs
736    /// [`PostOrder`]: crate::PostOrder
737    ///
738    /// # Examples
739    ///
740    /// ## Examples - Repeated Iterations without Allocation
741    ///
742    /// ```
743    /// use orx_tree::*;
744    ///
745    /// //      1
746    /// //     ╱ ╲
747    /// //    ╱   ╲
748    /// //   2     3
749    /// //  ╱ ╲   ╱ ╲
750    /// // 4   5 6   7
751    /// // |     |  ╱ ╲
752    /// // 8     9 10  11
753    ///
754    /// let mut tree = DynTree::new(1);
755    ///
756    /// let mut root = tree.root_mut();
757    /// let [id2, id3] = root.push_children([2, 3]);
758    ///
759    /// let mut n2 = tree.node_mut(&id2);
760    /// let [id4, _] = n2.push_children([4, 5]);
761    ///
762    /// tree.node_mut(&id4).push_child(8);
763    ///
764    /// let mut n3 = tree.node_mut(&id3);
765    /// let [id6, id7] = n3.push_children([6, 7]);
766    ///
767    /// tree.node_mut(&id6).push_child(9);
768    /// tree.node_mut(&id7).push_children([10, 11]);
769    ///
770    /// // create the traverser 'dfs' only once, use it many times
771    /// // to walk over references, mutable references or removed values
772    /// // without additional allocation
773    ///
774    /// let mut dfs = Dfs::default();
775    ///
776    /// let root = tree.root();
777    /// let values: Vec<_> = root.walk_with(&mut dfs).copied().collect();
778    /// assert_eq!(values, [1, 2, 4, 8, 5, 3, 6, 9, 7, 10, 11]);
779    ///
780    /// let mut n7 = tree.node_mut(&id7);
781    /// for x in n7.walk_mut_with(&mut dfs) {
782    ///     *x += 100;
783    /// }
784    /// let values: Vec<_> = tree.get_root().unwrap().walk_with(&mut dfs).copied().collect();
785    /// assert_eq!(values, [1, 2, 4, 8, 5, 3, 6, 9, 107, 110, 111]);
786    ///
787    /// let n3 = tree.node_mut(&id3);
788    /// let removed: Vec<_> = n3.into_walk_with(&mut dfs).collect();
789    /// assert_eq!(removed, [3, 6, 9, 107, 110, 111]);
790    ///
791    /// let remaining: Vec<_> = tree.get_root().unwrap().walk_with(&mut dfs).copied().collect();
792    /// assert_eq!(remaining, [1, 2, 4, 8, 5]);
793    /// ```
794    ///
795    /// ## Examples - Yielding Different Items
796    ///
797    /// ```
798    /// use orx_tree::*;
799    ///
800    /// //      1
801    /// //     ╱ ╲
802    /// //    ╱   ╲
803    /// //   2     3
804    /// //  ╱ ╲   ╱ ╲
805    /// // 4   5 6   7
806    /// // |     |  ╱ ╲
807    /// // 8     9 10  11
808    ///
809    /// let mut tree = DynTree::new(1);
810    ///
811    /// let mut root = tree.root_mut();
812    /// let [id2, id3] = root.push_children([2, 3]);
813    ///
814    /// let mut n2 = tree.node_mut(&id2);
815    /// let [id4, _] = n2.push_children([4, 5]);
816    ///
817    /// tree.node_mut(&id4).push_child(8);
818    ///
819    /// let mut n3 = tree.node_mut(&id3);
820    /// let [id6, id7] = n3.push_children([6, 7]);
821    ///
822    /// tree.node_mut(&id6).push_child(9);
823    /// tree.node_mut(&id7).push_children([10, 11]);
824    ///
825    /// // create the traverser 'bfs' iterator
826    /// // to walk over nodes rather than data
827    ///
828    /// let mut bfs = Bfs::default().over_nodes();
829    /// // OR: Bfs::<OverNode>::new();
830    ///
831    /// let n7 = tree.node(&id7);
832    /// let mut iter = n7.walk_with(&mut bfs);
833    /// let node = iter.next().unwrap();
834    /// assert_eq!(node.num_children(), 2);
835    /// assert_eq!(node.get_child(1).map(|x| *x.data()), Some(11));
836    ///
837    /// // or to additionally yield depth and/or sibling-idx
838    ///
839    /// let mut dfs = Dfs::default().with_depth().with_sibling_idx();
840    /// // OR: Dfs::<OverDepthSiblingIdxData>::new()
841    ///
842    /// let n3 = tree.node(&id3);
843    /// let result: Vec<_> = n3
844    ///     .walk_with(&mut dfs)
845    ///     .map(|(depth, sibling_idx, data)| (depth, sibling_idx, *data))
846    ///     .collect();
847    /// assert_eq!(
848    ///     result,
849    ///     [
850    ///         (0, 0, 3),
851    ///         (1, 0, 6),
852    ///         (2, 0, 9),
853    ///         (1, 1, 7),
854    ///         (2, 0, 10),
855    ///         (2, 1, 11)
856    ///     ]
857    /// );
858    /// ```
859    fn walk_with<'t, T, O>(
860        &'a self,
861        traverser: &'t mut T,
862    ) -> impl Iterator<Item = OverItem<'a, V, O, M, P>>
863    where
864        O: Over,
865        T: Traverser<O>,
866        Self: Sized,
867        't: 'a,
868    {
869        traverser.iter(self)
870    }
871
872    /// Returns an iterator of paths from all leaves of the subtree rooted at
873    /// this node **upwards** to this node.
874    ///
875    /// The iterator yields one path per leaf node.
876    ///
877    /// The order of the leaves, and hence the corresponding paths, is determined
878    /// by the generic [`Traverser`] parameter `T`.
879    ///
880    /// # See also
881    ///
882    /// * [`paths_with`]: (i) to iterate using a cached traverser to minimize allocation
883    ///   for repeated traversals, or (ii) to iterate over nodes rather than only the data.
884    ///
885    /// [`paths_with`]: NodeRef::paths_with
886    ///
887    /// # Yields
888    ///
889    /// * `Iterator::Item` => `impl Iterator<Item = &'a V::Item>`
890    ///
891    /// # Examples
892    ///
893    /// ```
894    /// use orx_tree::*;
895    ///
896    /// //      1
897    /// //     ╱ ╲
898    /// //    ╱   ╲
899    /// //   2     3
900    /// //  ╱ ╲   ╱ ╲
901    /// // 4   5 6   7
902    /// // |     |  ╱ ╲
903    /// // 8     9 10  11
904    ///
905    /// let mut tree = DynTree::new(1);
906    ///
907    /// let mut root = tree.root_mut();
908    /// let [id2, id3] = root.push_children([2, 3]);
909    ///
910    /// let mut n2 = tree.node_mut(&id2);
911    /// let [id4, _] = n2.push_children([4, 5]);
912    ///
913    /// tree.node_mut(&id4).push_child(8);
914    ///
915    /// let mut n3 = tree.node_mut(&id3);
916    /// let [id6, id7] = n3.push_children([6, 7]);
917    ///
918    /// tree.node_mut(&id6).push_child(9);
919    /// tree.node_mut(&id7).push_children([10, 11]);
920    ///
921    /// // paths from all leaves to the root
922    ///
923    /// let root = tree.root();
924    ///
925    /// // sorted in the order of leaves by breadth-first:
926    /// // 5, 8, 9, 10, 11
927    /// let paths: Vec<_> = root
928    ///     .paths::<Bfs>()
929    ///     .map(|x| x.copied().collect::<Vec<_>>())
930    ///     .collect();
931    ///
932    /// assert_eq!(
933    ///     paths,
934    ///     [
935    ///         vec![5, 2, 1],
936    ///         vec![8, 4, 2, 1],
937    ///         vec![9, 6, 3, 1],
938    ///         vec![10, 7, 3, 1],
939    ///         vec![11, 7, 3, 1]
940    ///     ]
941    /// );
942    ///
943    /// // paths from all leaves of subtree rooted at n3
944    ///
945    /// let n3 = tree.node(&id3);
946    ///
947    /// let paths: Vec<_> = n3
948    ///     .paths::<Dfs>()
949    ///     .map(|x| x.copied().collect::<Vec<_>>())
950    ///     .collect();
951    ///
952    /// assert_eq!(paths, [vec![9, 6, 3], vec![10, 7, 3], vec![11, 7, 3]]);
953    /// ```
954    fn paths<T>(&'a self) -> impl Iterator<Item = impl Iterator<Item = &'a V::Item>>
955    where
956        T: Traverser<OverData>,
957    {
958        let node_ptr = self.node_ptr();
959        T::iter_ptr_with_owned_storage(node_ptr.clone())
960            .filter(|x: &NodePtr<V>| unsafe { &*x.ptr() }.next().is_empty())
961            .map(|x: NodePtr<V>| {
962                let iter = AncestorsIterPtr::new(node_ptr.clone(), x);
963                iter.map(|ptr| (unsafe { &*ptr.ptr() }).data().expect("active tree node"))
964            })
965    }
966
967    /// Returns an iterator of paths from all leaves of the subtree rooted at
968    /// this node **upwards** to this node.
969    ///
970    /// The iterator yields one path per leaf node.
971    ///
972    /// The order of the leaves, and hence the corresponding paths, is determined
973    /// by explicit type of the [`Traverser`] argument `traverser`.
974    ///
975    /// # Yields
976    ///
977    /// * `Iterator::Item` => `impl Iterator<Item = &'a V::Item>`
978    ///   when `T: Traverser<OverData>`
979    /// * `Iterator::Item` => `impl Iterator<Item = Node<_>>`
980    ///   when `T: Traverser<OverNode>`
981    ///
982    /// # Examples
983    ///
984    /// ```
985    /// use orx_tree::*;
986    ///
987    /// //      1
988    /// //     ╱ ╲
989    /// //    ╱   ╲
990    /// //   2     3
991    /// //  ╱ ╲   ╱ ╲
992    /// // 4   5 6   7
993    /// // |     |  ╱ ╲
994    /// // 8     9 10  11
995    ///
996    /// let mut tree = DynTree::new(1);
997    ///
998    /// let mut root = tree.root_mut();
999    /// let [id2, id3] = root.push_children([2, 3]);
1000    ///
1001    /// let mut n2 = tree.node_mut(&id2);
1002    /// let [id4, _] = n2.push_children([4, 5]);
1003    ///
1004    /// tree.node_mut(&id4).push_child(8);
1005    ///
1006    /// let mut n3 = tree.node_mut(&id3);
1007    /// let [id6, id7] = n3.push_children([6, 7]);
1008    ///
1009    /// tree.node_mut(&id6).push_child(9);
1010    /// tree.node_mut(&id7).push_children([10, 11]);
1011    ///
1012    /// // create a depth first traverser and reuse it
1013    ///
1014    /// let mut dfs = Traversal.dfs(); // OverData by default
1015    ///
1016    /// // paths from leaves as data of the nodes
1017    ///
1018    /// let root = tree.root();
1019    /// let paths: Vec<_> = root
1020    ///     .paths_with(&mut dfs)
1021    ///     .map(|path_data| path_data.copied().collect::<Vec<_>>())
1022    ///     .collect();
1023    ///
1024    /// assert_eq!(
1025    ///     paths,
1026    ///     [
1027    ///         vec![8, 4, 2, 1],
1028    ///         vec![5, 2, 1],
1029    ///         vec![9, 6, 3, 1],
1030    ///         vec![10, 7, 3, 1],
1031    ///         vec![11, 7, 3, 1]
1032    ///     ]
1033    /// );
1034    ///
1035    /// // paths of subtree rooted at n3; as nodes rather than data.
1036    ///
1037    /// let mut dfs = dfs.over_nodes(); // transform from OverData to OverNode
1038    ///
1039    /// let n3 = tree.node(&id3);
1040    ///
1041    /// let paths: Vec<_> = n3
1042    ///     .paths_with(&mut dfs)
1043    ///     .map(|path_nodes| {
1044    ///         path_nodes
1045    ///             .map(|node| (*node.data(), node.depth()))
1046    ///             .collect::<Vec<_>>()
1047    ///     })
1048    ///     .collect();
1049    ///
1050    /// assert_eq!(
1051    ///     paths,
1052    ///     [
1053    ///         [(9, 3), (6, 2), (3, 1)],
1054    ///         [(10, 3), (7, 2), (3, 1)],
1055    ///         [(11, 3), (7, 2), (3, 1)]
1056    ///     ]
1057    /// );
1058    /// ```
1059    fn paths_with<T, O>(
1060        &'a self,
1061        traverser: &'a mut T,
1062    ) -> impl Iterator<Item = impl Iterator<Item = <O as Over>::NodeItem<'a, V, M, P>>>
1063    where
1064        O: Over<Enumeration = Val>,
1065        T: Traverser<O>,
1066    {
1067        let node_ptr = self.node_ptr();
1068        T::iter_ptr_with_storage(node_ptr.clone(), TraverserCore::storage_mut(traverser))
1069            .filter(|x| {
1070                let ptr: &NodePtr<V> = O::Enumeration::node_data(x);
1071                unsafe { &*ptr.ptr() }.next().is_empty()
1072            })
1073            .map(|x| {
1074                let ptr: &NodePtr<V> = O::Enumeration::node_data(&x);
1075                let iter = AncestorsIterPtr::new(node_ptr.clone(), ptr.clone());
1076                iter.map(|ptr: NodePtr<V>| {
1077                    O::Enumeration::from_element_ptr::<'a, V, M, P, O::NodeItem<'a, V, M, P>>(
1078                        self.col(),
1079                        ptr,
1080                    )
1081                })
1082            })
1083    }
1084
1085    /// Clone the subtree rooted at this node as a separate tree.
1086    ///
1087    /// # Examples
1088    ///
1089    /// ```
1090    /// use orx_tree::*;
1091    ///
1092    /// //      0
1093    /// //     ╱ ╲
1094    /// //    ╱   ╲
1095    /// //   1     2
1096    /// //  ╱ ╲   ╱ ╲
1097    /// // 3   4 5   6
1098    /// // |     |  ╱ ╲
1099    /// // 7     8 9  10
1100    ///
1101    /// let mut tree = DynTree::new(0);
1102    ///
1103    /// let mut root = tree.root_mut();
1104    /// let [id1, id2] = root.push_children([1, 2]);
1105    ///
1106    /// let mut n1 = tree.node_mut(&id1);
1107    /// let [id3, _] = n1.push_children([3, 4]);
1108    ///
1109    /// tree.node_mut(&id3).push_child(7);
1110    ///
1111    /// let mut n2 = tree.node_mut(&id2);
1112    /// let [id5, id6] = n2.push_children([5, 6]);
1113    ///
1114    /// tree.node_mut(&id5).push_child(8);
1115    /// tree.node_mut(&id6).push_children([9, 10]);
1116    ///
1117    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
1118    /// assert_eq!(bfs, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1119    ///
1120    /// // clone the subtree rooted at node 2 into another tree
1121    /// // which might be a different tree type
1122    ///
1123    /// let clone: BinaryTree<i32> = tree.node(&id2).clone_as_tree();
1124    ///
1125    /// let bfs: Vec<_> = clone.root().walk::<Bfs>().copied().collect();
1126    /// assert_eq!(bfs, [2, 5, 6, 8, 9, 10]);
1127    /// ```
1128    fn clone_as_tree<V2>(&'a self) -> Tree<V2, M, P>
1129    where
1130        V2: TreeVariant<Item = V::Item> + 'a,
1131        P::PinnedVec<V2>: Default,
1132        V::Item: Clone,
1133    {
1134        let mut tree = Tree::new_with_root(self.data().clone());
1135
1136        for child in self.children() {
1137            tree.root_mut().push_child_tree(child.as_cloned_subtree());
1138        }
1139
1140        tree
1141    }
1142
1143    // traversal shorthands
1144
1145    /// Returns an iterator of references to data of leaves of the subtree rooted at this node.
1146    ///
1147    /// The order of the elements is determined by the type of the `traverser` which implements [`Traverser`].
1148    /// Available implementations are:
1149    /// * [`Bfs`] for breadth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search))
1150    /// * [`Dfs`] for (pre-order) depth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search))
1151    /// * [`PostOrder`] for post-order ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN))
1152    ///
1153    /// Note that `leaves` is a shorthand of a chain of iterator methods over the more general [`walk_with`] method.
1154    /// This is demonstrated in the example below.
1155    ///
1156    /// [`walk_with`]: crate::NodeRef::walk_with
1157    /// [`Bfs`]: crate::Bfs
1158    /// [`Dfs`]: crate::Dfs
1159    /// [`PostOrder`]: crate::PostOrder
1160    ///
1161    /// # Examples
1162    ///
1163    /// ```
1164    /// use orx_tree::*;
1165    ///
1166    /// //      1
1167    /// //     ╱ ╲
1168    /// //    ╱   ╲
1169    /// //   2     3
1170    /// //  ╱ ╲   ╱ ╲
1171    /// // 4   5 6   7
1172    /// // |     |  ╱ ╲
1173    /// // 8     9 10  11
1174    ///
1175    /// let mut tree = DynTree::new(1);
1176    ///
1177    /// let mut root = tree.root_mut();
1178    /// let [id2, id3] = root.push_children([2, 3]);
1179    ///
1180    /// let mut n2 = tree.node_mut(&id2);
1181    /// let [id4, _] = n2.push_children([4, 5]);
1182    ///
1183    /// tree.node_mut(&id4).push_child(8);
1184    ///
1185    /// let mut n3 = tree.node_mut(&id3);
1186    /// let [id6, id7] = n3.push_children([6, 7]);
1187    ///
1188    /// tree.node_mut(&id6).push_child(9);
1189    /// tree.node_mut(&id7).push_children([10, 11]);
1190    ///
1191    /// // access the leaves in different orders that is determined by traversal
1192    ///
1193    /// let root = tree.root();
1194    ///
1195    /// let bfs_leaves: Vec<_> = root.leaves::<Bfs>().copied().collect();
1196    /// assert_eq!(bfs_leaves, [5, 8, 9, 10, 11]);
1197    ///
1198    /// let dfs_leaves: Vec<_> = root.leaves::<Dfs>().copied().collect();
1199    /// assert_eq!(dfs_leaves, [8, 5, 9, 10, 11]);
1200    ///
1201    /// // get the leaves from any node
1202    ///
1203    /// let n3 = tree.node(&id3);
1204    /// let leaves: Vec<_> = n3.leaves::<PostOrder>().copied().collect();
1205    /// assert_eq!(leaves, [9, 10, 11]);
1206    ///
1207    /// // ALTERNATIVELY: get the leaves with walk_with
1208    ///
1209    /// let mut tr = Traversal.bfs().over_nodes(); // we need Node to filter leaves
1210    ///
1211    /// let bfs_leaves: Vec<_> = root
1212    ///     .walk_with(&mut tr)
1213    ///     .filter(|x| x.is_leaf())
1214    ///     .map(|x| *x.data())
1215    ///     .collect();
1216    /// assert_eq!(bfs_leaves, [5, 8, 9, 10, 11]);
1217    /// ```
1218    fn leaves<T>(&'a self) -> impl Iterator<Item = &'a V::Item>
1219    where
1220        T: Traverser<OverData>,
1221    {
1222        T::iter_ptr_with_owned_storage(self.node_ptr().clone())
1223            .filter(|x: &NodePtr<V>| unsafe { &*x.ptr() }.next().is_empty())
1224            .map(|x: NodePtr<V>| {
1225                <OverData as Over>::Enumeration::from_element_ptr::<'a, V, M, P, &'a V::Item>(
1226                    self.col(),
1227                    x,
1228                )
1229            })
1230    }
1231
1232    /// Returns an iterator of leaves of the subtree rooted at this node.
1233    ///
1234    /// The order of the elements is determined by the type of the `traverser` which implements [`Traverser`].
1235    /// Available implementations are:
1236    /// * [`Bfs`] for breadth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search))
1237    /// * [`Dfs`] for (pre-order) depth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search))
1238    /// * [`PostOrder`] for post-order ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN))
1239    ///
1240    /// Note that `leaves` is a shorthand of a chain of iterator methods over the more general [`walk_with`] method.
1241    /// This is demonstrated in the example below.
1242    ///
1243    /// [`walk_with`]: crate::NodeRef::walk_with
1244    /// [`Bfs`]: crate::Bfs
1245    /// [`Dfs`]: crate::Dfs
1246    /// [`PostOrder`]: crate::PostOrder
1247    ///
1248    /// # Examples
1249    ///
1250    /// ```
1251    /// use orx_tree::*;
1252    ///
1253    /// //      1
1254    /// //     ╱ ╲
1255    /// //    ╱   ╲
1256    /// //   2     3
1257    /// //  ╱ ╲   ╱ ╲
1258    /// // 4   5 6   7
1259    /// // |     |  ╱ ╲
1260    /// // 8     9 10  11
1261    ///
1262    /// let mut tree = DynTree::new(1);
1263    ///
1264    /// let mut root = tree.root_mut();
1265    /// let [id2, id3] = root.push_children([2, 3]);
1266    ///
1267    /// let mut n2 = tree.node_mut(&id2);
1268    /// let [id4, _] = n2.push_children([4, 5]);
1269    ///
1270    /// tree.node_mut(&id4).push_child(8);
1271    ///
1272    /// let mut n3 = tree.node_mut(&id3);
1273    /// let [id6, id7] = n3.push_children([6, 7]);
1274    ///
1275    /// tree.node_mut(&id6).push_child(9);
1276    /// tree.node_mut(&id7).push_children([10, 11]);
1277    ///
1278    /// // access leaves with re-usable traverser
1279    ///
1280    /// let mut bfs = Traversal.bfs();
1281    /// assert_eq!(
1282    ///     tree.root().leaves_with(&mut bfs).collect::<Vec<_>>(),
1283    ///     [&5, &8, &9, &10, &11]
1284    /// );
1285    /// assert_eq!(
1286    ///     tree.node(&id3).leaves_with(&mut bfs).collect::<Vec<_>>(),
1287    ///     [&9, &10, &11]
1288    /// );
1289    ///
1290    /// // access leaf nodes instead of data
1291    ///
1292    /// let mut dfs = Traversal.dfs().over_nodes();
1293    ///
1294    /// let root = tree.root();
1295    /// let mut leaves = root.leaves_with(&mut dfs);
1296    ///
1297    /// let leaf: Node<_> = leaves.next().unwrap();
1298    /// assert!(leaf.is_leaf());
1299    /// assert_eq!(leaf.data(), &8);
1300    /// assert_eq!(leaf.parent(), Some(tree.node(&id4)));
1301    ///
1302    /// // add depth and/or sibling-idx to the iteration items
1303    ///
1304    /// let mut dfs = Traversal.dfs().over_nodes().with_depth().with_sibling_idx();
1305    /// let mut leaves = root.leaves_with(&mut dfs);
1306    /// let (depth, sibling_idx, leaf) = leaves.next().unwrap();
1307    /// assert_eq!(depth, 3);
1308    /// assert_eq!(sibling_idx, 0);
1309    /// assert_eq!(leaf.data(), &8);
1310    /// ```
1311    fn leaves_with<T, O>(
1312        &'a self,
1313        traverser: &'a mut T,
1314    ) -> impl Iterator<Item = OverItem<'a, V, O, M, P>>
1315    where
1316        O: Over,
1317        T: Traverser<O>,
1318    {
1319        T::iter_ptr_with_storage(self.node_ptr().clone(), traverser.storage_mut())
1320            .filter(|x| {
1321                let ptr: &NodePtr<V> = O::Enumeration::node_data(x);
1322                unsafe { &*ptr.ptr() }.next().is_empty()
1323            })
1324            .map(|x| {
1325                O::Enumeration::from_element_ptr::<'a, V, M, P, O::NodeItem<'a, V, M, P>>(
1326                    self.col(),
1327                    x,
1328                )
1329            })
1330    }
1331
1332    /// Returns an iterator of node indices.
1333    ///
1334    /// The order of the indices is determined by the generic [`Traverser`] parameter `T`.
1335    ///
1336    /// # See also
1337    ///
1338    /// Note that tree traversing methods typically allocate a temporary data structure that is dropped once the
1339    /// iterator is dropped.
1340    /// In use cases where we repeatedly iterate using any of the **walk** methods over different nodes or different
1341    /// trees, we can avoid the allocation by creating the traverser only once and using [`indices_with`] methods instead.
1342    /// This method additionally allow for yielding node depths and sibling indices in addition to node indices.
1343    ///
1344    /// [`indices_with`]: crate::NodeRef::indices_with
1345    ///
1346    /// # Examples
1347    ///
1348    /// ```
1349    /// use orx_tree::*;
1350    ///
1351    /// //      0
1352    /// //     ╱ ╲
1353    /// //    ╱   ╲
1354    /// //   1     2
1355    /// //  ╱ ╲   ╱ ╲
1356    /// // 3   4 5   6
1357    /// // |     |  ╱ ╲
1358    /// // 7     8 9  10
1359    ///
1360    /// let mut a = DynTree::new(0);
1361    /// let [a1, a2] = a.root_mut().push_children([1, 2]);
1362    /// let [a3, _] = a.node_mut(&a1).push_children([3, 4]);
1363    /// a.node_mut(&a3).push_child(7);
1364    /// let [a5, a6] = a.node_mut(&a2).push_children([5, 6]);
1365    /// a.node_mut(&a5).push_child(8);
1366    /// a.node_mut(&a6).push_children([9, 10]);
1367    ///
1368    /// // collect indices in breadth-first order
1369    ///
1370    /// let a0 = a.root();
1371    /// let bfs_indices: Vec<_> = a0.indices::<Bfs>().collect();
1372    ///
1373    /// assert_eq!(a.node(&bfs_indices[0]).data(), &0);
1374    /// assert_eq!(a.node(&bfs_indices[1]).data(), &1);
1375    /// assert_eq!(a.node(&bfs_indices[2]).data(), &2);
1376    /// assert_eq!(a.node(&bfs_indices[3]).data(), &3);
1377    ///
1378    /// // collect indices in depth-first order
1379    /// // we may also re-use a traverser
1380    ///
1381    /// let mut t = Traversal.dfs();
1382    ///
1383    /// let a0 = a.root();
1384    /// let dfs_indices: Vec<_> = a0.indices_with(&mut t).collect();
1385    ///
1386    /// assert_eq!(a.node(&dfs_indices[0]).data(), &0);
1387    /// assert_eq!(a.node(&dfs_indices[1]).data(), &1);
1388    /// assert_eq!(a.node(&dfs_indices[2]).data(), &3);
1389    /// assert_eq!(a.node(&dfs_indices[3]).data(), &7);
1390    /// ```
1391    fn indices<T>(&self) -> impl Iterator<Item = NodeIdx<V>>
1392    where
1393        T: Traverser<OverData>,
1394        V: 'static,
1395    {
1396        let node_ptr = self.node_ptr();
1397        let state = self.col().memory_state();
1398        T::iter_ptr_with_owned_storage(node_ptr.clone())
1399            .map(move |x: NodePtr<V>| NodeIdx(orx_selfref_col::NodeIdx::new(state, &x)))
1400    }
1401
1402    /// Returns an iterator of node indices.
1403    ///
1404    /// The order of the indices is determined by the generic [`Traverser`] parameter `T` of the given `traverser`.
1405    ///
1406    /// Depending on the traverser type, the iterator might yield:
1407    ///
1408    /// * NodeIdx
1409    /// * (depth, NodeIdx)
1410    /// * (sibling_idx, NodeIdx)
1411    /// * (depth, sibling_idx, NodeIdx)
1412    ///
1413    /// # See also
1414    ///
1415    /// Note that tree traversing methods typically allocate a temporary data structure that is dropped once the
1416    /// iterator is dropped.
1417    /// In use cases where we repeatedly iterate using any of the **walk** methods over different nodes or different
1418    /// trees, we can avoid the allocation by creating the traverser only once and using [`indices_with`] methods instead.
1419    /// This method additionally allow for yielding node depths and sibling indices in addition to node indices.
1420    ///
1421    /// [`indices_with`]: crate::NodeRef::indices_with
1422    fn indices_with<T, O>(
1423        &self,
1424        traverser: &mut T,
1425    ) -> impl Iterator<Item = <O::Enumeration as Enumeration>::Item<NodeIdx<V>>>
1426    where
1427        O: Over,
1428        T: Traverser<O>,
1429        V: 'static,
1430        Self: Sized,
1431    {
1432        let node_ptr = self.node_ptr();
1433        let state = self.col().memory_state();
1434        T::iter_ptr_with_storage(node_ptr.clone(), traverser.storage_mut()).map(move |x| {
1435            <O::Enumeration as Enumeration>::map_node_data(x, |ptr: NodePtr<V>| {
1436                NodeIdx(orx_selfref_col::NodeIdx::new(state, &ptr))
1437            })
1438        })
1439    }
1440
1441    // subtree
1442
1443    /// Creates a subtree view including this node as the root and all of its descendants with their orientation relative
1444    /// to this node.
1445    ///
1446    /// Consuming the created subtree in methods such as [`push_child_tree`] or [`push_sibling_tree`] will create
1447    /// the same subtree structure in the target tree with cloned values.
1448    /// This subtree and the tree it belongs to remain unchanged.
1449    /// Please see **Append Subtree cloned-copied from another Tree** section of the examples of these methods.
1450    ///
1451    /// Otherwise, it has no impact on the tree.
1452    ///
1453    /// [`push_child_tree`]: crate::NodeMut::push_child_tree
1454    /// [`push_sibling_tree`]: crate::NodeMut::push_sibling_tree
1455    #[allow(clippy::wrong_self_convention)]
1456    fn as_cloned_subtree(self) -> ClonedSubTree<'a, V, M, P, Self>
1457    where
1458        V::Item: Clone,
1459        Self: Sized,
1460    {
1461        ClonedSubTree::new(self)
1462    }
1463
1464    /// Creates a subtree view including this node as the root and all of its descendants with their orientation relative
1465    /// to this node.
1466    ///
1467    /// Consuming the created subtree in methods such as [`push_child_tree`] or [`push_sibling_tree`] will create
1468    /// the same subtree structure in the target tree with copied values.
1469    /// This subtree and the tree it belongs to remain unchanged.
1470    /// Please see **Append Subtree cloned-copied from another Tree** section of the examples of these methods.
1471    ///
1472    /// Otherwise, it has no impact on the tree.
1473    ///
1474    /// [`push_child_tree`]: crate::NodeMut::push_child_tree
1475    /// [`push_sibling_tree`]: crate::NodeMut::push_sibling_tree
1476    #[allow(clippy::wrong_self_convention)]
1477    fn as_copied_subtree(self) -> CopiedSubTree<'a, V, M, P, Self>
1478    where
1479        V::Item: Copy,
1480        Self: Sized,
1481    {
1482        CopiedSubTree::new(self)
1483    }
1484}