tree_struct/
node.rs

1use super::*;
2use ptrplus::AsPtr;
3use std::{marker::PhantomPinned, ptr::NonNull};
4
5/// Helper struct to build a [`Tree`] of [`Node`]s.
6///
7/// ### Examples
8/// Can be used as a [Builder Pattern](https://rust-unofficial.github.io/patterns/patterns/creational/builder.html),
9/// or something similar, but by assigning the fields.
10///
11/// ```
12/// # use tree_struct::{Node, NodeBuilder};
13/// let tree1 = Node::builder("parent")
14///     .child(Node::builder("child a"))
15///     .child(Node::builder("child b")
16///         .child(Node::builder("child c")))
17///     .build();
18///
19/// // Or:
20///
21/// let tree2 = NodeBuilder {
22///     content: "parent",
23///     children: vec![
24///         NodeBuilder {
25///             content: "child a",
26///             children: vec![]
27///         },
28///         NodeBuilder {
29///             content: "child b",
30///             children: vec![
31///                 NodeBuilder {
32///                     content: "child c",
33///                     children: vec![]
34///                 }
35///             ]
36///         },
37///     ],
38/// }.build();
39///
40/// assert_eq!(tree1, tree2);
41/// ```
42#[derive(Debug, Default)]
43pub struct NodeBuilder<T> {
44    pub content: T,
45    pub children: Vec<Self>,
46}
47impl<T> NodeBuilder<T> {
48    /// New [`NodeBuilder`] using [Builder Pattern](https://rust-unofficial.github.io/patterns/patterns/creational/builder.html).
49    pub fn new(content: T) -> Self {
50        NodeBuilder {
51            content,
52            children: vec![],
53        }
54    }
55    pub fn child(mut self, child: Self) -> Self {
56        self.children.push(child);
57        self
58    }
59
60    /// Create a new [`Tree`] from nodes with **children** and **content**.
61    /// The children will be made into [`Pin`]ned [`Node`]s with the proper **parent**.
62    pub fn build(self) -> Tree<T> {
63        let mut root = Box::pin(Node {
64            content: self.content,
65            parent: None,
66            children: vec![],
67            _pin: PhantomPinned,
68        });
69
70        unsafe { root.as_mut().get_unchecked_mut() }.children =
71            Self::build_children(root.ptr(), self.children);
72
73        Tree { root }
74    }
75    fn build_children(parent: Parent<Node<T>>, children: Vec<Self>) -> Vec<Owned<Node<T>>> {
76        children
77            .into_iter()
78            .map(|builder| {
79                let mut child = Box::pin(Node {
80                    content: builder.content,
81                    parent: Some(parent),
82                    children: vec![],
83                    _pin: PhantomPinned,
84                });
85
86                unsafe { child.as_mut().get_unchecked_mut() }.children =
87                    Self::build_children(child.ptr(), builder.children);
88
89                child
90            })
91            .collect()
92    }
93}
94
95/// A [`Node`] has 1 [`parent`](Self::parent()) and multiple [`children`](Self::children()).
96/// It also stores [`content`](Self::content) of type **`T`**.
97///
98/// A Node is [`heap-allocated`](Box) and [`pinned`](Pin) to allow storing a reference to the parent (Node is a *self referential struct*)
99/// without the data of said parent being moved.
100/// The pointer to the parent must be valid for the lifetime of the Node that holds the pointer.
101///
102/// Therefore, in theory, a *stack-allocated unpinned* Node should not exist, but that is ok as long as the Node has *no children*.
103/// The current implementation of the methods allows asserting that such Node has no children
104/// because [`adding children`](Self::append_child()) (i.e. using a *mutable Node*) requires it to be **[`Pin`]ned**.
105/// A user can still use [`std::pin::pin!`] on a *stack-allocated* Node and add children to it,
106/// but the Node *can't be moved*, and its children are dropped along with it,
107/// so the pointer it's children hold **remains valid for their lifetimes**.
108///
109/// This allows the Node struct to implement traits that require returning a *stack-allocated* Node (e.g. [`Default`] and [`Clone`]).
110/// However, it is recommended to convert the returned [`Node`] into a [`Tree`] using `Tree::from()` or `Node::into()` as an "ez mode"
111/// for getting rid of compiler errors that are caused by trying to use `&mut Node` or trying to move it.
112pub struct Node<T> {
113    pub content: T,
114    parent: Option<Parent<Self>>,
115    children: Vec<Owned<Self>>,
116    _pin: PhantomPinned,
117}
118impl<T> Node<T> {
119    #[inline]
120    pub fn builder(content: T) -> NodeBuilder<T> {
121        NodeBuilder::new(content)
122    }
123
124    /// Get an *immutable reference* to the `parent` [`Node`] of `self`.
125    /// To get a *mutable reference*,
126    /// call [`crate::Tree::borrow_descendant()`] from the owner [`Tree`] with `self.parent().ptr()`.
127    pub fn parent(&self) -> Option<&Self> {
128        self.parent.map(|p| unsafe { p.as_ref() })
129    }
130    /// Holds references to each **child**.
131    /// /// To get a *mutable reference* to one of the **children**,
132    /// call [`crate::Tree::borrow_descendant()`] from the owner [`Tree`] with `self.parent().ptr()`.
133    pub fn children(&self) -> Box<[&Self]> {
134        self.children
135            .iter()
136            .map(|child| child.as_ref().get_ref())
137            .collect()
138    }
139
140    /// A [`Node`] is a **descendant** of another [`Node`] if:
141    /// 1. The two [`Node`]s are not the same ([`std::ptr::eq()`]).
142    /// 2. Looking up the [`Tree`] from `other`, `self` is found to be one of `other`'s ancestors. (Not recursive).
143    fn is_descendant(&self, other: NonNull<Self>) -> bool {
144        if self.is_same_as(other) {
145            return false;
146        }
147
148        let mut ancestor = unsafe { other.as_ref() }.parent();
149
150        while let Some(node) = ancestor {
151            if self.is_same_as(node) {
152                return true;
153            }
154            ancestor = node.parent();
155        }
156
157        false
158    }
159    fn find_self_next<'a>(&self, iter: impl Iterator<Item = &'a Owned<Self>>) -> Option<&'a Self> {
160        let mut iter = iter.map(|sib| sib.as_ref().get_ref());
161        iter.find(|sib| self.is_same_as(*sib));
162        iter.next()
163    }
164
165    /// Returns the [`Node`] immediately following this one in the **parent**'s [`children`](Node::children).
166    /// Otherwise returns [`None`] if `self` has no **parent**, or if it is the *last* child of the **parent**.
167    pub fn next_sibling(&self) -> Option<&Self> {
168        self.find_self_next(self.parent()?.children.iter())
169    }
170    /// Returns the [`Node`] immediately preceeding this one in the **parent**'s [`children`](Node::children).
171    /// Otherwise returns [`None`] if `self` has no **parent**, or if it is the *first* child of the **parent**.
172    pub fn prev_sibling(&self) -> Option<&Self> {
173        self.find_self_next(self.parent()?.children.iter().rev())
174    }
175
176    /// Pushes the **child** to the end of **self**'s *children*.
177    /// Also see [`Self::insert_child()`].
178    pub fn append_child(self: Pin<&mut Self>, mut child: Tree<T>) {
179        // Compiler ensures `self != child.root`.
180        unsafe {
181            let this = self.get_unchecked_mut();
182            child.root_mut().get_unchecked_mut().parent = Some(NonNull::new_unchecked(this));
183            this.children.push(child.root)
184        }
185    }
186    /// Inserts the **child** to **self**'s *children* at some index.
187    /// Also see [`Self::append_child()`].
188    pub fn insert_child(self: Pin<&mut Self>, mut child: Tree<T>, index: usize) {
189        // Compiler ensures `self != child.root`.
190        unsafe {
191            let this = self.get_unchecked_mut();
192            child.root_mut().get_unchecked_mut().parent = Some(NonNull::new_unchecked(this));
193            this.children.insert(index, child.root)
194        }
195    }
196
197    /// See [`crate::Tree::detach_descendant()`].
198    /// TODO: Don't know if should make it public.
199    ///
200    /// **descendant** does not have to be `mut`.
201    /// It should be enough to assert that the whole [`Tree`] is `mut`, so by extension the **descendant** is also `mut`.
202    pub(super) fn detach_descendant(self: Pin<&mut Self>, descendant: NonNull<Self>) -> Option<Tree<T>> {
203        if !self.is_descendant(descendant) {
204            return None;
205        }
206
207        let parent = unsafe { descendant.as_ref().parent.unwrap().as_mut() };
208
209        // Find the index of **descendant** to remove it from its parent's children list
210        let index = parent
211            .children
212            .iter()
213            .position(|child| descendant.as_ptr() == child.ptr().as_ptr())
214            .expect("Node is not found in its parent");
215
216        // If children is not UnsafeCell, use std::mem::transmute(parent.children.remove(index)).
217        let mut root = parent.children.remove(index);
218        unsafe { root.as_mut().get_unchecked_mut() }.parent = None;
219        Some(Tree { root })
220    }
221
222    /// See [`crate::Tree::borrow_descendant()`].
223    /// TODO: Don't know if should make it public.
224    ///
225    /// **descendant** does not have to be `mut`.
226    /// It should be enough to assert that the whole [`Tree`] is `mut`, so by extension the **descendant** is also `mut`.
227    pub(super) fn borrow_descendant(self: Pin<&mut Self>, descendant: NonNull<Self>) -> Option<Pin<&mut Self>> {
228        if self.is_descendant(descendant) {
229            Some(unsafe { Pin::new_unchecked(&mut *descendant.as_ptr()) })
230        } else {
231            None
232        }
233    }
234
235    #[inline]
236    /// Iterate over all the [`Node`]s of the *subtree* (including `self`) using **Breadth-First Search**.
237    pub fn iter_bfs(&self) -> IterBFS<T> {
238        IterBFS::new(self)
239    }
240    #[inline]
241    /// Iterate over all the [`Node`]s of the *subtree* (including `self`) using **Depth-First Search**.
242    pub fn iter_dfs(&self) -> IterDFS<T> {
243        IterDFS::new(self)
244    }
245
246    #[inline]
247    /// Whether two [`Node`]s are the same (that is, they reference the same object).
248    pub fn is_same_as(&self, other: impl AsPtr<Raw = Self>) -> bool {
249        std::ptr::eq(self, other.as_ptr())
250    }
251    #[inline]
252    /// Get a *[`NonNull`] pointer* for **self**, which should only be treated as a `*const Self`.
253    /// Useful for [`Tree::detach_descendant`] and [`Tree::borrow_descendant`].
254    pub fn ptr(&self) -> NonNull<Self> {
255        NonNull::from(self)
256    }
257}
258
259impl<T: Default> Default for Node<T> {
260    /// Creates a Node with the Default content.
261    /// Converting the returned Node to a [`Tree`] is recommended.
262    fn default() -> Self {
263        Self {
264            content: T::default(),
265            parent: None,
266            children: vec![],
267            _pin: PhantomPinned,
268        }
269    }
270}
271
272impl<T: Clone> Clone for Node<T> {
273    /// Copies the [`Node`]'s [`content`](Node::content), but not its [`children`](Node::children).
274    /// The resulting cloned [`Node`] will have no **parent** or **children**.
275    ///
276    /// Converting the returned Node to a [`Tree`] is recommended.
277    ///
278    /// For a method that clones the [`Node`] *and* its subtree, see [`Node::clone_deep`].
279    fn clone(&self) -> Self {
280        Self {
281            content: self.content.clone(),
282            parent: None,
283            children: vec![],
284            _pin: PhantomPinned,
285        }
286    }
287}
288impl<T: Clone> Node<T> {
289    /// Copies the [`Node`]'s [`content`](Node::content) and its [`children`](Node::children) recursively.
290    /// The resulting cloned [`Node`] will have no **parent**.
291    ///
292    /// For a method that clones the [`Node`] but *not* its subtree, see [`Node::clone`].
293    pub fn clone_deep(&self) -> Tree<T> {
294        let mut root = Box::pin(self.clone());
295
296        unsafe { root.as_mut().get_unchecked_mut() }.children =
297            self.clone_children_deep(root.ptr());
298
299        Tree { root }
300    }
301    fn clone_children_deep(&self, parent: Parent<Self>) -> Vec<Owned<Self>> {
302        self.children
303            .iter()
304            .map(|node| {
305                let mut child = Box::pin(node.as_ref().get_ref().clone());
306                let mut_child = unsafe { child.as_mut().get_unchecked_mut() };
307                mut_child.parent = Some(parent);
308                mut_child.children = node.clone_children_deep(mut_child.ptr());
309                child
310            })
311            .collect()
312    }
313}
314
315impl<T: Debug> Node<T> {
316    /// [`Debug`] the entire subtree (`self` and its **children**).
317    #[inline]
318    pub fn debug_tree(&self) -> DebugTree<T> {
319        DebugTree { root: self }
320    }
321}
322impl<T: Debug> Debug for Node<T> {
323    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324        f.debug_struct("Node")
325            .field("content", &self.content)
326            .field(
327                "children",
328                &self
329                    .children()
330                    .iter()
331                    .map(|c| &c.content)
332                    .collect::<Box<_>>(),
333            )
334            .finish()
335    }
336}
337
338impl<T: PartialEq> PartialEq for Node<T> {
339    fn eq(&self, other: &Self) -> bool {
340        self.content == other.content
341    }
342}
343impl<T: Eq> Eq for Node<T> {}