Skip to main content

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