orx_tree/
node_mut.rs

1use crate::{
2    Node, NodeIdx, NodeRef, PostOrder, SubTree, Traverser, Tree, TreeVariant,
3    aliases::{Col, N},
4    iter::{ChildrenMutIter, CustomWalkIterPtr},
5    memory::{Auto, MemoryPolicy},
6    node_ref::NodeRefCore,
7    pinned_storage::{PinnedStorage, SplitRecursive},
8    subtrees::{MovedSubTree, SubTreeCore},
9    subtrees_within::SubTreeWithin,
10    traversal::{
11        Over, OverData, OverMut,
12        enumeration::Enumeration,
13        enumerations::Val,
14        over::OverPtr,
15        over_mut::{OverItemInto, OverItemMut},
16        post_order::iter_ptr::PostOrderIterPtr,
17        traverser_core::TraverserCore,
18    },
19    tree_node_idx::INVALID_IDX_ERROR,
20    tree_variant::RefsChildren,
21};
22use alloc::vec::Vec;
23use core::{fmt::Debug, marker::PhantomData};
24use orx_selfref_col::{NodePtr, Refs};
25
26/// A marker trait determining the mutation flexibility of a mutable node.
27pub trait NodeMutOrientation: 'static {}
28
29/// Allows mutation of only the node itself and its descendants.
30///
31/// This is a safety requirement for methods such as [`children_mut`]:
32///
33/// * `children_mut` returns mutable children; however, with `NodeMutDown` orientation.
34/// * This prevents us from having more than once mutable reference to the same node.
35///
36/// [`children_mut`]: crate::NodeMut::children_mut
37pub struct NodeMutDown {}
38impl NodeMutOrientation for NodeMutDown {}
39
40/// Allows mutation of the node itself, its descendants and ancestors;
41/// i.e., does limit.
42pub struct NodeMutUpAndDown {}
43impl NodeMutOrientation for NodeMutUpAndDown {}
44
45/// Side of a sibling node relative to a particular node within the children collection.
46#[derive(Clone, Copy, Debug)]
47pub enum Side {
48    /// To the left of this node.
49    Left,
50    /// To the right of this node.
51    Right,
52}
53
54/// A node of the tree, which in turn is a tree.
55pub struct NodeMut<'a, V, M = Auto, P = SplitRecursive, O = NodeMutUpAndDown>
56where
57    V: TreeVariant,
58    M: MemoryPolicy,
59    P: PinnedStorage,
60    O: NodeMutOrientation,
61{
62    col: &'a mut Col<V, M, P>,
63    node_ptr: NodePtr<V>,
64    phantom: PhantomData<O>,
65}
66
67impl<'a, V, M, P, MO> NodeRefCore<'a, V, M, P> for NodeMut<'a, V, M, P, MO>
68where
69    V: TreeVariant,
70    M: MemoryPolicy,
71    P: PinnedStorage,
72    MO: NodeMutOrientation,
73{
74    #[inline(always)]
75    fn col(&self) -> &'a Col<V, M, P> {
76        let x = self.col as *const Col<V, M, P>;
77        unsafe { &*x }
78    }
79
80    #[inline(always)]
81    fn node_ptr(&self) -> NodePtr<V> {
82        self.node_ptr
83    }
84}
85
86impl<'a, V, M, P, MO> NodeMut<'a, V, M, P, MO>
87where
88    V: TreeVariant,
89    M: MemoryPolicy,
90    P: PinnedStorage,
91    MO: NodeMutOrientation,
92{
93    /// Returns a mutable reference to data of this node.
94    ///
95    /// # Examples
96    ///
97    /// ```
98    /// use orx_tree::*;
99    ///
100    /// let mut tree = DynTree::new(0);
101    ///
102    /// let mut root = tree.root_mut();
103    ///
104    /// *root.data_mut() = 10;
105    /// assert_eq!(root.data(), &10);
106    ///
107    /// let [idx_a] = root.push_children([1]);
108    /// let mut node = tree.node_mut(idx_a);
109    ///
110    /// *node.data_mut() += 10;
111    /// assert_eq!(node.data(), &11);
112    /// ```
113    #[inline(always)]
114    #[allow(clippy::missing_panics_doc)]
115    pub fn data_mut(&mut self) -> &mut V::Item {
116        self.node_mut()
117            .data_mut()
118            .expect("node holding a tree reference must be active")
119    }
120
121    /// Swaps the data of this and the other node with the given `other_idx`.
122    ///
123    /// # Panics
124    ///
125    /// Panics if the `other_idx` is invalid.
126    ///
127    /// # See also
128    ///
129    /// See [`try_swap_nodes`] to swap two independent subtrees rooted at given node indices.
130    ///
131    /// [`try_swap_nodes`]: crate::Tree::try_swap_nodes
132    ///
133    /// # Examples
134    ///
135    /// ```
136    /// use orx_tree::*;
137    ///
138    /// //      1
139    /// //     ╱ ╲
140    /// //    ╱   ╲
141    /// //   2     3
142    /// //  ╱ ╲   ╱
143    /// // 4   5 6
144    ///
145    /// let mut tree = DynTree::new(1);
146    ///
147    /// let mut root = tree.root_mut();
148    /// let id1 = root.idx();
149    /// let [id2, id3] = root.push_children([2, 3]);
150    ///
151    /// let mut n2 = tree.node_mut(id2);
152    /// let [id4, id5] = n2.push_children([4, 5]);
153    ///
154    /// let mut n3 = tree.node_mut(id3);
155    /// n3.push_child(6);
156    ///
157    /// // swap data of nodes to obtain
158    ///
159    /// //      2
160    /// //     ╱ ╲
161    /// //    ╱   ╲
162    /// //   1     5
163    /// //  ╱ ╲   ╱
164    /// // 4   3 6
165    ///
166    /// tree.node_mut(id4).swap_data_with(id4); // does nothing
167    /// tree.node_mut(id2).swap_data_with(id1);
168    /// tree.node_mut(id5).swap_data_with(id3);
169    ///
170    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
171    /// assert_eq!(bfs, [2, 1, 5, 4, 3, 6]);
172    /// ```
173    pub fn swap_data_with(&mut self, other_idx: NodeIdx<V>) {
174        assert!(other_idx.0.is_valid_for(self.col), "{}", INVALID_IDX_ERROR);
175        let a = self.node_ptr;
176        let b = other_idx.0.node_ptr();
177        Self::swap_data_of_nodes(a, b);
178    }
179
180    /// Swaps the data of this node with its parent's data, and returns true.
181    ///
182    /// Does nothing and returns false if this node is the root, and hence, has no parent.
183    ///
184    /// # Examples
185    ///
186    /// ```
187    /// use orx_tree::*;
188    ///
189    /// //      1
190    /// //     ╱ ╲
191    /// //    ╱   ╲
192    /// //   2     3
193    /// //  ╱ ╲   ╱ ╲
194    /// // 4   5 6   7
195    /// // |     |  ╱ ╲
196    /// // 8     9 10  11
197    /// let mut tree = DynTree::new(1);
198    /// let [id2, id3] = tree.root_mut().push_children([2, 3]);
199    /// let [id4, _] = tree.node_mut(id2).push_children([4, 5]);
200    /// let id8 = tree.node_mut(id4).push_child(8);
201    /// let [id6, id7] = tree.node_mut(id3).push_children([6, 7]);
202    /// tree.node_mut(id6).push_child(9);
203    /// tree.node_mut(id7).push_children([10, 11]);
204    ///
205    /// // let's move 8 up to root one by one, swapping with its parents
206    /// //      8
207    /// //     ╱ ╲
208    /// //    ╱   ╲
209    /// //   1     3
210    /// //  ╱ ╲   ╱ ╲
211    /// // 2   5 6   7
212    /// // |     |  ╱ ╲
213    /// // 4     9 10  11
214    /// tree.node_mut(id8).swap_data_with_parent();
215    /// tree.node_mut(id4).swap_data_with_parent();
216    /// tree.node_mut(id2).swap_data_with_parent();
217    ///
218    /// let swapped = tree.root_mut().swap_data_with_parent();
219    /// assert!(!swapped);
220    ///
221    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
222    /// assert_eq!(bfs, [8, 1, 3, 2, 5, 6, 7, 4, 9, 10, 11]);
223    /// ```
224    pub fn swap_data_with_parent(&mut self) -> bool {
225        let a = self.node_ptr;
226        let b = unsafe { &*a.ptr() }.prev().get();
227        match b {
228            Some(b) => {
229                Self::swap_data_of_nodes(a, b);
230                true
231            }
232            None => false,
233        }
234    }
235
236    // growth - vertically
237
238    /// Pushes a child node with the given `value`;
239    /// returns the [`NodeIdx`] of the created node.
240    ///
241    /// If this node already has children, the new child is added to the end as the
242    /// new right-most node among the children.
243    ///
244    /// # Examples
245    ///
246    /// ```
247    /// use orx_tree::*;
248    ///
249    /// //      0
250    /// //     ╱ ╲
251    /// //    ╱   ╲
252    /// //   1     2
253    /// //  ╱ ╲   ╱ ╲
254    /// // 3   4 5   6
255    /// // |     |  ╱ ╲
256    /// // 7     8 9   10
257    ///
258    /// let mut tree = DynTree::<_>::new(0);
259    ///
260    /// let mut root = tree.root_mut();
261    /// let id1 = root.push_child(1);
262    /// let id2 = root.push_child(2);
263    ///
264    /// let mut n1 = tree.node_mut(id1);
265    /// let id3 = n1.push_child(3);
266    /// n1.push_child(4);
267    ///
268    /// tree.node_mut(id3).push_child(7);
269    ///
270    /// let mut n2 = tree.node_mut(id2);
271    /// let id5 = n2.push_child(5);
272    /// let id6 = n2.push_child(6);
273    ///
274    /// tree.node_mut(id5).push_child(8);
275    /// tree.node_mut(id6).push_child(9);
276    /// tree.node_mut(id6).push_child(10);
277    ///
278    /// // validate the tree
279    ///
280    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
281    /// assert_eq!(bfs, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
282    ///
283    /// let dfs: Vec<_> = tree.root().walk::<Dfs>().copied().collect();
284    /// assert_eq!(dfs, [0, 1, 3, 7, 4, 2, 5, 8, 6, 9, 10]);
285    /// ```
286    pub fn push_child(&mut self, value: V::Item) -> NodeIdx<V> {
287        let child_ptr = self.push_child_get_ptr(value);
288        self.node_idx_for(child_ptr)
289    }
290
291    /// Pushes the given constant number of `values` as children of this node;
292    /// returns the [`NodeIdx`] array of the created nodes.
293    ///
294    /// If this node already has children, the new children are added to the end as the
295    /// new right-most nodes of the children.
296    ///
297    /// # Examples
298    ///
299    /// ```
300    /// use orx_tree::*;
301    ///
302    /// //      0
303    /// //     ╱ ╲
304    /// //    ╱   ╲
305    /// //   1     2
306    /// //  ╱ ╲   ╱ ╲
307    /// // 3   4 5   6
308    /// // |     |  ╱ ╲
309    /// // 7     8 9   10
310    ///
311    /// let mut tree = DaryTree::<4, _>::new(0);
312    ///
313    /// let mut root = tree.root_mut();
314    /// let [id1, id2] = root.push_children([1, 2]);
315    ///
316    /// let mut n1 = tree.node_mut(id1);
317    /// let [id3, _] = n1.push_children([3, 4]);
318    ///
319    /// tree.node_mut(id3).push_child(7);
320    ///
321    /// let mut n2 = tree.node_mut(id2);
322    /// let [id5, id6] = n2.push_children([5, 6]);
323    ///
324    /// tree.node_mut(id5).push_child(8);
325    /// tree.node_mut(id6).push_children([9, 10]);
326    ///
327    /// // validate the tree
328    ///
329    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
330    /// assert_eq!(bfs, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
331    ///
332    /// let dfs: Vec<_> = tree.root().walk::<Dfs>().copied().collect();
333    /// assert_eq!(dfs, [0, 1, 3, 7, 4, 2, 5, 8, 6, 9, 10]);
334    /// ```
335    pub fn push_children<const N: usize>(&mut self, values: [V::Item; N]) -> [NodeIdx<V>; N] {
336        values.map(|child| {
337            let child_ptr = self.push_child_get_ptr(child);
338            self.node_idx_for(child_ptr)
339        })
340    }
341
342    /// Pushes the given variable number of `values` as children of this node;
343    /// returns the [`NodeIdx`] iterator of the created nodes.
344    ///
345    /// If this node already has children, the new children are added to the end as the
346    /// new right-most nodes of the children.
347    ///
348    /// Importantly note that this method returns a **lazy** iterator.
349    /// If the returned iterator is not consumed, the children will **not** be pushed.
350    ///
351    /// # Examples
352    ///
353    /// ```
354    /// use orx_tree::*;
355    ///
356    /// //      0
357    /// //     ╱ ╲
358    /// //    ╱   ╲
359    /// //   1     2
360    /// //  ╱ ╲   ╱ ╲
361    /// // 3   4 5   6
362    /// // |     |  ╱ ╲
363    /// // 7     8 9   10
364    ///
365    /// let mut idx = vec![];
366    ///
367    /// let mut tree = DynTree::<_>::new(0);
368    ///
369    /// let mut root = tree.root_mut();
370    /// idx.push(root.idx());
371    /// idx.extend(root.extend_children(1..=2));
372    ///
373    /// let mut n1 = tree.node_mut(idx[1]);
374    /// idx.extend(n1.extend_children([3, 4]));
375    ///
376    /// let mut n2 = tree.node_mut(idx[2]);
377    /// idx.extend(n2.extend_children(5..=6));
378    ///
379    /// idx.push(tree.node_mut(idx[3]).push_child(7));
380    ///
381    /// idx.push(tree.node_mut(idx[5]).push_child(8));
382    /// idx.extend(tree.node_mut(idx[6]).extend_children([9, 10]));
383    ///
384    /// // validate the tree
385    ///
386    /// let root = tree.root();
387    ///
388    /// let bfs: Vec<_> = root.walk::<Bfs>().copied().collect();
389    /// assert_eq!(bfs, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
390    ///
391    /// let dfs: Vec<_> = root.walk::<Dfs>().copied().collect();
392    /// assert_eq!(dfs, [0, 1, 3, 7, 4, 2, 5, 8, 6, 9, 10]);
393    /// ```
394    pub fn extend_children<'b, I>(
395        &'b mut self,
396        values: I,
397    ) -> impl Iterator<Item = NodeIdx<V>> + 'b + use<'b, 'a, I, V, M, P, MO>
398    where
399        I: IntoIterator<Item = V::Item>,
400        I::IntoIter: 'b,
401    {
402        values.into_iter().map(|value| {
403            let child_ptr = self.push_child_get_ptr(value);
404            NodeIdx(orx_selfref_col::NodeIdx::new(
405                self.col.memory_state(),
406                child_ptr,
407            ))
408        })
409    }
410
411    /// Appends the entire `subtree` of another tree as a child of this node;
412    /// and returns the [`NodeIdx`] of the created child node.
413    ///
414    /// In other words, the root of the subtree will be immediate child of this node,
415    /// and the other nodes of the subtree will also be added with the same orientation
416    /// relative to the subtree root.
417    ///
418    /// # Subtree Variants
419    ///
420    /// * **I.** Cloned / copied subtree
421    ///   * A subtree cloned or copied from another tree.
422    ///   * The source tree remains unchanged.
423    ///   * Can be created by [`as_cloned_subtree`] and [`as_copied_subtree`] methods.
424    ///   * ***O(n)***
425    /// * **II.** Subtree moved out of another tree
426    ///   * The subtree will be moved from the source tree to this tree.
427    ///   * Can be created by [`into_subtree`] method.
428    ///   * ***O(n)***
429    /// * **III.** Another entire tree
430    ///   * The other tree will be consumed and moved into this tree.
431    ///   * ***O(1)***
432    ///
433    /// [`as_cloned_subtree`]: crate::NodeRef::as_cloned_subtree
434    /// [`as_copied_subtree`]: crate::NodeRef::as_copied_subtree
435    /// [`into_subtree`]: crate::NodeMut::into_subtree
436    ///
437    /// # Examples
438    ///
439    /// ## I. Append Subtree cloned-copied from another Tree
440    ///
441    /// Remains the source tree unchanged.
442    ///
443    /// Runs in ***O(n)*** time where n is the number of source nodes.
444    ///
445    /// ```
446    /// use orx_tree::*;
447    ///
448    /// //     a          b
449    /// // -----------------------
450    /// //     0          5
451    /// //    ╱ ╲        ╱ ╲
452    /// //   1   2      6   7
453    /// //  ╱ ╲         |  ╱ ╲
454    /// // 3   4        8 9   10
455    ///
456    /// let mut a = DynTree::<_>::new(0);
457    /// let [id1, _] = a.root_mut().push_children([1, 2]);
458    /// let [id3, _] = a.node_mut(id1).push_children([3, 4]);
459    ///
460    /// let mut b = DaryTree::<4, _>::new(5);
461    /// let [id6, id7] = b.root_mut().push_children([6, 7]);
462    /// b.node_mut(id6).push_child(8);
463    /// b.node_mut(id7).push_children([9, 10]);
464    ///
465    /// // clone b.subtree(n6) under a.n3
466    /// // clone b.subtree(n7) under a.n0
467    /// //        a
468    /// // -----------------------
469    /// //        0
470    /// //       ╱|╲
471    /// //      ╱ | ╲
472    /// //     ╱  |  ╲
473    /// //    ╱   |   ╲
474    /// //   1    2    7
475    /// //  ╱ ╲       ╱ ╲
476    /// // 3   4     9   10
477    /// // |
478    /// // 6
479    /// // |
480    /// // 8
481    ///
482    /// let n6 = b.node(id6).as_cloned_subtree();
483    /// a.node_mut(id3).push_child_tree(n6);
484    ///
485    /// let n7 = b.node(id7).as_copied_subtree();
486    /// a.root_mut().push_child_tree(n7);
487    ///
488    /// // validate the trees
489    ///
490    /// let bfs_a: Vec<_> = a.root().walk::<Bfs>().copied().collect();
491    /// assert_eq!(bfs_a, [0, 1, 2, 7, 3, 4, 9, 10, 6, 8]);
492    ///
493    /// let bfs_b: Vec<_> = b.root().walk::<Bfs>().copied().collect();
494    /// assert_eq!(bfs_b, [5, 6, 7, 8, 9, 10]); // unchanged
495    /// ```
496    ///
497    /// ## II. Append Subtree moved out of another Tree
498    ///
499    /// The source subtree rooted at the given node will be removed from the source
500    /// tree.
501    ///
502    /// Runs in ***O(n)*** time where n is the number of source nodes.
503    ///
504    /// ```
505    /// use orx_tree::*;
506    ///
507    /// //     a          b
508    /// // -----------------------
509    /// //     0          5
510    /// //    ╱ ╲        ╱ ╲
511    /// //   1   2      6   7
512    /// //  ╱ ╲         |  ╱ ╲
513    /// // 3   4        8 9   10
514    ///
515    /// // into_lazy_reclaim: to keep the indices valid
516    /// let mut a = DynTree::<_>::new(0).into_lazy_reclaim();
517    /// let [id1, id2] = a.root_mut().push_children([1, 2]);
518    /// a.node_mut(id1).push_children([3, 4]);
519    ///
520    /// // into_lazy_reclaim: to keep the indices valid
521    /// let mut b = DaryTree::<4, _>::new(5).into_lazy_reclaim();
522    /// let id5 = b.root().idx();
523    /// let [id6, id7] = b.root_mut().push_children([6, 7]);
524    /// b.node_mut(id6).push_child(8);
525    /// b.node_mut(id7).push_children([9, 10]);
526    ///
527    /// // move b.subtree(n7) under a.n2
528    /// // move a.subtree(n1) under b.n5
529    /// //     a          b
530    /// // -----------------------
531    /// //     0          5
532    /// //      ╲        ╱ ╲
533    /// //       2      6   1
534    /// //       |      |  ╱ ╲
535    /// //       7      8 3   4
536    /// //      ╱ ╲
537    /// //     9   10
538    ///
539    /// let n7 = b.node_mut(id7).into_subtree();
540    /// a.node_mut(id2).push_child_tree(n7);
541    ///
542    /// let n1 = a.node_mut(id1).into_subtree();
543    /// b.node_mut(id5).push_child_tree(n1);
544    ///
545    /// // validate the trees
546    ///
547    /// let bfs_a: Vec<_> = a.root().walk::<Bfs>().copied().collect();
548    /// assert_eq!(bfs_a, [0, 2, 7, 9, 10]);
549    ///
550    /// let bfs_b: Vec<_> = b.root().walk::<Bfs>().copied().collect();
551    /// assert_eq!(bfs_b, [5, 6, 1, 8, 3, 4]);
552    /// ```
553    ///
554    /// ## III. Append Another Tree
555    ///
556    /// The source tree will be moved into the target tree.
557    ///
558    /// Runs in ***O(1)*** time.
559    ///
560    /// ```
561    /// use orx_tree::*;
562    ///
563    /// //  tree    b      c
564    /// // ----------------------
565    /// //     0    4      2
566    /// //    ╱     |     ╱ ╲
567    /// //   1      7    5   6
568    /// //  ╱            |  ╱ ╲
569    /// // 3             8 9   10
570    /// // ----------------------
571    /// //      0
572    /// //     ╱ ╲
573    /// //    ╱   ╲
574    /// //   1     2
575    /// //  ╱ ╲   ╱ ╲
576    /// // 3   4 5   6
577    /// //     | |  ╱ ╲
578    /// //     7 8 9   10
579    ///
580    /// let mut tree = DynTree::<_>::new(0);
581    /// let id0 = tree.root().idx();
582    /// let id1 = tree.node_mut(id0).push_child(1);
583    /// tree.node_mut(id1).push_child(3);
584    ///
585    /// let mut b = BinaryTree::<_>::new(4);
586    /// b.root_mut().push_child(7);
587    ///
588    /// let mut c = DaryTree::<4, _>::new(2);
589    /// let [id5, id6] = c.root_mut().push_children([5, 6]);
590    /// c.node_mut(id5).push_child(8);
591    /// c.node_mut(id6).push_children([9, 10]);
592    ///
593    /// // merge b & c into tree
594    ///
595    /// let id4 = tree.node_mut(id1).push_child_tree(b);
596    /// let id2 = tree.node_mut(id0).push_child_tree(c);
597    ///
598    /// assert_eq!(tree.node(id2).data(), &2);
599    /// assert_eq!(tree.node(id4).data(), &4);
600    ///
601    /// // validate the tree
602    ///
603    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
604    /// assert_eq!(bfs, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
605    /// ```
606    pub fn push_child_tree<Vs>(&mut self, subtree: impl SubTree<Vs>) -> NodeIdx<V>
607    where
608        Vs: TreeVariant<Item = V::Item>,
609    {
610        subtree.append_to_node_as_child(self, self.num_children())
611    }
612
613    /// Appends the entire `subtree` of this tree as a child of this node;
614    /// and returns the [`NodeIdx`] of the created child node.
615    ///
616    /// In other words, the root of the subtree will be immediate child of this node,
617    /// and the other nodes of the subtree will also be added with the same orientation
618    /// relative to the subtree root.
619    ///
620    /// # Subtree Variants
621    ///
622    /// * **I.** Subtree moved out of this tree
623    ///   * The subtree will be moved from its original to child of this node.
624    ///   * Can be created by [`into_subtree_within`] method.
625    ///   * **Panics** if the root of the subtree is an ancestor of this node.
626    ///   * ***O(1)***
627    /// * **II.** Cloned / copied subtree from this tree
628    ///   * A subtree cloned or copied from another tree.
629    ///   * The source tree remains unchanged.
630    ///   * Can be created by [`as_cloned_subtree_within`] and [`as_copied_subtree_within`] methods.
631    ///   * ***O(n)***
632    ///
633    /// # Panics
634    ///
635    /// Panics if the subtree is moved out of this tree created by [`into_subtree_within`] (**I.**) and
636    /// the root of the subtree is an ancestor of this node.
637    /// Notice that such a move would break structural properties of the tree.
638    /// When we are not certain, we can test the relation using the the [`is_ancestor_of`] method.
639    ///
640    /// [`as_cloned_subtree_within`]: crate::NodeIdx::as_cloned_subtree_within
641    /// [`as_copied_subtree_within`]: crate::NodeIdx::as_copied_subtree_within
642    /// [`into_subtree_within`]: crate::NodeIdx::into_subtree_within
643    /// [`is_ancestor_of`]: crate::NodeRef::is_ancestor_of
644    ///
645    /// # Examples
646    ///
647    /// ## I. Append Subtree moved from another position of this tree
648    ///
649    /// ```
650    /// use orx_tree::*;
651    ///
652    /// //      1                1              1
653    /// //     ╱ ╲              ╱ ╲             |
654    /// //    ╱   ╲            ╱   ╲            |
655    /// //   2     3          2     3           2
656    /// //  ╱ ╲   ╱ ╲   =>   ╱|╲   ╱ ╲    =>   ╱|╲
657    /// // 4   5 6   7      4 5 8 6   7       4 5 8
658    /// // |                                    |
659    /// // 8                                    3
660    /// //                                     ╱ ╲
661    /// //                                    6   7
662    ///
663    /// let mut tree = DynTree::<_>::new(1);
664    ///
665    /// let [id2, id3] = tree.root_mut().push_children([2, 3]);
666    /// let [id4, id5] = tree.node_mut(id2).push_children([4, 5]);
667    /// let id8 = tree.node_mut(id4).push_child(8);
668    /// tree.node_mut(id3).push_children([6, 7]);
669    ///
670    /// // move subtree rooted at n8 (single node) as a child of n2
671    /// let st8 = id8.into_subtree_within();
672    /// tree.node_mut(id2).push_child_tree_within(st8);
673    ///
674    /// // move subtree rooted at n3 (n3, n6 & n7) as a child of n5
675    /// let st3 = id3.into_subtree_within();
676    /// tree.node_mut(id5).push_child_tree_within(st3);
677    ///
678    /// // validate the tree
679    ///
680    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
681    /// assert_eq!(bfs, [1, 2, 4, 5, 8, 3, 6, 7]);
682    ///
683    /// let dfs: Vec<_> = tree.root().walk::<Dfs>().copied().collect();
684    /// assert_eq!(dfs, [1, 2, 4, 5, 3, 6, 7, 8]);
685    /// ```
686    ///
687    /// ## II. Append Subtree cloned-copied from another position of this tree
688    ///
689    /// Remains the source tree unchanged.
690    ///
691    /// Runs in ***O(n)*** time where n is the number of source nodes.
692    ///
693    /// ```
694    /// use orx_tree::*;
695    ///
696    /// //      1                1
697    /// //     ╱ ╲              ╱ ╲
698    /// //    ╱   ╲            ╱   ╲
699    /// //   2     3          2     3
700    /// //  ╱ ╲   ╱ ╲   =>   ╱ ╲   ╱|╲
701    /// // 4   5 6   7      4   5 6 7 3
702    /// //     |            |   |    ╱ ╲
703    /// //     8            5   8   6   7
704    /// //                  |
705    /// //                  8
706    ///
707    /// let mut tree = DynTree::<_>::new(1);
708    ///
709    /// let [id2, id3] = tree.root_mut().push_children([2, 3]);
710    /// let [id4, id5] = tree.node_mut(id2).push_children([4, 5]);
711    /// tree.node_mut(id5).push_child(8);
712    /// tree.node_mut(id3).push_children([6, 7]);
713    ///
714    /// // clone subtree rooted at n5 as a child of n4
715    /// let st5 = id5.as_cloned_subtree_within();
716    /// tree.node_mut(id4).push_child_tree_within(st5);
717    ///
718    /// // copy subtree rooted at n3 (n3, n6 & n7) as a child of n3 (itself)
719    /// let st3 = id3.as_cloned_subtree_within();
720    /// tree.node_mut(id3).push_child_tree_within(st3);
721    ///
722    /// // validate the tree
723    ///
724    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
725    /// assert_eq!(bfs, [1, 2, 3, 4, 5, 6, 7, 3, 5, 8, 6, 7, 8]);
726    ///
727    /// let dfs: Vec<_> = tree.root().walk::<Dfs>().copied().collect();
728    /// assert_eq!(dfs, [1, 2, 4, 5, 8, 5, 8, 3, 6, 7, 3, 6, 7]);
729    /// ```
730    pub fn push_child_tree_within(&mut self, subtree: impl SubTreeWithin<V>) -> NodeIdx<V> {
731        subtree.append_to_node_within_as_child(self, self.num_children())
732    }
733
734    // growth - horizontally
735
736    /// Pushes a sibling node with the given `value`:
737    ///
738    /// * as the immediate left-sibling of this node when `side` is [`Side::Left`],
739    /// * as the immediate right-sibling of this node when `side` is [`Side::Right`],
740    ///
741    /// returns the [`NodeIdx`] of the created node.
742    ///
743    /// # Panics
744    ///
745    /// Panics if this node is the root; root node cannot have a sibling.
746    ///
747    /// # Examples
748    ///
749    /// ```
750    /// use orx_tree::*;
751    ///
752    /// //      1
753    /// //     ╱ ╲
754    /// //    ╱   ╲
755    /// //   2     3
756    /// //  ╱ ╲     ╲
757    /// // 4   5     6
758    ///
759    /// let mut tree = DynTree::new(1);
760    ///
761    /// let mut root = tree.root_mut();
762    /// let [id2, id3] = root.push_children([2, 3]);
763    ///
764    /// let mut n2 = tree.node_mut(id2);
765    /// let [id4, _] = n2.push_children([4, 5]);
766    ///
767    /// let mut n3 = tree.node_mut(id3);
768    /// let [id6] = n3.push_children([6]);
769    ///
770    /// // grow horizontally to obtain
771    /// //         1
772    /// //        ╱ ╲
773    /// //       ╱   ╲
774    /// //      2     3
775    /// //     ╱|╲    └────────
776    /// //    ╱ | ╲          ╱ | ╲
777    /// //   ╱ ╱ ╲ ╲        ╱  |  ╲
778    /// //  ╱ ╱   ╲ ╲      ╱╲  |  ╱╲
779    /// // 7 4    8  5    9 10 6 11 12
780    ///
781    /// let mut n4 = tree.node_mut(id4);
782    /// n4.push_sibling(Side::Left, 7);
783    /// n4.push_sibling(Side::Right, 8);
784    ///
785    /// let mut n6 = tree.node_mut(id6);
786    /// n6.push_sibling(Side::Left, 9);
787    /// n6.push_sibling(Side::Left, 10);
788    /// let id12 = n6.push_sibling(Side::Right, 12);
789    /// let id11 = n6.push_sibling(Side::Right, 11);
790    ///
791    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
792    /// assert_eq!(bfs, [1, 2, 3, 7, 4, 8, 5, 9, 10, 6, 11, 12]);
793    ///
794    /// assert_eq!(tree.node(id12).data(), &12);
795    /// assert_eq!(tree.node(id11).data(), &11);
796    /// ```
797    pub fn push_sibling(&mut self, side: Side, value: V::Item) -> NodeIdx<V> {
798        let parent_ptr = self
799            .parent_ptr()
800            .expect("Cannot push sibling to the root node");
801
802        let position = match side {
803            Side::Left => self.sibling_idx(),
804            Side::Right => self.sibling_idx() + 1,
805        };
806
807        let ptr = Self::insert_sibling_get_ptr(self.col, value, parent_ptr, position);
808        self.node_idx_for(ptr)
809    }
810
811    /// Pushes the given constant number of `values` as:
812    ///
813    /// * as the immediate left-siblings of this node when `side` is [`Side::Left`],
814    /// * as the immediate right-siblings of this node when `side` is [`Side::Right`],
815    ///
816    /// returns the [`NodeIdx`] array of the created nodes.
817    ///
818    /// # Panics
819    ///
820    /// Panics if this node is the root; root node cannot have a sibling.
821    ///
822    /// # Examples
823    ///
824    /// ```
825    /// use orx_tree::*;
826    ///
827    /// //      1
828    /// //     ╱ ╲
829    /// //    ╱   ╲
830    /// //   2     3
831    /// //  ╱ ╲     ╲
832    /// // 4   5     6
833    ///
834    /// let mut tree = DynTree::new(1);
835    ///
836    /// let mut root = tree.root_mut();
837    /// let [id2, id3] = root.push_children([2, 3]);
838    ///
839    /// let mut n2 = tree.node_mut(id2);
840    /// let [id4, _] = n2.push_children([4, 5]);
841    ///
842    /// let mut n3 = tree.node_mut(id3);
843    /// let [id6] = n3.push_children([6]);
844    ///
845    /// // grow horizontally to obtain
846    /// //         1
847    /// //        ╱ ╲
848    /// //       ╱   ╲
849    /// //      2     3
850    /// //     ╱|╲    └────────
851    /// //    ╱ | ╲          ╱ | ╲
852    /// //   ╱ ╱ ╲ ╲        ╱  |  ╲
853    /// //  ╱ ╱   ╲ ╲      ╱╲  |  ╱╲
854    /// // 7 4    8  5    9 10 6 11 12
855    ///
856    /// let mut n4 = tree.node_mut(id4);
857    /// n4.push_sibling(Side::Left, 7);
858    /// n4.push_sibling(Side::Right, 8);
859    ///
860    /// let mut n6 = tree.node_mut(id6);
861    /// let [id9, id10] = n6.push_siblings(Side::Left, [9, 10]);
862    /// let [id11, id12] = n6.push_siblings(Side::Right, [11, 12]);
863    ///
864    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
865    /// assert_eq!(bfs, [1, 2, 3, 7, 4, 8, 5, 9, 10, 6, 11, 12]);
866    ///
867    /// assert_eq!(tree.node(id9).data(), &9);
868    /// assert_eq!(tree.node(id10).data(), &10);
869    /// assert_eq!(tree.node(id11).data(), &11);
870    /// assert_eq!(tree.node(id12).data(), &12);
871    /// ```
872    pub fn push_siblings<const N: usize>(
873        &mut self,
874        side: Side,
875        values: [V::Item; N],
876    ) -> [NodeIdx<V>; N] {
877        let parent_ptr = self
878            .parent_ptr()
879            .expect("Cannot push sibling to the root node");
880
881        let mut position = match side {
882            Side::Left => self.sibling_idx(),
883            Side::Right => self.sibling_idx() + 1,
884        };
885
886        values.map(|sibling| {
887            let sibling_ptr = Self::insert_sibling_get_ptr(self.col, sibling, parent_ptr, position);
888            position += 1;
889            NodeIdx(orx_selfref_col::NodeIdx::new(
890                self.col.memory_state(),
891                sibling_ptr,
892            ))
893        })
894    }
895
896    /// Pushes the given variable number of `values` as:
897    ///
898    /// * as the immediate left-siblings of this node when `side` is [`Side::Left`],
899    /// * as the immediate right-siblings of this node when `side` is [`Side::Right`],
900    ///
901    /// returns the [`NodeIdx`] iterator of the created nodes.
902    ///
903    /// Importantly note that this method returns a **lazy** iterator.
904    /// If the returned iterator is not consumed, the siblings will **not** be pushed.
905    ///
906    /// # Panics
907    ///
908    /// Panics if this node is the root; root node cannot have a sibling.
909    ///
910    /// # Examples
911    ///
912    /// ```
913    /// use orx_tree::*;
914    ///
915    /// //      1
916    /// //     ╱ ╲
917    /// //    ╱   ╲
918    /// //   2     3
919    /// //  ╱ ╲     ╲
920    /// // 4   5     6
921    ///
922    /// let mut tree = DynTree::new(1);
923    ///
924    /// let mut root = tree.root_mut();
925    /// let [id2, id3] = root.push_children([2, 3]);
926    ///
927    /// let mut n2 = tree.node_mut(id2);
928    /// let [id4, _] = n2.push_children([4, 5]);
929    ///
930    /// let mut n3 = tree.node_mut(id3);
931    /// let [id6] = n3.push_children([6]);
932    ///
933    /// // grow horizontally to obtain
934    /// //         1
935    /// //        ╱ ╲
936    /// //       ╱   ╲
937    /// //      2     3
938    /// //     ╱|╲    └────────
939    /// //    ╱ | ╲          ╱ | ╲
940    /// //   ╱ ╱ ╲ ╲        ╱  |  ╲
941    /// //  ╱ ╱   ╲ ╲      ╱╲  |  ╱╲
942    /// // 7 4    8  5    9 10 6 11 12
943    ///
944    /// let mut n4 = tree.node_mut(id4);
945    /// n4.push_sibling(Side::Left, 7);
946    /// n4.push_sibling(Side::Right, 8);
947    ///
948    /// let mut n6 = tree.node_mut(id6);
949    /// n6.extend_siblings(Side::Left, 9..=10).count();
950    /// let idx: Vec<_> = n6.extend_siblings(Side::Right, 11..=12).collect();
951    ///
952    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
953    /// assert_eq!(bfs, [1, 2, 3, 7, 4, 8, 5, 9, 10, 6, 11, 12]);
954    ///
955    /// assert_eq!(tree.node(idx[0]).data(), &11);
956    /// assert_eq!(tree.node(idx[1]).data(), &12);
957    /// ```
958    pub fn extend_siblings<'b, I>(
959        &'b mut self,
960        side: Side,
961        values: I,
962    ) -> impl Iterator<Item = NodeIdx<V>> + 'b + use<'b, 'a, I, V, M, P, MO>
963    where
964        I: IntoIterator<Item = V::Item>,
965        I::IntoIter: 'b,
966    {
967        let parent_ptr = self
968            .parent_ptr()
969            .expect("Cannot push sibling to the root node");
970
971        let mut position = match side {
972            Side::Left => self.sibling_idx(),
973            Side::Right => self.sibling_idx() + 1,
974        };
975
976        values.into_iter().map(move |sibling| {
977            let sibling_ptr = Self::insert_sibling_get_ptr(self.col, sibling, parent_ptr, position);
978            position += 1;
979            NodeIdx(orx_selfref_col::NodeIdx::new(
980                self.col.memory_state(),
981                sibling_ptr,
982            ))
983        })
984    }
985
986    /// Appends the entire `subtree`:
987    ///
988    /// * as the immediate left-sibling of this node when `side` is [`Side::Left`],
989    /// * as the immediate right-sibling of this node when `side` is [`Side::Right`],
990    ///
991    /// returns the [`NodeIdx`] of the sibling child node.
992    ///
993    /// In other words, the root of the subtree will be immediate sibling of this node,
994    /// and the other nodes of the subtree will also be added with the same orientation
995    /// relative to the subtree root.
996    ///
997    /// # Panics
998    ///
999    /// Panics if this node is the root; root node cannot have a sibling.
1000    ///
1001    /// # Subtree Variants
1002    ///
1003    /// * **I.** Cloned / copied subtree
1004    ///   * A subtree cloned or copied from another tree.
1005    ///   * The source tree remains unchanged.
1006    ///   * Can be created by [`as_cloned_subtree`] and [`as_copied_subtree`] methods.
1007    ///   * ***O(n)***
1008    /// * **II.** Subtree moved out of another tree
1009    ///   * The subtree will be moved from the source tree to this tree.
1010    ///   * Can be created by [`into_subtree`] method.
1011    ///   * ***O(n)***
1012    /// * **III.** Another entire tree
1013    ///   * The other tree will be consumed and moved into this tree.
1014    ///   * ***O(1)***
1015    ///
1016    /// [`as_cloned_subtree`]: crate::NodeRef::as_cloned_subtree
1017    /// [`as_copied_subtree`]: crate::NodeRef::as_copied_subtree
1018    /// [`into_subtree`]: crate::NodeMut::into_subtree
1019    ///
1020    /// # Examples
1021    ///
1022    /// ## I. Append Subtree cloned-copied from another Tree
1023    ///
1024    /// Remains the source tree unchanged.
1025    ///
1026    /// Runs in ***O(n)*** time where n is the number of source nodes.
1027    ///
1028    /// ```
1029    /// use orx_tree::*;
1030    ///
1031    /// //     a          b
1032    /// // -----------------------
1033    /// //     0          5
1034    /// //    ╱ ╲        ╱ ╲
1035    /// //   1   2      6   7
1036    /// //  ╱ ╲         |  ╱ ╲
1037    /// // 3   4        8 9   10
1038    ///
1039    /// let mut a = DynTree::<_>::new(0);
1040    /// let [id1, id2] = a.root_mut().push_children([1, 2]);
1041    /// let [_, id4] = a.node_mut(id1).push_children([3, 4]);
1042    ///
1043    /// let mut b = DaryTree::<4, _>::new(5);
1044    /// let [id6, id7] = b.root_mut().push_children([6, 7]);
1045    /// b.node_mut(id6).push_child(8);
1046    /// b.node_mut(id7).push_children([9, 10]);
1047    ///
1048    /// // clone b.subtree(n6) under a.n3
1049    /// // clone b.subtree(n7) under a.n0
1050    /// //        a
1051    /// // -----------------------
1052    /// //        0
1053    /// //       ╱|╲
1054    /// //      ╱ | ╲
1055    /// //     ╱  |  ╲
1056    /// //    ╱   |   ╲
1057    /// //   1    2    7
1058    /// //  ╱|╲       ╱ ╲
1059    /// // 3 6 4     9   10
1060    /// //   |
1061    /// //   8
1062    ///
1063    /// let n6 = b.node(id6).as_cloned_subtree();
1064    /// a.node_mut(id4).push_sibling_tree(Side::Left, n6);
1065    ///
1066    /// let n7 = b.node(id7).as_copied_subtree();
1067    /// a.node_mut(id2).push_sibling_tree(Side::Right, n7);
1068    ///
1069    /// // validate the trees
1070    ///
1071    /// let bfs_a: Vec<_> = a.root().walk::<Bfs>().copied().collect();
1072    /// assert_eq!(bfs_a, [0, 1, 2, 7, 3, 6, 4, 9, 10, 8]);
1073    ///
1074    /// let bfs_b: Vec<_> = b.root().walk::<Bfs>().copied().collect();
1075    /// assert_eq!(bfs_b, [5, 6, 7, 8, 9, 10]); // unchanged
1076    /// ``````
1077    ///
1078    /// ## II. Append Subtree taken out of another Tree
1079    ///
1080    /// The source subtree rooted at the given node will be removed from the source
1081    /// tree.
1082    ///
1083    /// Runs in ***O(n)*** time where n is the number of source nodes.
1084    ///
1085    /// ```
1086    /// use orx_tree::*;
1087    ///
1088    /// //     a          b
1089    /// // -----------------------
1090    /// //     0          5
1091    /// //    ╱ ╲        ╱ ╲
1092    /// //   1   2      6   7
1093    /// //  ╱ ╲         |  ╱ ╲
1094    /// // 3   4        8 9   10
1095    ///
1096    /// // into_lazy_reclaim -> to keep indices valid
1097    /// let mut a = DynTree::<_>::new(0).into_lazy_reclaim();
1098    /// let [id1, id2] = a.root_mut().push_children([1, 2]);
1099    /// a.node_mut(id1).push_children([3, 4]);
1100    ///
1101    /// // into_lazy_reclaim -> to keep indices valid
1102    /// let mut b = DaryTree::<4, _>::new(5).into_lazy_reclaim();
1103    /// let [id6, id7] = b.root_mut().push_children([6, 7]);
1104    /// b.node_mut(id6).push_child(8);
1105    /// b.node_mut(id7).push_children([9, 10]);
1106    ///
1107    /// // move b.subtree(n7) under a.n2
1108    /// // move a.subtree(n1) under b.n5
1109    /// //     a          b
1110    /// // -----------------------
1111    /// //     0          5
1112    /// //    ╱ ╲        ╱ ╲
1113    /// //   7   2      6   1
1114    /// //  ╱ ╲         |  ╱ ╲
1115    /// // 9   10       8 3   4
1116    /// //
1117    /// //
1118    ///
1119    /// let n7 = b.node_mut(id7).into_subtree();
1120    /// a.node_mut(id2).push_sibling_tree(Side::Left, n7);
1121    ///
1122    /// let n1 = a.node_mut(id1).into_subtree();
1123    /// b.node_mut(id6).push_sibling_tree(Side::Right, n1);
1124    ///
1125    /// // validate the trees
1126    ///
1127    /// let bfs_a: Vec<_> = a.root().walk::<Bfs>().copied().collect();
1128    /// assert_eq!(bfs_a, [0, 7, 2, 9, 10]);
1129    ///
1130    /// let bfs_b: Vec<_> = b.root().walk::<Bfs>().copied().collect();
1131    /// assert_eq!(bfs_b, [5, 6, 1, 8, 3, 4]);
1132    /// ```
1133    ///
1134    /// ## III. Append Another Tree
1135    ///
1136    /// The source tree will be moved into the target tree.
1137    ///
1138    /// Runs in ***O(1)*** time.
1139    ///
1140    /// ```
1141    /// use orx_tree::*;
1142    ///
1143    /// //  tree    b      c
1144    /// // ----------------------
1145    /// //     0    4      2
1146    /// //    ╱     |     ╱ ╲
1147    /// //   1      7    5   6
1148    /// //  ╱            |  ╱ ╲
1149    /// // 3             8 9   10
1150    /// // ----------------------
1151    /// //      0
1152    /// //     ╱ ╲
1153    /// //    ╱   ╲
1154    /// //   1     2
1155    /// //  ╱ ╲   ╱ ╲
1156    /// // 4   3 5   6
1157    /// // |     |  ╱ ╲
1158    /// // 7     8 9   10
1159    ///
1160    /// let mut tree = DynTree::<_>::new(0);
1161    /// let id0 = tree.root().idx();
1162    /// let id1 = tree.node_mut(id0).push_child(1);
1163    /// let id3 = tree.node_mut(id1).push_child(3);
1164    ///
1165    /// let mut b = BinaryTree::<_>::new(4);
1166    /// b.root_mut().push_child(7);
1167    ///
1168    /// let mut c = DaryTree::<4, _>::new(2);
1169    /// let [id5, id6] = c.root_mut().push_children([5, 6]);
1170    /// c.node_mut(id5).push_child(8);
1171    /// c.node_mut(id6).push_children([9, 10]);
1172    ///
1173    /// // merge b & c into tree
1174    ///
1175    /// let id4 = tree.node_mut(id3).push_sibling_tree(Side::Left, b);
1176    /// let id2 = tree.node_mut(id1).push_sibling_tree(Side::Right, c);
1177    ///
1178    /// assert_eq!(tree.node(id2).data(), &2);
1179    /// assert_eq!(tree.node(id4).data(), &4);
1180    ///
1181    /// // validate the tree
1182    ///
1183    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
1184    /// assert_eq!(bfs, [0, 1, 2, 4, 3, 5, 6, 7, 8, 9, 10]);
1185    /// ```
1186    pub fn push_sibling_tree<Vs>(&mut self, side: Side, subtree: impl SubTree<Vs>) -> NodeIdx<V>
1187    where
1188        Vs: TreeVariant<Item = V::Item>,
1189    {
1190        let parent_ptr = self
1191            .parent_ptr()
1192            .expect("Cannot push sibling to the root node");
1193
1194        let position = match side {
1195            Side::Left => self.sibling_idx(),
1196            Side::Right => self.sibling_idx() + 1,
1197        };
1198
1199        let mut parent = NodeMut::<V, M, P, MO>::new(self.col, parent_ptr);
1200
1201        subtree.append_to_node_as_child(&mut parent, position)
1202    }
1203
1204    /// Appends the entire `subtree`:
1205    ///
1206    /// * as the immediate left-sibling of this node when `side` is [`Side::Left`],
1207    /// * as the immediate right-sibling of this node when `side` is [`Side::Right`],
1208    ///
1209    /// returns the [`NodeIdx`] of the sibling child node.
1210    ///
1211    /// In other words, the root of the subtree will be immediate sibling of this node,
1212    /// and the other nodes of the subtree will also be added with the same orientation
1213    /// relative to the subtree root.
1214    ///
1215    /// # Subtree Variants
1216    ///
1217    /// * **I.** Subtree moved out of this tree
1218    ///   * The subtree will be moved from its original to child of this node.
1219    ///   * Can be created by [`into_subtree_within`] method.
1220    ///   * **Panics** if the root of the subtree is an ancestor of this node.
1221    ///   * ***O(1)***
1222    /// * **II.** Cloned / copied subtree from this tree
1223    ///   * A subtree cloned or copied from another tree.
1224    ///   * The source tree remains unchanged.
1225    ///   * Can be created by [`as_cloned_subtree_within`] and [`as_copied_subtree_within`] methods.
1226    ///   * ***O(n)***
1227    ///
1228    /// # Panics
1229    ///
1230    /// * Panics if this node is the root; root node cannot have a sibling.
1231    /// * Panics if the subtree is moved out of this tree created by [`into_subtree_within`] (**I.**) and
1232    ///   the root of the subtree is an ancestor of this node.
1233    ///   Notice that such a move would break structural properties of the tree.
1234    ///   When we are not certain, we can test the relation using the the [`is_ancestor_of`] method.
1235    ///
1236    /// [`as_cloned_subtree_within`]: crate::NodeIdx::as_cloned_subtree_within
1237    /// [`as_copied_subtree_within`]: crate::NodeIdx::as_copied_subtree_within
1238    /// [`into_subtree_within`]: crate::NodeIdx::into_subtree_within
1239    /// [`is_ancestor_of`]: crate::NodeRef::is_ancestor_of
1240    ///
1241    /// # Examples
1242    ///
1243    /// ## I. Append Subtree moved from another position of this tree
1244    ///
1245    /// ```
1246    /// use orx_tree::*;
1247    ///
1248    /// //      1                1              1
1249    /// //     ╱ ╲              ╱ ╲             |
1250    /// //    ╱   ╲            ╱   ╲            |
1251    /// //   2     3          2     3           2
1252    /// //  ╱ ╲   ╱ ╲   =>   ╱|╲   ╱ ╲    =>   ╱|╲
1253    /// // 4   5 6   7      4 8 5 6   7       ╱ | ╲
1254    /// // |                                 ╱ ╱ ╲ ╲
1255    /// // 8                                4 3   8 5
1256    /// //                                   ╱ ╲
1257    /// //                                  6   7
1258    ///
1259    /// let mut tree = DynTree::<_>::new(1);
1260    ///
1261    /// let [id2, id3] = tree.root_mut().push_children([2, 3]);
1262    /// let [id4, id5] = tree.node_mut(id2).push_children([4, 5]);
1263    /// let id8 = tree.node_mut(id4).push_child(8);
1264    /// tree.node_mut(id3).push_children([6, 7]);
1265    ///
1266    /// // move subtree rooted at n8 (single node) as left sibling of n5
1267    /// let st8 = id8.into_subtree_within();
1268    /// tree.node_mut(id5)
1269    ///     .push_sibling_tree_within(Side::Left, st8);
1270    ///
1271    /// // move subtree rooted at n3 (n3, n6 & n7) as right sibling of n4
1272    /// let st3 = id3.into_subtree_within();
1273    /// tree.node_mut(id4)
1274    ///     .push_sibling_tree_within(Side::Right, st3);
1275    ///
1276    /// // validate the tree
1277    ///
1278    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
1279    /// assert_eq!(bfs, [1, 2, 4, 3, 8, 5, 6, 7]);
1280    ///
1281    /// let dfs: Vec<_> = tree.root().walk::<Dfs>().copied().collect();
1282    /// assert_eq!(dfs, [1, 2, 4, 3, 6, 7, 8, 5]);
1283    /// ```
1284    ///
1285    /// ## II. Append Subtree cloned-copied from another position of this tree
1286    ///
1287    /// Remains the source tree unchanged.
1288    ///
1289    /// Runs in ***O(n)*** time where n is the number of source nodes.
1290    ///
1291    /// ```
1292    /// use orx_tree::*;
1293    ///
1294    /// //      1                1
1295    /// //     ╱ ╲              ╱ ╲
1296    /// //    ╱   ╲            ╱   ╲
1297    /// //   2     3          2     3
1298    /// //  ╱ ╲   ╱ ╲   =>   ╱|╲   ╱|╲
1299    /// // 4   5 6   7      4 6 5 6 7 3
1300    /// //     |                |    ╱ ╲
1301    /// //     8                8   6   7
1302    /// //
1303    /// //
1304    ///
1305    /// let mut tree = DynTree::<_>::new(1);
1306    ///
1307    /// let [id2, id3] = tree.root_mut().push_children([2, 3]);
1308    /// let [_, id5] = tree.node_mut(id2).push_children([4, 5]);
1309    /// tree.node_mut(id5).push_child(8);
1310    /// let [id6, id7] = tree.node_mut(id3).push_children([6, 7]);
1311    ///
1312    /// // clone subtree rooted at n6 as left sibling of n5
1313    /// let st6 = id6.as_cloned_subtree_within();
1314    /// tree.node_mut(id5)
1315    ///     .push_sibling_tree_within(Side::Left, st6);
1316    ///
1317    /// // copy subtree rooted at n3 (n3, n6 & n7) as right sibling of n7
1318    /// let st3 = id3.as_cloned_subtree_within();
1319    /// tree.node_mut(id7)
1320    ///     .push_sibling_tree_within(Side::Right, st3);
1321    ///
1322    /// // validate the tree
1323    ///
1324    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
1325    /// assert_eq!(bfs, [1, 2, 3, 4, 6, 5, 6, 7, 3, 8, 6, 7]);
1326    ///
1327    /// let dfs: Vec<_> = tree.root().walk::<Dfs>().copied().collect();
1328    /// assert_eq!(dfs, [1, 2, 4, 6, 5, 8, 3, 6, 7, 3, 6, 7]);
1329    /// ```
1330    pub fn push_sibling_tree_within(
1331        &mut self,
1332        side: Side,
1333        subtree: impl SubTreeWithin<V>,
1334    ) -> NodeIdx<V> {
1335        let parent_ptr = self
1336            .parent_ptr()
1337            .expect("Cannot push sibling to the root node");
1338
1339        let position = match side {
1340            Side::Left => self.sibling_idx(),
1341            Side::Right => self.sibling_idx() + 1,
1342        };
1343
1344        let mut parent = NodeMut::<V, M, P, MO>::new(self.col, parent_ptr);
1345
1346        subtree.append_to_node_within_as_child(&mut parent, position)
1347    }
1348
1349    // move
1350
1351    /// ***O(1)*** Inserts a node with the given `value` as the parent of this node;
1352    /// and returns the [`NodeIdx`] of the new parent node.
1353    ///
1354    /// As a result of this move:
1355    ///
1356    /// * this node and all its descendants will be down-shifted by one level in depth
1357    /// * this node will be the only child of the new parent node
1358    /// * this node's earlier parent will be the parent of the new parent node
1359    /// * if this node was the root, the new parent will now be the root
1360    ///
1361    /// # Examples
1362    ///
1363    /// ```
1364    /// use orx_tree::*;
1365    ///
1366    /// //                       0
1367    /// //                       |
1368    /// //      1                1
1369    /// //     ╱ ╲              ╱ ╲
1370    /// //    ╱   ╲            ╱   ╲
1371    /// //   2     3     =>   6     7
1372    /// //        ╱ ╲         |     |
1373    /// //       4   5        2     3
1374    /// //                         ╱ ╲
1375    /// //                        4   5
1376    ///
1377    /// let mut tree = DynTree::new(1);
1378    ///
1379    /// let mut root = tree.root_mut();
1380    /// let [id2, id3] = root.push_children([2, 3]);
1381    ///
1382    /// let mut n3 = tree.node_mut(id3);
1383    /// n3.push_children([4, 5]);
1384    ///
1385    /// // push parent (insert a node vertically)
1386    ///
1387    /// let id0 = tree.root_mut().push_parent(0);
1388    /// let id6 = tree.node_mut(id2).push_parent(6);
1389    /// let id7 = tree.node_mut(id3).push_parent(7);
1390    ///
1391    /// // test inserted parent indices
1392    ///
1393    /// assert!(tree.node(id0).is_root());
1394    /// assert_eq!(tree.node(id6).data(), &6);
1395    /// assert_eq!(tree.node(id7).data(), &7);
1396    ///
1397    /// // validate the tree
1398    ///
1399    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
1400    /// assert_eq!(bfs, [0, 1, 6, 7, 2, 3, 4, 5]);
1401    ///
1402    /// let dfs: Vec<_> = tree.root().walk::<Dfs>().copied().collect();
1403    /// assert_eq!(dfs, [0, 1, 6, 2, 7, 3, 4, 5]);
1404    /// ```
1405    pub fn push_parent(&mut self, value: V::Item) -> NodeIdx<V> {
1406        let parent_ptr = self.col.push(value);
1407
1408        let child_ptr = self.node_ptr;
1409        let child = unsafe { &mut *child_ptr.ptr_mut() };
1410
1411        let ancestor_ptr = child.prev().get();
1412
1413        // down arrows
1414        match &ancestor_ptr {
1415            Some(ancestor_ptr) => {
1416                let ancestor = unsafe { &mut *ancestor_ptr.ptr_mut() };
1417                ancestor.next_mut().replace_with(child_ptr, parent_ptr);
1418            }
1419            None => {
1420                // this node was the root => parent will be the new root
1421                self.col.ends_mut().set_some(parent_ptr);
1422            }
1423        }
1424
1425        let parent = unsafe { &mut *parent_ptr.ptr_mut() };
1426        parent.next_mut().push(child_ptr);
1427
1428        // up arrows
1429
1430        let child = unsafe { &mut *child_ptr.ptr_mut() };
1431        child.prev_mut().set_some(parent_ptr);
1432
1433        parent.prev_mut().set(ancestor_ptr);
1434
1435        self.node_idx_for(parent_ptr)
1436    }
1437
1438    // shrink
1439
1440    /// Removes this node and all of its descendants from the tree; and returns the
1441    /// data of this node.
1442    ///
1443    /// > **(!)** As a method that removes nodes from the tree, this method might result in invalidating indices that are
1444    /// > cached earlier in the [`Auto`] mode, but not in the [`Lazy`] mode. Please see the documentation of [MemoryPolicy]
1445    /// > for details of node index validity. Specifically, the examples in the "Lazy Memory Claim: Preventing Invalid Indices"
1446    /// > section presents a convenient way that allows us to make sure that the indices are valid.
1447    ///
1448    /// [`Auto`]: crate::Auto
1449    /// [`Lazy`]: crate::Lazy
1450    /// [`MemoryPolicy`]: crate::MemoryPolicy
1451    ///
1452    /// # See also
1453    ///
1454    /// Note that this method returns the data of this node, while the data of the descendants
1455    /// are dropped.
1456    ///
1457    /// If the data of the entire subtree is required, you may use [`into_walk`] method with
1458    /// the desired traversal to define the order of the returned iterator.
1459    ///
1460    /// [`into_walk`]: crate::NodeMut::into_walk
1461    ///
1462    /// # Examples
1463    ///
1464    /// ```
1465    /// use orx_tree::*;
1466    ///
1467    /// //      1
1468    /// //     ╱ ╲
1469    /// //    ╱   ╲
1470    /// //   2     3
1471    /// //  ╱ ╲   ╱ ╲
1472    /// // 4   5 6   7
1473    /// // |     |  ╱ ╲
1474    /// // 8     9 10  11
1475    ///
1476    /// let mut tree = DynTree::new(1);
1477    ///
1478    /// let mut root = tree.root_mut();
1479    /// let [id2, id3] = root.push_children([2, 3]);
1480    ///
1481    /// let mut n2 = tree.node_mut(id2);
1482    /// let [id4, _] = n2.push_children([4, 5]);
1483    ///
1484    /// let id8 = tree.node_mut(id4).push_child(8);
1485    ///
1486    /// let mut n3 = tree.node_mut(id3);
1487    /// let [id6, id7] = n3.push_children([6, 7]);
1488    ///
1489    /// tree.node_mut(id6).push_child(9);
1490    /// tree.node_mut(id7).push_children([10, 11]);
1491    ///
1492    /// // prune n4 (removes 4 and 8)
1493    ///
1494    /// let data = tree.node_mut(id4).prune();
1495    /// assert_eq!(data, 4);
1496    ///
1497    /// let values: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
1498    /// assert_eq!(values, [1, 2, 3, 5, 6, 7, 9, 10, 11]);
1499    ///
1500    /// assert_eq!(tree.get_node(id4), None);
1501    /// assert_eq!(tree.try_node(id8), Err(NodeIdxError::RemovedNode));
1502    ///
1503    /// // prune n3 (3, 6, 7, 9, 10, 11)
1504    ///
1505    /// let data = tree.node_mut(id3).prune();
1506    /// assert_eq!(data, 3);
1507    ///
1508    /// let values: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
1509    /// assert_eq!(values, [1, 2, 5]);
1510    ///
1511    /// // prune the root: clear the entire (remaining) tree
1512    ///
1513    /// let data = tree.root_mut().prune();
1514    /// assert_eq!(data, 1);
1515    /// assert!(tree.is_empty());
1516    /// assert_eq!(tree.get_root(), None);
1517    /// ```
1518    #[allow(clippy::missing_panics_doc)]
1519    pub fn prune(self) -> V::Item {
1520        // TODO: we have the option to choose any traversal here; they are all safe
1521        // with SelfRefCol. We can pick the fastest one after benchmarks.
1522
1523        // # SAFETY: We use this shared reference to iterate over the pointers of the
1524        // descendent nodes. Using a mut reference to the collection, we will close
1525        // each of the descendent nodes that we visit. Closing a node corresponds to
1526        // taking its data out and emptying all of its previous and next links.
1527        // Close operation is lazy and does not invalidate the pointers that we the
1528        // shared reference to create.
1529        let iter = PostOrderIterPtr::<_, Val>::from((Default::default(), self.node_ptr));
1530        for ptr in iter {
1531            if ptr != self.node_ptr {
1532                self.col.close(ptr);
1533            }
1534        }
1535
1536        let node = unsafe { &mut *self.node_ptr.ptr_mut() };
1537        if let Some(parent) = node.prev_mut().get() {
1538            let parent = unsafe { &mut *parent.ptr_mut() };
1539            let sibling_idx = parent
1540                .next_mut()
1541                .remove(unsafe { self.node_ptr.ptr() as usize });
1542            debug_assert!(sibling_idx.is_some());
1543        }
1544
1545        let root_ptr = self.col.ends().get().expect("tree is not empty");
1546        if root_ptr == self.node_ptr {
1547            self.col.ends_mut().clear();
1548        }
1549
1550        // # SAFETY: On the other hand, close_and_reclaim might trigger a reclaim
1551        // operation which moves around the nodes, invalidating other pointers;
1552        // however, only after 'self.node_ptr' is also closed.
1553        self.col.close_and_reclaim(self.node_ptr)
1554    }
1555
1556    /// Removes this node and returns its data;
1557    /// and connects the children of this node to its parent.
1558    ///
1559    /// Therefore, unlike [`prune`], the resulting tree will contain only one less node.
1560    ///
1561    /// Assume that this node's parent had `n` children while this node is the i-th child.
1562    /// Further, assume that this node has `m` children.
1563    /// Then, the i-th element of the parent's children will be replaced with the m children.
1564    /// After the move, the parent will contain `n - 1 + m` children.
1565    ///
1566    /// [`prune`]: crate::NodeMut::prune
1567    ///
1568    /// > **(!)** As a method that removes nodes from the tree, this method might result in invalidating indices that are
1569    /// > cached earlier in the [`Auto`] mode, but not in the [`Lazy`] mode. Please see the documentation of [MemoryPolicy]
1570    /// > for details of node index validity. Specifically, the examples in the "Lazy Memory Claim: Preventing Invalid Indices"
1571    /// > section presents a convenient way that allows us to make sure that the indices are valid.
1572    ///
1573    /// [`Auto`]: crate::Auto
1574    /// [`Lazy`]: crate::Lazy
1575    /// [`MemoryPolicy`]: crate::MemoryPolicy
1576    ///
1577    /// # Panics
1578    ///
1579    /// Due to the fact that the tree can contain only one root, this move panics:
1580    ///
1581    /// * if this node is the root,
1582    /// * and it has more than one child.
1583    ///
1584    /// # Examples
1585    ///
1586    /// ```
1587    /// use orx_tree::*;
1588    ///
1589    /// //      1                    1                  1
1590    /// //     ╱ ╲                  ╱ ╲                ╱|╲
1591    /// //    ╱   ╲                ╱   ╲              ╱ | ╲
1592    /// //   2     3     (-n7)    2     3     (-n2)  4  5  3
1593    /// //  ╱ ╲   ╱ ╲     =>     ╱ ╲   ╱| ╲    =>    |    ╱| ╲
1594    /// // 4   5 6   7          4   5 6 10 11        8   6 10 11
1595    /// // |     |  ╱ ╲         |     |                  |
1596    /// // 8     9 10  11       8     9                  9
1597    ///
1598    /// let mut tree = DynTree::new(1);
1599    ///
1600    /// let mut root = tree.root_mut();
1601    /// let [id2, id3] = root.push_children([2, 3]);
1602    ///
1603    /// let mut n2 = tree.node_mut(id2);
1604    /// let [id4, _] = n2.push_children([4, 5]);
1605    ///
1606    /// tree.node_mut(id4).push_child(8);
1607    ///
1608    /// let mut n3 = tree.node_mut(id3);
1609    /// let [id6, id7] = n3.push_children([6, 7]);
1610    ///
1611    /// tree.node_mut(id6).push_child(9);
1612    /// tree.node_mut(id7).push_children([10, 11]);
1613    ///
1614    /// // take out n7
1615    ///
1616    /// let d7 = tree.node_mut(id7).take_out();
1617    /// assert_eq!(d7, 7);
1618    /// assert_eq!(tree.try_node(id7), Err(NodeIdxError::RemovedNode));
1619    ///
1620    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
1621    /// assert_eq!(bfs, [1, 2, 3, 4, 5, 6, 10, 11, 8, 9]);
1622    ///
1623    /// // take out n2
1624    ///
1625    /// let d2 = tree.node_mut(id2).take_out();
1626    /// assert_eq!(d2, 2);
1627    /// assert_eq!(tree.get_node(id2), None);
1628    ///
1629    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
1630    /// assert_eq!(bfs, [1, 4, 5, 3, 8, 6, 10, 11, 9]);
1631    /// ```
1632    pub fn take_out(self) -> V::Item {
1633        assert!(
1634            !self.is_root() || self.num_children() == 1,
1635            "If taken out node is the root, it must have only one child which will be the new root."
1636        );
1637
1638        let parent_ptr = self.parent_ptr();
1639        let sibling_idx = self.sibling_idx();
1640
1641        for child_ptr in self.node().next().children_ptr() {
1642            let child = unsafe { &mut *child_ptr.ptr_mut() };
1643            child.prev_mut().set(parent_ptr);
1644        }
1645
1646        match parent_ptr {
1647            None => {
1648                let first_child = self.node().next().children_ptr().next().cloned();
1649                self.col.ends_mut().set(first_child);
1650            }
1651            Some(parent_ptr) => {
1652                let parent = unsafe { &mut *parent_ptr.ptr_mut() };
1653                parent.next_mut().remove_at(sibling_idx);
1654                for child_ptr in self.node().next().children_ptr().rev().cloned() {
1655                    parent.next_mut().insert(sibling_idx, child_ptr);
1656                }
1657            }
1658        }
1659
1660        self.col.close_and_reclaim(self.node_ptr)
1661    }
1662
1663    /// Removes all children of this node together with the subtrees rooted at the children.
1664    /// This node remains in the tree while it becomes a leaf node if it was not already.
1665    ///
1666    /// Note that, `node.remove_children()` call is just a shorthand for:
1667    ///
1668    /// ```rust ignore
1669    /// for c in node.children_mut() {
1670    ///     _ = c.prune();
1671    /// }
1672    /// ```
1673    ///
1674    /// # Examples
1675    /// ```
1676    /// use orx_tree::*;
1677    ///
1678    /// //      1
1679    /// //     ╱ ╲
1680    /// //    ╱   ╲
1681    /// //   2     3
1682    /// //  ╱ ╲   ╱ ╲
1683    /// // 4   5 6   7
1684    /// // |     |  ╱ ╲
1685    /// // 8     9 10  11
1686    /// let mut tree = DynTree::new(1);
1687    /// let [id2, id3] = tree.root_mut().push_children([2, 3]);
1688    /// let [id4, _] = tree.node_mut(id2).push_children([4, 5]);
1689    /// tree.node_mut(id4).push_child(8);
1690    /// let [id6, id7] = tree.node_mut(id3).push_children([6, 7]);
1691    /// tree.node_mut(id6).push_child(9);
1692    /// tree.node_mut(id7).push_children([10, 11]);
1693    ///
1694    /// // let's remove children of node 3
1695    /// tree.node_mut(id3).remove_children();
1696    ///
1697    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
1698    /// assert_eq!(bfs, [1, 2, 3, 4, 5, 8]);
1699    /// ```
1700    pub fn remove_children(&mut self) {
1701        for c in self.children_mut() {
1702            _ = c.prune();
1703        }
1704    }
1705
1706    // traversal
1707
1708    /// Creates a custom mutable walk starting from this node such that:
1709    ///
1710    /// * the first element will be this node, say `n1`,
1711    /// * the second element will be node `n2 = next_node(n1)`,
1712    /// * the third element will be node `n3 = next_node(n2)`,
1713    /// * ...
1714    ///
1715    /// The iteration will terminate as soon as the `next_node` returns `None`.
1716    ///
1717    /// # Examples
1718    ///
1719    /// In the following example we create a custom iterator that walks down the tree as follows:
1720    ///
1721    /// * if the current node is not the last of its siblings, the next node will be its next sibling;
1722    /// * if the current node is the last of its siblings and if it has children, the next node will be its first child;
1723    /// * otherwise, the iteration will terminate.
1724    ///
1725    /// This walk strategy is implemented by the `next_node` function, and `custom_walk` is called with this strategy.
1726    ///
1727    /// ```rust
1728    /// use orx_tree::*;
1729    ///
1730    /// //      1
1731    /// //     ╱ ╲
1732    /// //    ╱   ╲
1733    /// //   2     3
1734    /// //  ╱ ╲   ╱ ╲
1735    /// // 4   5 6   7
1736    ///
1737    /// fn next_node<'a, T>(node: DynNode<'a, T>) -> Option<DynNode<'a, T>> {
1738    ///     let sibling_idx = node.sibling_idx();
1739    ///     let is_last_sibling = sibling_idx == node.num_siblings() - 1;
1740    ///
1741    ///     match is_last_sibling {
1742    ///         true => node.get_child(0),
1743    ///         false => match node.parent() {
1744    ///             Some(parent) => {
1745    ///                 let child_idx = sibling_idx + 1;
1746    ///                 parent.get_child(child_idx)
1747    ///             }
1748    ///             None => None,
1749    ///         },
1750    ///     }
1751    /// }
1752    ///
1753    /// let mut tree = DynTree::new(1);
1754    ///
1755    /// let mut root = tree.root_mut();
1756    /// let [id2, id3] = root.push_children([2, 3]);
1757    /// tree.node_mut(id2).push_children([4, 5]);
1758    /// tree.node_mut(id3).push_children([6, 7]);
1759    ///
1760    /// let mut root = tree.root_mut();
1761    /// for (i, x) in root.custom_walk_mut(next_node).enumerate() {
1762    ///     *x += (i + 1) * 100;
1763    /// }
1764    ///
1765    /// let values: Vec<_> = tree.root().custom_walk(next_node).copied().collect();
1766    /// assert_eq!(values, [101, 202, 303, 406, 507]);
1767    ///
1768    /// let all_values: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
1769    /// assert_eq!(all_values, [101, 202, 303, 4, 5, 406, 507]);
1770    /// ```
1771    #[allow(clippy::missing_panics_doc)]
1772    pub fn custom_walk_mut<F>(&mut self, next_node: F) -> impl Iterator<Item = &'a mut V::Item>
1773    where
1774        F: Fn(Node<'a, V, M, P>) -> Option<Node<'a, V, M, P>>,
1775    {
1776        let iter_ptr = CustomWalkIterPtr::new(self.col(), Some(self.node_ptr()), next_node);
1777        iter_ptr.map(|ptr| {
1778            let node = unsafe { &mut *ptr.ptr_mut() };
1779            node.data_mut()
1780                .expect("node is returned by next_node and is active")
1781        })
1782    }
1783
1784    /// Returns the mutable node of the `child-index`-th child of this node;
1785    /// returns None if the child index is out of bounds.
1786    ///
1787    /// See also [`into_child_mut`] for consuming traversal.
1788    ///
1789    /// [`into_child_mut`]: crate::NodeMut::into_child_mut
1790    ///
1791    /// # Examples
1792    ///
1793    /// ```
1794    /// use orx_tree::*;
1795    ///
1796    /// //       1
1797    /// //      ╱ ╲
1798    /// //     ╱   ╲
1799    /// //    ╱     ╲
1800    /// //   2       3
1801    /// //  ╱ ╲    ╱ | ╲
1802    /// // 3   4  4  5  6
1803    /// // |   |  |  |  |
1804    /// // 6   7  7  8  9
1805    ///
1806    /// let mut tree = DynTree::<_>::new(1);
1807    ///
1808    /// let mut root = tree.root_mut();
1809    /// root.push_children([2, 3]);
1810    ///
1811    /// for c in 0..root.num_children() {
1812    ///     let mut node = root.get_child_mut(c).unwrap();
1813    ///
1814    ///     let val = *node.data();
1815    ///     let children = (0..val).map(|x| x + 1 + val);
1816    ///
1817    ///     let _ = node.extend_children(children).count();
1818    ///
1819    ///     for c in 0..node.num_children() {
1820    ///         let mut node = node.get_child_mut(c).unwrap();
1821    ///         node.push_child(*node.data() + 3);
1822    ///     }
1823    /// }
1824    ///
1825    /// // validate the tree
1826    ///
1827    /// let root = tree.root();
1828    ///
1829    /// let bfs: Vec<_> = root.walk::<Bfs>().copied().collect();
1830    /// assert_eq!(bfs, [1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 7, 8, 9]);
1831    ///
1832    /// let dfs: Vec<_> = root.walk::<Dfs>().copied().collect();
1833    /// assert_eq!(dfs, [1, 2, 3, 6, 4, 7, 3, 4, 7, 5, 8, 6, 9]);
1834    /// ```
1835    pub fn get_child_mut(&mut self, child_index: usize) -> Option<NodeMut<'_, V, M, P>> {
1836        self.node()
1837            .next()
1838            .get_ptr(child_index)
1839            .map(move |p| NodeMut::new(self.col, p))
1840    }
1841
1842    /// Returns the mutable node of the `child-index`-th child of this node.
1843    ///
1844    /// See also [`into_child_mut`] for consuming traversal.
1845    ///
1846    /// [`into_child_mut`]: crate::NodeMut::into_child_mut
1847    ///
1848    /// # Panics
1849    ///
1850    /// Panics if the child index is out of bounds; i.e., `child_index >= self.num_children()`.
1851    ///
1852    /// # Examples
1853    ///
1854    /// ```
1855    /// use orx_tree::*;
1856    ///
1857    /// //       1
1858    /// //      ╱ ╲
1859    /// //     ╱   ╲
1860    /// //    ╱     ╲
1861    /// //   2       3
1862    /// //  ╱ ╲    ╱ | ╲
1863    /// // 3   4  4  5  6
1864    /// // |   |  |  |  |
1865    /// // 6   7  7  8  9
1866    ///
1867    /// let mut tree = DynTree::<_>::new(1);
1868    ///
1869    /// let mut root = tree.root_mut();
1870    /// root.push_children([2, 3]);
1871    ///
1872    /// for c in 0..root.num_children() {
1873    ///     let mut node = root.child_mut(c);
1874    ///
1875    ///     let val = *node.data();
1876    ///     let children = (0..val).map(|x| x + 1 + val);
1877    ///
1878    ///     let _ = node.extend_children(children).count();
1879    ///
1880    ///     for c in 0..node.num_children() {
1881    ///         let mut node = node.child_mut(c);
1882    ///         node.push_child(*node.data() + 3);
1883    ///     }
1884    /// }
1885    ///
1886    /// // validate the tree
1887    ///
1888    /// let root = tree.root();
1889    ///
1890    /// let bfs: Vec<_> = root.walk::<Bfs>().copied().collect();
1891    /// assert_eq!(bfs, [1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 7, 8, 9]);
1892    ///
1893    /// let dfs: Vec<_> = root.walk::<Dfs>().copied().collect();
1894    /// assert_eq!(dfs, [1, 2, 3, 6, 4, 7, 3, 4, 7, 5, 8, 6, 9]);
1895    /// ```
1896    pub fn child_mut(&mut self, child_index: usize) -> NodeMut<'_, V, M, P> {
1897        self.get_child_mut(child_index)
1898            .expect("Given child_index is out of bounds; i.e., child_index >= self.num_children()")
1899    }
1900
1901    /// Consumes this mutable node and returns the mutable node of the `child-index`-th child;
1902    /// returns None if the child index is out of bounds.
1903    ///
1904    /// See also [`get_child_mut`] for non-consuming access.
1905    ///
1906    /// [`get_child_mut`]: crate::NodeMut::get_child_mut
1907    ///
1908    /// # Examples
1909    ///
1910    /// The example below demonstrates one way to build a tree using `into_parent_mut` and `into_child_mut` methods.
1911    /// In this approach, we start from the mutable root node.
1912    /// Then, we convert one mutable node to another, always having only one mutable node.
1913    ///
1914    /// See also index returning growth methods for an alternative tree building approach, such as
1915    /// [`push_child`] and [`push_children`].
1916    ///
1917    /// [`push_child`]: crate::NodeMut::push_child
1918    /// [`push_children`]: crate::NodeMut::push_children
1919    ///
1920    /// ```
1921    /// use orx_tree::*;
1922    ///
1923    /// //        r
1924    /// //       ╱ ╲
1925    /// //      ╱   ╲
1926    /// //     ╱     ╲
1927    /// //    a       b
1928    /// //  ╱ | ╲    ╱ ╲
1929    /// // c  d  e  f   g
1930    /// //            ╱ | ╲
1931    /// //           h  i  j
1932    ///
1933    /// let mut tree = DynTree::<char>::new('r');
1934    ///
1935    /// let mut root = tree.root_mut();
1936    /// root.push_children(['a', 'b']);
1937    ///
1938    /// let mut a = root.into_child_mut(0).unwrap();
1939    /// a.push_children(['c', 'd', 'e']);
1940    ///
1941    /// let mut b = a.into_parent_mut().unwrap().into_child_mut(1).unwrap();
1942    /// b.push_children(['f', 'g']);
1943    ///
1944    /// let mut g = b.into_child_mut(1).unwrap();
1945    /// g.push_children(['h', 'i', 'j']);
1946    ///
1947    /// // validate the tree
1948    ///
1949    /// let root = tree.root();
1950    ///
1951    /// let bfs: Vec<_> = root.walk::<Bfs>().copied().collect();
1952    /// assert_eq!(bfs, ['r', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']);
1953    ///
1954    /// let dfs: Vec<_> = root.walk::<Dfs>().copied().collect();
1955    /// assert_eq!(dfs, ['r', 'a', 'c', 'd', 'e', 'b', 'f', 'g', 'h', 'i', 'j']);
1956    /// ```
1957    pub fn into_child_mut(self, child_index: usize) -> Option<NodeMut<'a, V, M, P>> {
1958        self.node()
1959            .next()
1960            .get_ptr(child_index)
1961            .map(|p| NodeMut::new(self.col, p))
1962    }
1963
1964    /// Creates an iterator over mutable nodes of children of this node.
1965    ///
1966    /// # Safety
1967    ///
1968    /// Mutable tree nodes; i.e. `NodeMut`, has two orientation for mutations:
1969    ///
1970    /// * [`NodeMutUpAndDown`]: This is the default orientation which allows to mutate both ancestors
1971    ///   and descendants of the node.
1972    /// * [`NodeMutDown`]: This orientation allows only to mutate self and descendants of the node.
1973    ///   For instance, a mutable node with this orientation does not implement [`parent_mut`] or
1974    ///   [`into_parent_mut`] methods.
1975    ///
1976    /// The `children_mut` iterator yields mutable nodes with the limited `NodeMutDown` orientation.
1977    /// Therefore, mutating children of a node is safe, since the node itself or its ancestors cannot be mutated
1978    /// during the iteration.
1979    ///
1980    /// [`parent_mut`]: Self::parent_mut
1981    /// [`into_parent_mut`]: Self::into_parent_mut
1982    ///
1983    /// # Examples
1984    ///
1985    /// In the following example, we first build the tree; however:
1986    ///
1987    /// * we do not add nodes 8 & 9; and
1988    /// * we add nodes 11 & 12 with initial values of 711 & 712.
1989    ///
1990    /// Later using `children_mut` of node 2, we grow the tree by adding nodes 8 & 9.
1991    /// This demonstrates that we can safely mutate the structure of the tree.
1992    ///
1993    /// Then, using `children_mut` of node 7, we update values of its children.
1994    /// This demonstrates the mutation of node data.
1995    ///
1996    /// ```
1997    /// use orx_tree::*;
1998    ///
1999    /// //       1
2000    /// //      ╱ ╲
2001    /// //     ╱   ╲
2002    /// //    ╱     ╲
2003    /// //   2       3
2004    /// //  ╱ ╲     ╱  ╲
2005    /// // 4   5   6    7
2006    /// // |   |   |   ╱ ╲
2007    /// // *8  *9 10 *11 *12
2008    ///
2009    /// let mut tree = DynTree::<_>::new(1);
2010    ///
2011    /// let mut root = tree.root_mut();
2012    ///
2013    /// let [id2, id3] = root.push_children([2, 3]);
2014    ///
2015    /// let mut n2 = tree.node_mut(id2);
2016    /// n2.push_children([4, 5]);
2017    ///
2018    /// let mut n3 = tree.node_mut(id3);
2019    /// let [id6, id7] = n3.push_children([6, 7]);
2020    ///
2021    /// tree.node_mut(id6).push_child(10);
2022    /// tree.node_mut(id7).push_children([711, 712]);
2023    ///
2024    /// // push nodes 8 and 9 using children_mut of node 2
2025    ///
2026    /// let mut n2 = tree.node_mut(id2);
2027    /// for mut child in n2.children_mut() {
2028    ///     let child_val = *child.data(); // 4 & 5
2029    ///     child.push_child(child_val + 4); // 8 & 9
2030    /// }
2031    ///
2032    /// // update values using children_mut of node 7
2033    ///
2034    /// let mut n7 = tree.node_mut(id7);
2035    /// for mut child in n7.children_mut() {
2036    ///     *child.data_mut() -= 700;
2037    /// }
2038    ///
2039    /// // validate the tree
2040    ///
2041    /// let root = tree.root();
2042    ///
2043    /// let bfs: Vec<_> = root.walk::<Bfs>().copied().collect();
2044    /// assert_eq!(bfs, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
2045    ///
2046    /// let dfs: Vec<_> = root.walk::<Dfs>().copied().collect();
2047    /// assert_eq!(dfs, [1, 2, 4, 8, 5, 9, 3, 6, 10, 7, 11, 12]);
2048    /// ```
2049    pub fn children_mut(
2050        &mut self,
2051    ) -> impl ExactSizeIterator<Item = NodeMut<'_, V, M, P, NodeMutDown>>
2052    + DoubleEndedIterator
2053    + use<'_, 'a, V, M, P, MO> {
2054        ChildrenMutIter::new(self.col, unsafe { self.node_ptr.ptr() })
2055    }
2056
2057    /// Creates an iterator that yields mutable references to data of all nodes belonging to the subtree rooted at this node.
2058    ///
2059    /// The order of the elements is determined by the generic [`Traverser`] parameter `T`.
2060    /// Available implementations are:
2061    /// * [`Bfs`] for breadth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search))
2062    /// * [`Dfs`] for (pre-order) depth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search))
2063    /// * [`PostOrder`] for post-order ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN))
2064    ///
2065    /// See also [`walk`] and [`into_walk`] variants.
2066    ///
2067    /// Note that tree traversing methods typically allocate a temporary data structure that is dropped once the
2068    /// iterator is dropped.
2069    /// In use cases where we repeatedly iterate using any of the **walk** methods over different nodes or different
2070    /// trees, we can avoid the allocation by creating the traverser only once and using [`walk_with`], [`walk_mut_with`]
2071    /// and [`into_walk_with`] methods instead.
2072    /// These methods additionally allow for iterating over nodes rather than data; and yielding node depths and sibling
2073    /// indices in addition to node data.
2074    ///
2075    /// [`Bfs`]: crate::Bfs
2076    /// [`Dfs`]: crate::Dfs
2077    /// [`PostOrder`]: crate::PostOrder
2078    /// [`walk`]: crate::NodeRef::walk
2079    /// [`into_walk`]: crate::NodeMut::into_walk
2080    /// [`walk_with`]: crate::NodeRef::walk_with
2081    /// [`walk_mut_with`]: crate::NodeMut::walk_mut_with
2082    /// [`into_walk_with`]: crate::NodeMut::into_walk_with
2083    ///
2084    /// # Examples
2085    ///
2086    /// ```
2087    /// use orx_tree::*;
2088    ///
2089    /// //      1
2090    /// //     ╱ ╲
2091    /// //    ╱   ╲
2092    /// //   2     3
2093    /// //  ╱ ╲   ╱ ╲
2094    /// // 4   5 6   7
2095    /// // |     |  ╱ ╲
2096    /// // 8     9 10  11
2097    ///
2098    /// let mut tree = DynTree::new(1);
2099    /// let [id2, id3] = tree.root_mut().push_children([2, 3]);
2100    /// let [id4, _] = tree.node_mut(id2).push_children([4, 5]);
2101    /// tree.node_mut(id4).push_child(8);
2102    /// let [id6, id7] = tree.node_mut(id3).push_children([6, 7]);
2103    /// tree.node_mut(id6).push_child(9);
2104    /// tree.node_mut(id7).push_children([10, 11]);
2105    ///
2106    /// // walk over mutable references of nodes of any subtree
2107    /// // rooted at a selected node with different traversals
2108    ///
2109    /// let mut root = tree.root_mut();
2110    /// {
2111    ///     let mut bfs = root.walk_mut::<Bfs>();
2112    ///     assert_eq!(bfs.next(), Some(&mut 1));
2113    ///     assert_eq!(bfs.next(), Some(&mut 2)); // ...
2114    /// }
2115    ///
2116    /// let mut n3 = tree.node_mut(id3);
2117    /// {
2118    ///     let mut dfs = n3.walk_mut::<Dfs>();
2119    ///     assert_eq!(dfs.next(), Some(&mut 3));
2120    ///     assert_eq!(dfs.next(), Some(&mut 6)); // ...
2121    /// }
2122    ///
2123    /// let mut n2 = tree.node_mut(id2);
2124    /// {
2125    ///     let mut post_order = n2.walk_mut::<PostOrder>();
2126    ///     assert_eq!(post_order.next(), Some(&mut 8));
2127    ///     assert_eq!(post_order.next(), Some(&mut 4)); // ...
2128    /// }
2129    /// ```
2130    pub fn walk_mut<T>(&'a mut self) -> impl Iterator<Item = &'a mut V::Item>
2131    where
2132        T: Traverser<OverData>,
2133    {
2134        T::iter_mut_with_owned_storage::<V, M, P, MO>(self)
2135    }
2136
2137    /// Creates an iterator that traverses all nodes belonging to the subtree rooted at this node.
2138    ///
2139    /// The order of the elements is determined by the type of the `traverser` which implements [`Traverser`].
2140    /// Available implementations are:
2141    /// * [`Bfs`] for breadth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search))
2142    /// * [`Dfs`] for (pre-order) depth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search))
2143    /// * [`PostOrder`] for post-order ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN))
2144    ///
2145    /// As opposed to [`walk_mut`], this method does not require internal allocation.
2146    /// Furthermore, it allows to attach node depths or sibling indices to the yield values.
2147    /// Please see the examples below.
2148    ///
2149    /// [`walk_mut`]: crate::NodeMut::walk_mut
2150    /// [`Bfs`]: crate::Bfs
2151    /// [`Dfs`]: crate::Dfs
2152    /// [`PostOrder`]: crate::PostOrder
2153    ///
2154    /// # Examples
2155    ///
2156    /// ## Examples - Repeated Iterations without Allocation
2157    ///
2158    /// ```
2159    /// use orx_tree::*;
2160    ///
2161    /// //      1
2162    /// //     ╱ ╲
2163    /// //    ╱   ╲
2164    /// //   2     3
2165    /// //  ╱ ╲   ╱ ╲
2166    /// // 4   5 6   7
2167    /// // |     |  ╱ ╲
2168    /// // 8     9 10  11
2169    ///
2170    /// let mut tree = DynTree::new(1);
2171    ///
2172    /// let mut root = tree.root_mut();
2173    /// let [id2, id3] = root.push_children([2, 3]);
2174    ///
2175    /// let mut n2 = tree.node_mut(id2);
2176    /// let [id4, _] = n2.push_children([4, 5]);
2177    ///
2178    /// tree.node_mut(id4).push_child(8);
2179    ///
2180    /// let mut n3 = tree.node_mut(id3);
2181    /// let [id6, id7] = n3.push_children([6, 7]);
2182    ///
2183    /// tree.node_mut(id6).push_child(9);
2184    /// tree.node_mut(id7).push_children([10, 11]);
2185    ///
2186    /// // create the traverser 'dfs' only once, use it many times
2187    /// // to walk over references, mutable references or removed values
2188    /// // without additional allocation
2189    ///
2190    /// let mut dfs = Dfs::default();
2191    ///
2192    /// let root = tree.root();
2193    /// let values: Vec<_> = root.walk_with(&mut dfs).copied().collect();
2194    /// assert_eq!(values, [1, 2, 4, 8, 5, 3, 6, 9, 7, 10, 11]);
2195    ///
2196    /// let mut n7 = tree.node_mut(id7);
2197    /// for x in n7.walk_mut_with(&mut dfs) {
2198    ///     *x += 100;
2199    /// }
2200    /// let values: Vec<_> = tree.root().walk_with(&mut dfs).copied().collect();
2201    /// assert_eq!(values, [1, 2, 4, 8, 5, 3, 6, 9, 107, 110, 111]);
2202    ///
2203    /// let n3 = tree.node_mut(id3);
2204    /// let removed: Vec<_> = n3.into_walk_with(&mut dfs).collect();
2205    /// assert_eq!(removed, [3, 6, 9, 107, 110, 111]);
2206    ///
2207    /// let remaining: Vec<_> = tree.root().walk_with(&mut dfs).copied().collect();
2208    /// assert_eq!(remaining, [1, 2, 4, 8, 5]);
2209    /// ```
2210    ///
2211    /// ## Examples - Yielding Different Items
2212    ///
2213    /// ```
2214    /// use orx_tree::*;
2215    ///
2216    /// //      1
2217    /// //     ╱ ╲
2218    /// //    ╱   ╲
2219    /// //   2     3
2220    /// //  ╱ ╲   ╱ ╲
2221    /// // 4   5 6   7
2222    /// // |     |  ╱ ╲
2223    /// // 8     9 10  11
2224    ///
2225    /// let mut tree = DynTree::new(1);
2226    ///
2227    /// let mut root = tree.root_mut();
2228    /// let [id2, id3] = root.push_children([2, 3]);
2229    ///
2230    /// let mut n2 = tree.node_mut(id2);
2231    /// let [id4, _] = n2.push_children([4, 5]);
2232    ///
2233    /// tree.node_mut(id4).push_child(8);
2234    ///
2235    /// let mut n3 = tree.node_mut(id3);
2236    /// let [id6, id7] = n3.push_children([6, 7]);
2237    ///
2238    /// tree.node_mut(id6).push_child(9);
2239    /// tree.node_mut(id7).push_children([10, 11]);
2240    ///
2241    /// // create the traverser 'bfs' iterator
2242    /// // to walk over nodes rather than data
2243    ///
2244    /// let mut bfs = Bfs::default().over_nodes();
2245    /// // OR: Bfs::<OverNode>::new();
2246    ///
2247    /// let n7 = tree.node(id7);
2248    /// let mut iter = n7.walk_with(&mut bfs);
2249    /// let node = iter.next().unwrap();
2250    /// assert_eq!(node.num_children(), 2);
2251    /// assert_eq!(node.get_child(1).map(|x| *x.data()), Some(11));
2252    ///
2253    /// // or to additionally yield depth and/or sibling-idx
2254    ///
2255    /// let mut dfs = Dfs::default().with_depth().with_sibling_idx();
2256    /// // OR: Dfs::<OverDepthSiblingIdxData>::new()
2257    ///
2258    /// let n3 = tree.node(id3);
2259    /// let result: Vec<_> = n3
2260    ///     .walk_with(&mut dfs)
2261    ///     .map(|(depth, sibling_idx, data)| (depth, sibling_idx, *data))
2262    ///     .collect();
2263    /// assert_eq!(
2264    ///     result,
2265    ///     [
2266    ///         (0, 0, 3),
2267    ///         (1, 0, 6),
2268    ///         (2, 0, 9),
2269    ///         (1, 1, 7),
2270    ///         (2, 0, 10),
2271    ///         (2, 1, 11)
2272    ///     ]
2273    /// );
2274    /// ```
2275    pub fn walk_mut_with<T, O>(
2276        &'a mut self,
2277        traverser: &'a mut T,
2278    ) -> impl Iterator<Item = OverItemMut<'a, V, O, M, P>>
2279    where
2280        O: OverMut,
2281        T: Traverser<O>,
2282    {
2283        traverser.iter_mut(self)
2284    }
2285
2286    /// Creates an iterator that yields owned (removed) data of all nodes belonging to the subtree rooted at this node.
2287    ///
2288    /// Note that once the returned iterator is dropped, regardless of whether it is completely used up or not,
2289    /// the subtree rooted at this node will be **removed** from the tree it belongs to.
2290    /// If this node is the root of the tree, the tree will be left empty.
2291    ///
2292    /// The order of the elements is determined by the generic [`Traverser`] parameter `T`.
2293    /// Available implementations are:
2294    /// * [`Bfs`] for breadth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search))
2295    /// * [`Dfs`] for (pre-order) depth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search))
2296    /// * [`PostOrder`] for post-order ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN))
2297    ///
2298    /// See also [`walk`] and [`walk_mut`] for iterators over shared and mutable references, respectively.
2299    ///
2300    /// Note that tree traversing methods typically allocate a temporary data structure that is dropped once the
2301    /// iterator is dropped.
2302    /// In use cases where we repeatedly iterate using any of the **walk** methods over different nodes or different
2303    /// trees, we can avoid the allocation by creating the traverser only once and using [`walk_with`], [`walk_mut_with`]
2304    /// and [`into_walk_with`] methods instead.
2305    /// These methods additionally allow for iterating over nodes rather than data; and yielding node depths and sibling
2306    /// indices in addition to node data.
2307    ///
2308    /// > **(!)** As a method that removes nodes from the tree, this method might result in invalidating indices that are
2309    /// > cached earlier in the [`Auto`] mode, but not in the [`Lazy`] mode. Please see the documentation of [MemoryPolicy]
2310    /// > for details of node index validity. Specifically, the examples in the "Lazy Memory Claim: Preventing Invalid Indices"
2311    /// > section presents a convenient way that allows us to make sure that the indices are valid.
2312    ///
2313    /// [`Auto`]: crate::Auto
2314    /// [`Lazy`]: crate::Lazy
2315    /// [`MemoryPolicy`]: crate::MemoryPolicy
2316    ///
2317    /// [`Bfs`]: crate::Bfs
2318    /// [`Dfs`]: crate::Dfs
2319    /// [`PostOrder`]: crate::PostOrder
2320    /// [`walk`]: crate::NodeRef::walk
2321    /// [`walk_mut`]: crate::NodeMut::walk_mut
2322    /// [`walk_with`]: crate::NodeRef::walk_with
2323    /// [`walk_mut_with`]: crate::NodeMut::walk_mut_with
2324    /// [`into_walk_with`]: crate::NodeMut::into_walk_with
2325    ///
2326    /// # Examples
2327    ///
2328    /// ```
2329    /// use orx_tree::*;
2330    ///
2331    /// //      1
2332    /// //     ╱ ╲
2333    /// //    ╱   ╲
2334    /// //   2     3
2335    /// //  ╱ ╲   ╱ ╲
2336    /// // 4   5 6   7
2337    /// // |     |  ╱ ╲
2338    /// // 8     9 10  11
2339    ///
2340    /// // keep indices valid during removals
2341    /// let mut tree = DynTree::new(1).into_lazy_reclaim();
2342    /// let [id2, id3] = tree.root_mut().push_children([2, 3]);
2343    /// let [id4, _] = tree.node_mut(id2).push_children([4, 5]);
2344    /// tree.node_mut(id4).push_child(8);
2345    /// let [id6, id7] = tree.node_mut(id3).push_children([6, 7]);
2346    /// tree.node_mut(id6).push_child(9);
2347    /// tree.node_mut(id7).push_children([10, 11]);
2348    ///
2349    /// // remove any subtree rooted at a selected node
2350    /// // from the tree, and collect the node values
2351    /// // in the order of different traversals
2352    ///
2353    /// let n4 = tree.node_mut(id4);
2354    /// let removed: Vec<_> = n4.into_walk::<PostOrder>().collect();
2355    /// assert_eq!(removed, [8, 4]);
2356    ///
2357    /// let remaining: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
2358    /// assert_eq!(remaining, [1, 2, 3, 5, 6, 7, 9, 10, 11]);
2359    ///
2360    /// let n3 = tree.node_mut(id3);
2361    /// let removed: Vec<_> = n3.into_walk::<Dfs>().collect();
2362    /// assert_eq!(removed, [3, 6, 9, 7, 10, 11]);
2363    ///
2364    /// let remaining: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
2365    /// assert_eq!(remaining, [1, 2, 5]);
2366    ///
2367    /// let root = tree.root_mut();
2368    /// let removed: Vec<_> = root.into_walk::<Bfs>().collect(); // empties the tree
2369    /// assert_eq!(removed, [1, 2, 5]);
2370    ///
2371    /// assert!(tree.is_empty());
2372    /// assert_eq!(tree.get_root(), None);
2373    /// ```
2374    pub fn into_walk<T>(self) -> impl Iterator<Item = V::Item>
2375    where
2376        T: Traverser<OverData>,
2377    {
2378        T::into_iter_with_owned_storage::<V, M, P, MO>(self)
2379    }
2380
2381    /// Creates an iterator that yields owned (removed) data of all nodes belonging to the subtree rooted at this node.
2382    ///
2383    /// Note that once the returned iterator is dropped, regardless of whether it is completely used up or not,
2384    /// the subtree rooted at this node will be **removed** from the tree it belongs to.
2385    /// If this node is the root of the tree, the tree will be left empty.
2386    ///
2387    /// The order of the elements is determined by the type of the `traverser` which implements [`Traverser`].
2388    /// Available implementations are:
2389    /// * [`Bfs`] for breadth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search))
2390    /// * [`Dfs`] for (pre-order) depth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search))
2391    /// * [`PostOrder`] for post-order ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN))
2392    ///
2393    /// As opposed to [`into_walk`], this method does not require internal allocation.
2394    /// Furthermore, it allows to attach node depths or sibling indices to the yield values.
2395    /// Please see the examples below.
2396    ///
2397    /// [`into_walk`]: crate::NodeMut::into_walk
2398    /// [`Bfs`]: crate::Bfs
2399    /// [`Dfs`]: crate::Dfs
2400    /// [`PostOrder`]: crate::PostOrder
2401    ///
2402    /// > **(!)** As a method that removes nodes from the tree, this method might result in invalidating indices that are
2403    /// > cached earlier in the [`Auto`] mode, but not in the [`Lazy`] mode. Please see the documentation of [MemoryPolicy]
2404    /// > for details of node index validity. Specifically, the examples in the "Lazy Memory Claim: Preventing Invalid Indices"
2405    /// > section presents a convenient way that allows us to make sure that the indices are valid.
2406    ///
2407    /// [`Auto`]: crate::Auto
2408    /// [`Lazy`]: crate::Lazy
2409    /// [`MemoryPolicy`]: crate::MemoryPolicy
2410    ///
2411    /// # Examples
2412    ///
2413    /// ## Examples - Repeated Iterations without Allocation
2414    ///
2415    /// ```
2416    /// use orx_tree::*;
2417    ///
2418    /// //      1
2419    /// //     ╱ ╲
2420    /// //    ╱   ╲
2421    /// //   2     3
2422    /// //  ╱ ╲   ╱ ╲
2423    /// // 4   5 6   7
2424    /// // |     |  ╱ ╲
2425    /// // 8     9 10  11
2426    ///
2427    /// // keep indices valid during removals
2428    /// let mut tree = DynTree::new(1).into_lazy_reclaim();
2429    /// let [id2, id3] = tree.root_mut().push_children([2, 3]);
2430    /// let [id4, _] = tree.node_mut(id2).push_children([4, 5]);
2431    /// tree.node_mut(id4).push_child(8);
2432    /// let [id6, id7] = tree.node_mut(id3).push_children([6, 7]);
2433    /// tree.node_mut(id6).push_child(9);
2434    /// tree.node_mut(id7).push_children([10, 11]);
2435    ///
2436    /// // create the traverser 'dfs' only once, use it many times
2437    /// // to walk over references, mutable references or removed values
2438    /// // without additional allocation
2439    ///
2440    /// let mut dfs = Dfs::default();
2441    ///
2442    /// let root = tree.root();
2443    /// let values: Vec<_> = root.walk_with(&mut dfs).copied().collect();
2444    /// assert_eq!(values, [1, 2, 4, 8, 5, 3, 6, 9, 7, 10, 11]);
2445    ///
2446    /// let mut n7 = tree.node_mut(id7);
2447    /// for x in n7.walk_mut_with(&mut dfs) {
2448    ///     *x += 100;
2449    /// }
2450    /// let values: Vec<_> = tree.root().walk_with(&mut dfs).copied().collect();
2451    /// assert_eq!(values, [1, 2, 4, 8, 5, 3, 6, 9, 107, 110, 111]);
2452    ///
2453    /// let n3 = tree.node_mut(id3);
2454    /// let removed: Vec<_> = n3.into_walk_with(&mut dfs).collect();
2455    /// assert_eq!(removed, [3, 6, 9, 107, 110, 111]);
2456    ///
2457    /// let remaining: Vec<_> = tree.root().walk_with(&mut dfs).copied().collect();
2458    /// assert_eq!(remaining, [1, 2, 4, 8, 5]);
2459    /// ```
2460    ///
2461    /// ## Examples - Yielding Different Items
2462    ///
2463    /// ```
2464    /// use orx_tree::*;
2465    ///
2466    /// //      1
2467    /// //     ╱ ╲
2468    /// //    ╱   ╲
2469    /// //   2     3
2470    /// //  ╱ ╲   ╱ ╲
2471    /// // 4   5 6   7
2472    /// // |     |  ╱ ╲
2473    /// // 8     9 10  11
2474    ///
2475    /// let mut tree = DynTree::new(1);
2476    ///
2477    /// let mut root = tree.root_mut();
2478    /// let [id2, id3] = root.push_children([2, 3]);
2479    ///
2480    /// let mut n2 = tree.node_mut(id2);
2481    /// let [id4, _] = n2.push_children([4, 5]);
2482    ///
2483    /// tree.node_mut(id4).push_child(8);
2484    ///
2485    /// let mut n3 = tree.node_mut(id3);
2486    /// let [id6, id7] = n3.push_children([6, 7]);
2487    ///
2488    /// tree.node_mut(id6).push_child(9);
2489    /// tree.node_mut(id7).push_children([10, 11]);
2490    ///
2491    /// // create the traverser 'bfs' iterator
2492    /// // to walk over nodes rather than data
2493    ///
2494    /// let mut bfs = Bfs::default().over_nodes();
2495    /// // OR: Bfs::<OverNode>::new();
2496    ///
2497    /// let n7 = tree.node(id7);
2498    /// let mut iter = n7.walk_with(&mut bfs);
2499    /// let node = iter.next().unwrap();
2500    /// assert_eq!(node.num_children(), 2);
2501    /// assert_eq!(node.get_child(1).map(|x| *x.data()), Some(11));
2502    ///
2503    /// // or to additionally yield depth and/or sibling-idx
2504    ///
2505    /// let mut dfs = Dfs::default().with_depth().with_sibling_idx();
2506    /// // OR: Dfs::<OverDepthSiblingIdxData>::new()
2507    ///
2508    /// let n3 = tree.node(id3);
2509    /// let result: Vec<_> = n3
2510    ///     .walk_with(&mut dfs)
2511    ///     .map(|(depth, sibling_idx, data)| (depth, sibling_idx, *data))
2512    ///     .collect();
2513    /// assert_eq!(
2514    ///     result,
2515    ///     [
2516    ///         (0, 0, 3),
2517    ///         (1, 0, 6),
2518    ///         (2, 0, 9),
2519    ///         (1, 1, 7),
2520    ///         (2, 0, 10),
2521    ///         (2, 1, 11)
2522    ///     ]
2523    /// );
2524    /// ```
2525    pub fn into_walk_with<T, O>(
2526        self,
2527        traverser: &'a mut T,
2528    ) -> impl Iterator<Item = OverItemInto<'a, V, O>>
2529    where
2530        O: OverMut,
2531        T: Traverser<O>,
2532    {
2533        traverser.into_iter(self)
2534    }
2535
2536    // traversal shorthands
2537
2538    /// Returns an iterator of mutable references to data of leaves of the subtree rooted at this node.
2539    ///
2540    /// The order of the elements is determined by the type of the `traverser` which implements [`Traverser`].
2541    /// Available implementations are:
2542    /// * [`Bfs`] for breadth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search))
2543    /// * [`Dfs`] for (pre-order) depth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search))
2544    /// * [`PostOrder`] for post-order ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN))
2545    ///
2546    /// [`Bfs`]: crate::Bfs
2547    /// [`Dfs`]: crate::Dfs
2548    /// [`PostOrder`]: crate::PostOrder
2549    ///
2550    /// # Examples
2551    ///
2552    /// ```
2553    /// use orx_tree::*;
2554    ///
2555    /// //      1
2556    /// //     ╱ ╲
2557    /// //    ╱   ╲
2558    /// //   2     3
2559    /// //  ╱ ╲   ╱ ╲
2560    /// // 4   5 6   7
2561    /// // |     |  ╱ ╲
2562    /// // 8     9 10  11
2563    ///
2564    /// let mut tree = DynTree::new(1);
2565    ///
2566    /// let mut root = tree.root_mut();
2567    /// let [id2, id3] = root.push_children([2, 3]);
2568    ///
2569    /// let mut n2 = tree.node_mut(id2);
2570    /// let [id4, _] = n2.push_children([4, 5]);
2571    ///
2572    /// tree.node_mut(id4).push_child(8);
2573    ///
2574    /// let mut n3 = tree.node_mut(id3);
2575    /// let [id6, id7] = n3.push_children([6, 7]);
2576    ///
2577    /// tree.node_mut(id6).push_child(9);
2578    /// tree.node_mut(id7).push_children([10, 11]);
2579    ///
2580    /// // access the leaves in different orders that is determined by traversal
2581    ///
2582    /// let mut root = tree.root_mut();
2583    /// for (l, leaf) in root.leaves_mut::<Bfs>().enumerate() {
2584    ///     *leaf += 100 * l;
2585    /// }
2586    ///
2587    /// let bfs_leaves: Vec<_> = tree.root().leaves::<Bfs>().copied().collect();
2588    /// assert_eq!(bfs_leaves, [5, 108, 209, 310, 411]);
2589    ///
2590    /// // get the leaves from any node
2591    ///
2592    /// let mut n3 = tree.node_mut(id3);
2593    /// for (l, leaf) in n3.leaves_mut::<PostOrder>().enumerate() {
2594    ///     *leaf -= 100 * l;
2595    /// }
2596    ///
2597    /// let n3 = tree.node(id3);
2598    /// let leaves: Vec<_> = n3.leaves::<PostOrder>().copied().collect();
2599    /// assert_eq!(leaves, [209, 210, 211]);
2600    /// ```
2601    pub fn leaves_mut<T>(&'a mut self) -> impl Iterator<Item = &'a mut V::Item>
2602    where
2603        T: Traverser<OverData>,
2604    {
2605        T::iter_ptr_with_owned_storage(self.node_ptr())
2606                .filter(|x: &NodePtr<V>| unsafe { &*x.ptr() }.next().is_empty())
2607                .map(|x: NodePtr<V>| {
2608                    <OverData as Over>::Enumeration::from_element_ptr_mut::<
2609                        'a,
2610                        V,
2611                        M,
2612                        P,
2613                        &'a mut V::Item,
2614                    >(self.col(), x)
2615                })
2616    }
2617
2618    /// Creates an iterator of mutable references to leaves of the subtree rooted at this node.
2619    ///
2620    /// The order of the leaves is determined by the type of the `traverser` which implements [`Traverser`].
2621    /// Available implementations are:
2622    /// * [`Bfs`] for breadth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search))
2623    /// * [`Dfs`] for (pre-order) depth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search))
2624    /// * [`PostOrder`] for post-order ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN))
2625    ///
2626    /// As opposed to [`leaves_mut`], this method does not require internal allocation.
2627    /// Furthermore, it allows to attach node depths or sibling indices to the yield values.
2628    /// Please see the examples below.
2629    ///
2630    /// [`leaves_mut`]: crate::NodeMut::leaves_mut
2631    /// [`Bfs`]: crate::Bfs
2632    /// [`Dfs`]: crate::Dfs
2633    /// [`PostOrder`]: crate::PostOrder
2634    ///
2635    /// # Examples
2636    ///
2637    /// ## Examples - Repeated Iterations without Allocation
2638    ///
2639    /// ```
2640    /// use orx_tree::*;
2641    ///
2642    /// //      1
2643    /// //     ╱ ╲
2644    /// //    ╱   ╲
2645    /// //   2     3
2646    /// //  ╱ ╲   ╱ ╲
2647    /// // 4   5 6   7
2648    /// // |     |  ╱ ╲
2649    /// // 8     9 10  11
2650    ///
2651    /// let mut tree = DynTree::new(1);
2652    ///
2653    /// let mut root = tree.root_mut();
2654    /// let [id2, id3] = root.push_children([2, 3]);
2655    ///
2656    /// let mut n2 = tree.node_mut(id2);
2657    /// let [id4, _] = n2.push_children([4, 5]);
2658    ///
2659    /// tree.node_mut(id4).push_child(8);
2660    ///
2661    /// let mut n3 = tree.node_mut(id3);
2662    /// let [id6, id7] = n3.push_children([6, 7]);
2663    ///
2664    /// tree.node_mut(id6).push_child(9);
2665    /// tree.node_mut(id7).push_children([10, 11]);
2666    ///
2667    /// // create the traverser 'bfs' (or others) only once, use it many times
2668    /// // to walk over references, mutable references or removed values
2669    /// // without additional allocation
2670    ///
2671    /// let mut t = Bfs::default();
2672    ///
2673    /// for (l, leaf) in tree.root_mut().leaves_mut_with(&mut t).enumerate() {
2674    ///     *leaf += 100 * l;
2675    /// }
2676    ///
2677    /// let bfs_leaves: Vec<_> = tree.root().leaves_with(&mut t).copied().collect();
2678    /// assert_eq!(bfs_leaves, [5, 108, 209, 310, 411]);
2679    ///
2680    /// // get the leaves from any node
2681    ///
2682    /// let mut n3 = tree.node_mut(id3);
2683    /// for (l, leaf) in n3.leaves_mut_with(&mut t).enumerate() {
2684    ///     *leaf -= 100 * l;
2685    /// }
2686    ///
2687    /// let n3 = tree.node(id3);
2688    /// let leaves: Vec<_> = n3.leaves_with(&mut t).copied().collect();
2689    /// assert_eq!(leaves, [209, 210, 211]);
2690    /// ```
2691    ///
2692    /// ## Examples - Yielding Different Items
2693    ///
2694    /// ```
2695    /// use orx_tree::*;
2696    ///
2697    /// //      1
2698    /// //     ╱ ╲
2699    /// //    ╱   ╲
2700    /// //   2     3
2701    /// //  ╱ ╲   ╱ ╲
2702    /// // 4   5 6   7
2703    /// // |     |  ╱ ╲
2704    /// // 8     9 10  11
2705    /// let mut tree = DynTree::new(1);
2706    ///
2707    /// let mut root = tree.root_mut();
2708    /// let [id2, id3] = root.push_children([2, 3]);
2709    ///
2710    /// let mut n2 = tree.node_mut(id2);
2711    /// let [id4, _] = n2.push_children([4, 5]);
2712    ///
2713    /// tree.node_mut(id4).push_child(8);
2714    ///
2715    /// let mut n3 = tree.node_mut(id3);
2716    /// let [id6, id7] = n3.push_children([6, 7]);
2717    ///
2718    /// tree.node_mut(id6).push_child(9);
2719    /// tree.node_mut(id7).push_children([10, 11]);
2720    ///
2721    /// // create the traverser 'bfs' iterator which additionally
2722    /// // yields depths (or sibling_idx)
2723    ///
2724    /// let mut bfs = Traversal.bfs().with_depth();
2725    ///
2726    /// for (depth, x) in tree.root_mut().leaves_mut_with(&mut bfs) {
2727    ///     *x += 100 * depth;
2728    /// }
2729    ///
2730    /// let root = tree.root();
2731    /// let leaves: Vec<_> = root.leaves_with(&mut bfs).collect();
2732    /// assert_eq!(
2733    ///     leaves,
2734    ///     [(2, &205), (3, &308), (3, &309), (3, &310), (3, &311)]
2735    /// );
2736    /// ```
2737    pub fn leaves_mut_with<T, O>(
2738        &'a mut self,
2739        traverser: &'a mut T,
2740    ) -> impl Iterator<Item = OverItemMut<'a, V, O, M, P>>
2741    where
2742        O: OverMut,
2743        T: Traverser<O>,
2744    {
2745        T::iter_ptr_with_storage(self.node_ptr(), traverser.storage_mut())
2746            .filter(|x| {
2747                let ptr: &NodePtr<V> = O::Enumeration::node_data(x);
2748                unsafe { &*ptr.ptr() }.next().is_empty()
2749            })
2750            .map(|x| {
2751                O::Enumeration::from_element_ptr_mut::<'a, V, M, P, O::NodeItemMut<'a, V, M, P>>(
2752                    self.col(),
2753                    x,
2754                )
2755            })
2756    }
2757
2758    /// Creates an iterator that yields owned (removed) data of all leaves of the subtree rooted at this node.
2759    ///
2760    /// Note that once the returned iterator is dropped, regardless of whether it is completely used up or not,
2761    /// the subtree rooted at this node will be **removed** from the tree it belongs to.
2762    /// If this node is the root of the tree, the tree will be left empty.
2763    ///
2764    /// The order of the elements is determined by the generic [`Traverser`] parameter `T`.
2765    /// Available implementations are:
2766    /// * [`Bfs`] for breadth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search))
2767    /// * [`Dfs`] for (pre-order) depth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search))
2768    /// * [`PostOrder`] for post-order ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN))
2769    ///
2770    /// See also [`leaves`] and [`leaves_mut`] for iterators over shared and mutable references, respectively.
2771    ///
2772    /// Note that tree traversing methods typically allocate a temporary data structure that is dropped once the
2773    /// iterator is dropped.
2774    /// In use cases where we repeatedly iterate using any of the **leaves** methods over different nodes or different
2775    /// trees, we can avoid the allocation by creating the traverser only once and using [`leaves_with`], [`leaves_mut_with`]
2776    /// and [`into_leaves_with`] methods instead.
2777    /// These methods additionally allow for iterating over nodes rather than data; and yielding node depths and sibling
2778    /// indices in addition to node data.
2779    ///
2780    /// > **(!)** As a method that removes nodes from the tree, this method might result in invalidating indices that are
2781    /// > cached earlier in the [`Auto`] mode, but not in the [`Lazy`] mode. Please see the documentation of [MemoryPolicy]
2782    /// > for details of node index validity. Specifically, the examples in the "Lazy Memory Claim: Preventing Invalid Indices"
2783    /// > section presents a convenient way that allows us to make sure that the indices are valid.
2784    ///
2785    /// [`Auto`]: crate::Auto
2786    /// [`Lazy`]: crate::Lazy
2787    /// [`MemoryPolicy`]: crate::MemoryPolicy
2788    ///
2789    /// [`Bfs`]: crate::Bfs
2790    /// [`Dfs`]: crate::Dfs
2791    /// [`PostOrder`]: crate::PostOrder
2792    /// [`leaves`]: crate::NodeRef::leaves
2793    /// [`leaves_mut`]: crate::NodeMut::walk_mut
2794    /// [`leaves_with`]: crate::NodeRef::leaves_with
2795    /// [`leaves_mut_with`]: crate::NodeMut::leaves_mut_with
2796    /// [`into_leaves_with`]: crate::NodeMut::into_leaves_with
2797    ///
2798    /// # Examples
2799    ///
2800    /// ```
2801    /// use orx_tree::*;
2802    ///
2803    /// //      1
2804    /// //     ╱ ╲
2805    /// //    ╱   ╲
2806    /// //   2     3
2807    /// //  ╱ ╲   ╱ ╲
2808    /// // 4   5 6   7
2809    /// // |     |  ╱ ╲
2810    /// // 8     9 10  11
2811    ///
2812    /// let mut tree = DynTree::new(1);
2813    /// let [id2, id3] = tree.root_mut().push_children([2, 3]);
2814    /// let [id4, _] = tree.node_mut(id2).push_children([4, 5]);
2815    /// tree.node_mut(id4).push_child(8);
2816    /// let [id6, id7] = tree.node_mut(id3).push_children([6, 7]);
2817    /// tree.node_mut(id6).push_child(9);
2818    /// tree.node_mut(id7).push_children([10, 11]);
2819    ///
2820    /// // keep indices valid during removals
2821    /// let mut tree = tree.into_lazy_reclaim();
2822    ///
2823    /// let n3 = tree.node_mut(id3);
2824    /// let leaves: Vec<_> = n3.into_leaves::<Dfs>().collect();
2825    /// assert_eq!(leaves, [9, 10, 11]);
2826    ///
2827    /// //      1
2828    /// //     ╱
2829    /// //    ╱
2830    /// //   2
2831    /// //  ╱ ╲
2832    /// // 4   5
2833    /// // |
2834    /// // 8
2835    /// let remaining: Vec<_> = tree.root().walk::<Dfs>().copied().collect();
2836    /// assert_eq!(remaining, [1, 2, 4, 8, 5]);
2837    ///
2838    /// let leaves: Vec<_> = tree.root_mut().into_leaves::<Dfs>().collect();
2839    /// assert_eq!(leaves, [8, 5]);
2840    ///
2841    /// assert!(tree.is_empty());
2842    /// ```
2843    pub fn into_leaves<T>(self) -> impl Iterator<Item = V::Item>
2844    where
2845        T: Traverser<OverData>,
2846    {
2847        let storage = T::Storage::<V>::default();
2848        T::into_iter_with_storage_filtered(self, storage, |x| {
2849            let ptr = <<OverData as Over>::Enumeration as Enumeration>::node_data(&x);
2850            unsafe { &*ptr.ptr() }.next().is_empty()
2851        })
2852    }
2853
2854    /// Creates an iterator that yields owned (removed) data of all leaves of the subtree rooted at this node.
2855    ///
2856    /// Note that once the returned iterator is dropped, regardless of whether it is completely used up or not,
2857    /// the subtree rooted at this node will be **removed** from the tree it belongs to.
2858    /// If this node is the root of the tree, the tree will be left empty.
2859    ///
2860    /// The order of the elements is determined by the type of the `traverser` which implements [`Traverser`].
2861    /// Available implementations are:
2862    /// * [`Bfs`] for breadth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search))
2863    /// * [`Dfs`] for (pre-order) depth-first ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search))
2864    /// * [`PostOrder`] for post-order ([wikipedia](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN))
2865    ///
2866    /// As opposed to [`into_leaves`], this method does not require internal allocation.
2867    /// Furthermore, it allows to attach node depths or sibling indices to the yield values.
2868    /// Please see the examples below.
2869    ///
2870    /// [`into_leaves`]: crate::NodeMut::into_leaves
2871    /// [`Bfs`]: crate::Bfs
2872    /// [`Dfs`]: crate::Dfs
2873    /// [`PostOrder`]: crate::PostOrder
2874    ///
2875    /// > **(!)** As a method that removes nodes from the tree, this method might result in invalidating indices that are
2876    /// > cached earlier in the [`Auto`] mode, but not in the [`Lazy`] mode. Please see the documentation of [MemoryPolicy]
2877    /// > for details of node index validity. Specifically, the examples in the "Lazy Memory Claim: Preventing Invalid Indices"
2878    /// > section presents a convenient way that allows us to make sure that the indices are valid.
2879    ///
2880    /// [`Auto`]: crate::Auto
2881    /// [`Lazy`]: crate::Lazy
2882    /// [`MemoryPolicy`]: crate::MemoryPolicy
2883    ///
2884    /// # Examples
2885    ///
2886    /// ```
2887    /// use orx_tree::*;
2888    ///
2889    /// //      1
2890    /// //     ╱ ╲
2891    /// //    ╱   ╲
2892    /// //   2     3
2893    /// //  ╱ ╲   ╱ ╲
2894    /// // 4   5 6   7
2895    /// // |     |  ╱ ╲
2896    /// // 8     9 10  11
2897    ///
2898    /// let mut tree = DynTree::new(1);
2899    /// let [id2, id3] = tree.root_mut().push_children([2, 3]);
2900    /// let [id4, _] = tree.node_mut(id2).push_children([4, 5]);
2901    /// tree.node_mut(id4).push_child(8);
2902    /// let [id6, id7] = tree.node_mut(id3).push_children([6, 7]);
2903    /// tree.node_mut(id6).push_child(9);
2904    /// tree.node_mut(id7).push_children([10, 11]);
2905    ///
2906    /// // create the traverser 'dfs' only once, use it many times
2907    /// // to walk over references, mutable references or removed values
2908    /// // without additional allocation
2909    ///
2910    /// let mut dfs = Dfs::default();
2911    ///
2912    /// // keep indices valid during removals
2913    /// let mut tree = tree.into_lazy_reclaim();
2914    ///
2915    /// let n3 = tree.node_mut(id3);
2916    /// let leaves: Vec<_> = n3.into_leaves_with(&mut dfs).collect();
2917    /// assert_eq!(leaves, [9, 10, 11]);
2918    ///
2919    /// //      1
2920    /// //     ╱
2921    /// //    ╱
2922    /// //   2
2923    /// //  ╱ ╲
2924    /// // 4   5
2925    /// // |
2926    /// // 8
2927    /// let remaining: Vec<_> = tree.root().walk_with(&mut dfs).copied().collect();
2928    /// assert_eq!(remaining, [1, 2, 4, 8, 5]);
2929    ///
2930    /// let leaves: Vec<_> = tree.root_mut().into_leaves_with(&mut dfs).collect();
2931    /// assert_eq!(leaves, [8, 5]);
2932    ///
2933    /// assert!(tree.is_empty());
2934    /// ```
2935    pub fn into_leaves_with<T, O>(
2936        self,
2937        traverser: &'a mut T,
2938    ) -> impl Iterator<Item = OverItemInto<'a, V, O>>
2939    where
2940        O: OverMut,
2941        T: Traverser<O>,
2942    {
2943        T::into_iter_with_storage_filtered(self, traverser.storage_mut(), |x| {
2944            let ptr = <O::Enumeration as Enumeration>::node_data(x);
2945            unsafe { &*ptr.ptr() }.next().is_empty()
2946        })
2947    }
2948
2949    // recursive
2950
2951    /// Recursively sets the data of all nodes belonging to the subtree rooted at this node using the `compute_data`
2952    /// function.
2953    ///
2954    /// This method provides an expressive way to update the values of a tree where value of a node is a function of
2955    /// its prior value and values of its children. Since the values of its children subsequently depend on their own
2956    /// children, it immediately follows that the value of the node depends on values of all of its descendants that
2957    /// must be computed to be able to compute the node's value.
2958    ///
2959    /// The `compute_data` function takes two arguments:
2960    ///
2961    /// * current value (data) of this node, and
2962    /// * slice of values of children of this node that are computed recursively using `compute_data` (*);
2963    ///
2964    /// and then, computes the new value of this node.
2965    ///
2966    /// The method is named *recursive* (*) due to the fact that,
2967    ///
2968    /// * before computing the value of this node;
2969    /// * values of all of its children are also computed and set using the `compute_data` function.
2970    ///
2971    /// *Note that this method does **not** actually make recursive method calls. Instead, it internally uses the [`PostOrder`]
2972    /// traverser which ensures that all required values are computed before they are used for another computation. This
2973    /// is a guard against potential stack overflow issues, and hence, can be used for trees of arbitrary depth.*
2974    ///
2975    /// [`PostOrder`]: crate::PostOrder
2976    ///
2977    /// # Examples
2978    ///
2979    /// In the following example, we set the value of every node to the sum of values of all its descendants.
2980    ///
2981    /// While building the tree, we set only the values of the leaves.
2982    /// We initially set values of all other nodes to zero as a placeholder.
2983    /// Then, we call `recursive_set` to compute them.
2984    ///
2985    /// ```
2986    /// use orx_tree::*;
2987    ///
2988    /// let mut tree = DynTree::<_>::new(0);
2989    /// let [id1, id2] = tree.root_mut().push_children([0, 0]);
2990    /// tree.node_mut(id1).push_children([1, 3]);
2991    /// tree.node_mut(id2).push_children([7, 2, 4]);
2992    /// //      0
2993    /// //     ╱ ╲
2994    /// //    ╱   ╲
2995    /// //   0     0
2996    /// //  ╱ ╲   ╱|╲
2997    /// // 1   3 7 2 4
2998    ///
2999    /// tree.root_mut()
3000    ///     .recursive_set(
3001    ///         |current_value, children_values| match children_values.is_empty() {
3002    ///             true => *current_value, // is a leaf
3003    ///             false => children_values.iter().copied().sum(),
3004    ///         },
3005    ///     );
3006    /// //      17
3007    /// //     ╱ ╲
3008    /// //    ╱   ╲
3009    /// //   4    13
3010    /// //  ╱ ╲   ╱|╲
3011    /// // 1   3 7 2 4
3012    ///
3013    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
3014    /// assert_eq!(bfs, [17, 4, 13, 1, 3, 7, 2, 4]);
3015    /// ```
3016    ///
3017    /// The following is a similar example where leaf nodes represent deterministic outcomes of
3018    /// a process.
3019    /// The root represents the current state.
3020    /// The remaining nodes represent intermediate states that we can reach from its parent with
3021    /// the given `probability`.
3022    /// Our task is to compute `expected_value` of each state.
3023    ///
3024    /// Since we know the value of the leaves with certainty, we set them while constructing the
3025    /// tree. Then, we call `recursive_set` to compute the expected value of every other node.
3026    ///
3027    /// ```
3028    /// use orx_tree::*;
3029    ///
3030    /// #[derive(Clone)]
3031    /// struct State {
3032    ///     /// Probability of reaching this state from its parent.
3033    ///     probability: f64,
3034    ///     /// Expected value of the state; i.e., average of values of all leaves weighted by
3035    ///     /// the probability of being reached from this state.
3036    ///     expected_value: f64,
3037    /// }
3038    ///
3039    /// fn state(probability: f64, expected_value: f64) -> State {
3040    ///     State {
3041    ///         probability,
3042    ///         expected_value,
3043    ///     }
3044    /// }
3045    ///
3046    /// //         (1.0, ???)
3047    /// //         ╱         ╲
3048    /// //        ╱           ╲
3049    /// //       ╱             ╲
3050    /// //      ╱               ╲
3051    /// //  (.3, ???)        (.7, ???)
3052    /// //   ╱     ╲          |    ╲
3053    /// //  ╱       ╲         |     ╲
3054    /// // (.2, 9) (.8, 2) (.9, 5) (.1, 4)
3055    ///
3056    /// let mut tree = DynTree::<_>::new(state(1.0, 0.0));
3057    ///
3058    /// let [id1, id2] = tree
3059    ///     .root_mut()
3060    ///     .push_children([state(0.3, 0.0), state(0.7, 0.0)]);
3061    /// tree.node_mut(id1)
3062    ///     .push_children([state(0.2, 9.0), state(0.8, 2.0)]);
3063    /// tree.node_mut(id2)
3064    ///     .push_children([state(0.9, 5.0), state(0.1, 4.0)]);
3065    ///
3066    /// tree.root_mut()
3067    ///     .recursive_set(
3068    ///         |current_value, children_values| match children_values.is_empty() {
3069    ///             true => current_value.clone(), // is a leaf, we know expected value
3070    ///             false => {
3071    ///                 let expected_value = children_values
3072    ///                     .iter()
3073    ///                     .fold(0.0, |a, x| a + x.probability * x.expected_value);
3074    ///                 state(current_value.probability, expected_value)
3075    ///             }
3076    ///         },
3077    ///     );
3078    /// //         (1.0, 4.45)
3079    /// //         ╱         ╲
3080    /// //        ╱           ╲
3081    /// //       ╱             ╲
3082    /// //      ╱               ╲
3083    /// //   (.3, 3.4)      (.7, 4.9)
3084    /// //   ╱     ╲          |    ╲
3085    /// //  ╱       ╲         |     ╲
3086    /// // (.2, 9) (.8, 2) (.9, 5) (.1, 4)
3087    ///
3088    /// let equals = |a: f64, b: f64| (a - b).abs() < 1e-5;
3089    ///
3090    /// assert!(equals(tree.root().data().expected_value, 4.45));
3091    /// assert!(equals(tree.node(id1).data().expected_value, 3.40));
3092    /// assert!(equals(tree.node(id2).data().expected_value, 4.90));
3093    /// ```
3094    #[allow(clippy::missing_panics_doc)]
3095    pub fn recursive_set(&mut self, compute_data: impl Fn(&V::Item, &[&V::Item]) -> V::Item) {
3096        let iter = PostOrder::<OverPtr>::iter_ptr_with_owned_storage(self.node_ptr);
3097        let mut children_data = Vec::<&V::Item>::new();
3098
3099        for ptr in iter {
3100            let node = unsafe { &mut *ptr.ptr_mut() };
3101            let node_data = node.data().expect("is not closed");
3102
3103            for child_ptr in node.next().children_ptr() {
3104                let data = unsafe { &*child_ptr.ptr() }.data().expect("is not closed");
3105                children_data.push(data);
3106            }
3107
3108            let new_data = compute_data(node_data, &children_data);
3109
3110            *node.data_mut().expect("is not closed") = new_data;
3111
3112            children_data.clear();
3113        }
3114    }
3115
3116    // subtree
3117
3118    /// Creates a subtree view including this node as the root and all of its descendants with their orientation relative
3119    /// to this node.
3120    ///
3121    /// Consuming the created subtree in methods such as [`push_child_tree`] or [`push_sibling_tree`] will remove the
3122    /// subtree from this tree and move it to the target tree.
3123    /// Please see **Append Subtree taken out of another Tree** section of the examples of these methods.
3124    ///
3125    /// Otherwise, it has no impact on the tree.
3126    ///
3127    /// [`push_child_tree`]: crate::NodeMut::push_child_tree
3128    /// [`push_sibling_tree`]: crate::NodeMut::push_sibling_tree
3129    pub fn into_subtree(self) -> MovedSubTree<'a, V, M, P, MO> {
3130        MovedSubTree::new(self)
3131    }
3132
3133    /// Removes the subtree rooted at this node from its tree; moves it into a new tree where this node is the root.
3134    ///
3135    /// See also [`clone_as_tree`] in order to keep the original tree unchanged.
3136    ///
3137    /// [`clone_as_tree`]: crate::NodeRef::clone_as_tree
3138    ///
3139    /// # Examples
3140    ///
3141    /// ```
3142    /// use orx_tree::*;
3143    ///
3144    /// //      1
3145    /// //     ╱ ╲
3146    /// //    ╱   ╲
3147    /// //   2     3
3148    /// //  ╱ ╲   ╱ ╲
3149    /// // 4   5 6   7
3150    /// // |     |  ╱ ╲
3151    /// // 8     9 10  11
3152    /// let mut tree = DynTree::new(1).into_lazy_reclaim(); // ensure index validity
3153    /// let [id2, id3] = tree.root_mut().push_children([2, 3]);
3154    /// let [id4, _] = tree.node_mut(id2).push_children([4, 5]);
3155    /// tree.node_mut(id4).push_child(8);
3156    /// let [id6, id7] = tree.node_mut(id3).push_children([6, 7]);
3157    /// tree.node_mut(id6).push_child(9);
3158    /// tree.node_mut(id7).push_children([10, 11]);
3159    ///
3160    /// // let's move subtree rooted at n2 into new tree: tree2
3161    /// //   2
3162    /// //  ╱ ╲
3163    /// // 4   5
3164    /// // |
3165    /// // 8
3166    /// let tree2: DynTree<_> = tree.node_mut(id2).into_new_tree();
3167    /// let bfs: Vec<_> = tree2.root().walk::<Bfs>().copied().collect();
3168    /// assert_eq!(bfs, [2, 4, 5, 8]);
3169    ///
3170    /// // let's move subtree rooted at n7 into new tree: tree7
3171    /// // this time, the target tree is a BinaryTree
3172    /// //   7
3173    /// //  ╱ ╲
3174    /// // 10  11
3175    /// let tree7: BinaryTree<_> = tree.node_mut(id7).into_new_tree();
3176    /// let bfs: Vec<_> = tree7.root().walk::<Bfs>().copied().collect();
3177    /// assert_eq!(bfs, [7, 10, 11]);
3178    ///
3179    /// // these subtrees are removed from the original tree
3180    /// // 1
3181    /// //  ╲
3182    /// //   ╲
3183    /// //    3
3184    /// //   ╱
3185    /// //  6
3186    /// //  |
3187    /// //  9
3188    /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
3189    /// assert_eq!(bfs, [1, 3, 6, 9]);
3190    /// ```
3191    pub fn into_new_tree<V2>(self) -> Tree<V2, Auto, P>
3192    where
3193        V2: TreeVariant<Item = V::Item>,
3194        P::PinnedVec<V2>: Default,
3195    {
3196        self.into_subtree().into_new_tree()
3197    }
3198
3199    // helpers
3200
3201    pub(crate) fn new(col: &'a mut Col<V, M, P>, node_ptr: NodePtr<V>) -> Self {
3202        Self {
3203            col,
3204            node_ptr,
3205            phantom: PhantomData,
3206        }
3207    }
3208
3209    fn node_mut(&mut self) -> &mut N<V> {
3210        unsafe { &mut *self.node_ptr().ptr_mut() }
3211    }
3212
3213    pub(crate) fn push_child_get_ptr(&mut self, value: V::Item) -> NodePtr<V> {
3214        let parent_ptr = self.node_ptr;
3215
3216        let child_ptr = self.col.push(value);
3217
3218        let child = self.col.node_mut(child_ptr);
3219        child.prev_mut().set_some(parent_ptr);
3220
3221        let parent = self.col.node_mut(parent_ptr);
3222        parent.next_mut().push(child_ptr);
3223
3224        child_ptr
3225    }
3226
3227    fn insert_sibling_get_ptr(
3228        col: &mut Col<V, M, P>,
3229        value: V::Item,
3230        parent_ptr: NodePtr<V>,
3231        position: usize,
3232    ) -> NodePtr<V> {
3233        let sibling_ptr = col.push(value);
3234
3235        let child = col.node_mut(sibling_ptr);
3236        child.prev_mut().set_some(parent_ptr);
3237
3238        let parent = col.node_mut(parent_ptr);
3239        parent.next_mut().insert(position, sibling_ptr);
3240
3241        sibling_ptr
3242    }
3243
3244    pub(crate) fn into_inner(self) -> (&'a mut Col<V, M, P>, NodePtr<V>) {
3245        (self.col, self.node_ptr)
3246    }
3247
3248    pub(crate) fn parent_ptr(&self) -> Option<NodePtr<V>> {
3249        self.node().prev().get()
3250    }
3251
3252    /// Returns the pointer to the root; None if empty.
3253    pub(crate) fn root_ptr(&self) -> Option<NodePtr<V>> {
3254        self.col.ends().get()
3255    }
3256
3257    fn node_idx_for(&self, ptr: NodePtr<V>) -> NodeIdx<V> {
3258        NodeIdx(orx_selfref_col::NodeIdx::new(self.col.memory_state(), ptr))
3259    }
3260
3261    /// Tries to append the `subtree` as the `child_position`-th child of this node.
3262    ///
3263    /// This operation might only fail if the there is an increasing jump in depths that is
3264    /// greater than one.
3265    /// The method returns the (depth, succeeding_depth) pair as the error when this error
3266    /// is observed.
3267    #[allow(clippy::unwrap_in_result)]
3268    pub(crate) fn try_append_subtree_as_child(
3269        &mut self,
3270        subtree: impl IntoIterator<Item = (usize, V::Item)>,
3271        child_position: usize,
3272    ) -> Result<NodeIdx<V>, (usize, usize)> {
3273        let mut iter = subtree.into_iter();
3274        let (mut current_depth, value) = iter.next().expect("tree is not empty");
3275
3276        let idx = match child_position == self.num_children() {
3277            true => self.push_child(value),
3278            false => {
3279                let ptr =
3280                    Self::insert_sibling_get_ptr(self.col, value, self.node_ptr, child_position);
3281                self.node_idx_for(ptr)
3282            }
3283        };
3284
3285        let position = child_position;
3286        let mut dst = self.get_child_mut(position).expect("child exists");
3287
3288        for (depth, value) in iter {
3289            match depth > current_depth {
3290                true => {
3291                    if depth > current_depth + 1 {
3292                        return Err((current_depth, depth));
3293                    }
3294                }
3295                false => {
3296                    let num_parent_moves = current_depth - depth + 1;
3297                    for _ in 0..num_parent_moves {
3298                        dst = dst.into_parent_mut().expect("in bounds");
3299                    }
3300                }
3301            }
3302            let position = dst.num_children();
3303            dst.push_child(value);
3304            dst = dst.into_child_mut(position).expect("child exists");
3305            current_depth = depth;
3306        }
3307
3308        Ok(idx)
3309    }
3310
3311    /// Appends the `subtree` as the `child_position`-th child of this node.
3312    ///
3313    /// # Panics
3314    ///
3315    /// It is only safe to call this method where the `subtree` represents a valid depth-first sequence.
3316    /// Note that any sequence created by [`Dfs`] iterator using the [`OverDepthData`] is always valid, and hence, the conversion cannot fail.
3317    ///
3318    /// Please see [`DepthFirstSequence`] for validity conditions.
3319    ///
3320    /// [`DepthFirstSequence`]: crate::DepthFirstSequence
3321    /// [`Dfs`]: crate::Dfs
3322    /// [`OverDepthData`]: crate::traversal::OverDepthData
3323    pub(crate) fn append_subtree_as_child(
3324        &mut self,
3325        subtree: impl IntoIterator<Item = (usize, V::Item)>,
3326        child_position: usize,
3327    ) -> NodeIdx<V> {
3328        self.try_append_subtree_as_child(subtree, child_position)
3329            .expect("Since the depth first sequence is created by internal Dfs walk methods, sequence to subtree conversion cannot fail")
3330    }
3331
3332    /// Swaps the data of the two valid nodes a and b, if they are different nodes.
3333    /// Does nothing if a == b.
3334    fn swap_data_of_nodes(a: NodePtr<V>, b: NodePtr<V>) {
3335        if a != b {
3336            let a = unsafe { &mut *a.ptr_mut() };
3337            let b = unsafe { &mut *b.ptr_mut() };
3338            core::mem::swap(
3339                a.data_mut().expect("valid idx"),
3340                b.data_mut().expect("valid idx"),
3341            );
3342        }
3343    }
3344
3345    pub(crate) unsafe fn clone_node_mut(&mut self) -> Self {
3346        let node_ptr = self.node_ptr;
3347        let col = self.col as *mut Col<V, M, P>;
3348        Self {
3349            col: unsafe { &mut *col },
3350            node_ptr,
3351            phantom: PhantomData,
3352        }
3353    }
3354}
3355
3356impl<'a, V, M, P> NodeMut<'a, V, M, P, NodeMutUpAndDown>
3357where
3358    V: TreeVariant,
3359    M: MemoryPolicy,
3360    P: PinnedStorage,
3361{
3362    /// Returns the mutable node of this node's parent,
3363    /// returns None if this is the root node.
3364    ///
3365    /// See also [`into_parent_mut`] for consuming traversal.
3366    ///
3367    /// [`into_parent_mut`]: crate::NodeMut::into_parent_mut
3368    ///
3369    /// # Examples
3370    ///
3371    /// The example below demonstrates one way to build a tree using `into_parent_mut` and `into_child_mut` methods.
3372    /// In this approach, we start from the mutable root node.
3373    /// Then, we convert one mutable node to another, always having only one mutable node.
3374    ///
3375    /// See also index returning growth methods for an alternative tree building approach, such as
3376    /// [`push_child`] and [`push_children`].
3377    ///
3378    /// [`push_child`]: crate::NodeMut::push_child
3379    /// [`push_children`]: crate::NodeMut::push_children
3380    ///
3381    /// ```
3382    /// use orx_tree::*;
3383    ///
3384    /// //        x
3385    /// //       ╱ ╲
3386    /// //      ╱   ╲
3387    /// //     ╱     ╲
3388    /// //    a       b
3389    /// //  ╱ | ╲    ╱ ╲
3390    /// // c  d  e  f   g
3391    ///
3392    /// let mut tree = DynTree::<char>::new('r');
3393    ///
3394    /// let mut root = tree.root_mut();
3395    /// let [id_a, id_b] = root.push_children(['a', 'b']);
3396    ///
3397    /// let mut a = tree.node_mut(id_a);
3398    /// a.push_children(['c', 'd', 'e']);
3399    ///
3400    /// let mut b = tree.node_mut(id_b);
3401    /// let [_, id_g] = b.push_children(['f', 'g']);
3402    ///
3403    /// let mut g = tree.node_mut(id_g);
3404    /// let mut b = g.parent_mut().unwrap();
3405    /// let mut root = b.parent_mut().unwrap();
3406    ///
3407    /// *root.data_mut() = 'x';
3408    ///
3409    /// // validate the tree
3410    ///
3411    /// let root = tree.root();
3412    ///
3413    /// let bfs: Vec<_> = root.walk::<Bfs>().copied().collect();
3414    /// assert_eq!(bfs, ['x', 'a', 'b', 'c', 'd', 'e', 'f', 'g']);
3415    ///
3416    /// let dfs: Vec<_> = root.walk::<Dfs>().copied().collect();
3417    /// assert_eq!(dfs, ['x', 'a', 'c', 'd', 'e', 'b', 'f', 'g']);
3418    /// ```
3419    pub fn parent_mut(&mut self) -> Option<NodeMut<'_, V, M, P>> {
3420        self.node().prev().get().map(|p| NodeMut::new(self.col, p))
3421    }
3422
3423    /// Consumes this mutable node and returns the mutable node of its parent,
3424    /// returns None if this is the root node.
3425    ///
3426    /// See also [`parent_mut`] for non-consuming access.
3427    ///
3428    /// [`parent_mut`]: crate::NodeMut::parent_mut
3429    ///
3430    /// # Examples
3431    ///
3432    /// The example below demonstrates one way to build a tree using `into_parent_mut` and `into_child_mut` methods.
3433    /// In this approach, we start from the mutable root node.
3434    /// Then, we convert one mutable node to another, always having only one mutable node.
3435    ///
3436    /// See also index returning growth methods for an alternative tree building approach, such as
3437    /// [`push_child`] and [`push_children`].
3438    ///
3439    /// [`push_child`]: crate::NodeMut::push_child
3440    /// [`push_children`]: crate::NodeMut::push_children
3441    ///
3442    /// ```
3443    /// use orx_tree::*;
3444    ///
3445    /// //        r
3446    /// //       ╱ ╲
3447    /// //      ╱   ╲
3448    /// //     ╱     ╲
3449    /// //    a       b
3450    /// //  ╱ | ╲    ╱ ╲
3451    /// // c  d  e  f   g
3452    /// //            ╱ | ╲
3453    /// //           h  i  j
3454    ///
3455    /// let mut tree = DynTree::<char>::new('r');
3456    ///
3457    /// let mut root = tree.root_mut();
3458    /// root.push_children(['a', 'b']);
3459    ///
3460    /// let mut a = root.into_child_mut(0).unwrap();
3461    /// a.push_children(['c', 'd', 'e']);
3462    ///
3463    /// let mut b = a.into_parent_mut().unwrap().into_child_mut(1).unwrap();
3464    /// b.push_children(['f', 'g']);
3465    ///
3466    /// let mut g = b.into_child_mut(1).unwrap();
3467    /// g.push_children(['h', 'i', 'j']);
3468    ///
3469    /// // validate the tree
3470    ///
3471    /// let root = tree.root();
3472    ///
3473    /// let bfs: Vec<_> = root.walk::<Bfs>().copied().collect();
3474    /// assert_eq!(bfs, ['r', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']);
3475    ///
3476    /// let dfs: Vec<_> = root.walk::<Dfs>().copied().collect();
3477    /// assert_eq!(dfs, ['r', 'a', 'c', 'd', 'e', 'b', 'f', 'g', 'h', 'i', 'j']);
3478    /// ```
3479    pub fn into_parent_mut(self) -> Option<NodeMut<'a, V, M, P>> {
3480        self.node().prev().get().map(|p| NodeMut::new(self.col, p))
3481    }
3482}