orx_tree/
node_mut.rs

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