orx_tree/common_traits/clone.rs
1use crate::{NodeRef, Tree, TreeVariant, memory::MemoryPolicy, pinned_storage::PinnedStorage};
2
3impl<V, M, P> Clone for Tree<V, M, P>
4where
5 V: TreeVariant,
6 M: MemoryPolicy,
7 P: PinnedStorage,
8 P::PinnedVec<V>: Default,
9 V::Item: Clone,
10{
11 /// Clones the tree.
12 ///
13 /// # See also
14 ///
15 /// * [`clone_as_tree`]: to clone a subtree rooted at a given node as a separate tree.
16 ///
17 /// [`clone_as_tree`]: crate::NodeRef::clone_as_tree
18 ///
19 /// # Examples
20 ///
21 /// ```
22 /// use orx_tree::*;
23 ///
24 /// // 0
25 /// // ╱ ╲
26 /// // ╱ ╲
27 /// // 1 2
28 /// // ╱ ╲ ╱ ╲
29 /// // 3 4 5 6
30 /// // | | ╱ ╲
31 /// // 7 8 9 10
32 ///
33 /// let mut tree = DynTree::new(0);
34 ///
35 /// let mut root = tree.root_mut();
36 /// let [id1, id2] = root.push_children([1, 2]);
37 ///
38 /// let mut n1 = tree.node_mut(&id1);
39 /// let [id3, _] = n1.push_children([3, 4]);
40 ///
41 /// tree.node_mut(&id3).push_child(7);
42 ///
43 /// let mut n2 = tree.node_mut(&id2);
44 /// let [id5, id6] = n2.push_children([5, 6]);
45 ///
46 /// tree.node_mut(&id5).push_child(8);
47 /// tree.node_mut(&id6).push_children([9, 10]);
48 ///
49 /// let bfs: Vec<_> = tree.root().walk::<Bfs>().copied().collect();
50 /// assert_eq!(bfs, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
51 ///
52 /// // clone the entire tree
53 ///
54 /// let clone = tree.clone();
55 /// let bfs: Vec<_> = clone.root().walk::<Bfs>().copied().collect();
56 /// assert_eq!(bfs, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
57 ///
58 /// // indices are valid only for their trees
59 ///
60 /// let indices: Vec<_> = clone.root().indices::<Bfs>().collect();
61 ///
62 /// assert_eq!(tree.get_node(&indices[2]), None);
63 /// assert_eq!(tree.try_node(&indices[2]), Err(NodeIdxError::OutOfBounds));
64 ///
65 /// assert_eq!(clone.get_node(&id2), None);
66 /// assert_eq!(clone.try_node(&id2), Err(NodeIdxError::OutOfBounds));
67 ///
68 /// assert_eq!(clone.node(&indices[2]).data(), &2);
69 /// ```
70 fn clone(&self) -> Self {
71 match self.get_root() {
72 None => Self::default(),
73 Some(root) => {
74 let mut tree = Self::new_with_root(root.data().clone());
75
76 for child in root.children() {
77 tree.root_mut().push_child_tree(child.as_cloned_subtree());
78 }
79
80 tree
81 }
82 }
83 }
84}