orx_tree/
node_mut.rs

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