forest_ds/
tree.rs

1use crate::{entry::Entry, error::Error, id::NodeId, node::Node};
2
3#[derive(Debug, Clone)]
4pub struct Tree<T> {
5    pub(crate) first_free: Option<usize>,
6    pub(crate) first_node: Option<usize>,
7    pub(crate) last_node: Option<usize>,
8    pub(crate) nodes: Vec<Entry<T>>,
9}
10
11impl<T> Tree<T> {
12    /// Create a new tree.
13    #[must_use]
14    pub fn new() -> Self {
15        Self::default()
16    }
17
18    /// Create a new tree with a specific parameter.
19    #[must_use]
20    pub fn with_capacity(capacity: usize) -> Self {
21        Self {
22            first_free: None,
23            first_node: None,
24            last_node: None,
25            nodes: Vec::with_capacity(capacity),
26        }
27    }
28
29    /// Add a node to the tree, without relations with the other nodes.
30    pub fn create_node(&mut self, value: T) -> NodeId {
31        let index = self.allocate_node(Node::new(value));
32
33        NodeId::new(index)
34    }
35
36    /// Remove a node.
37    ///
38    /// If there are some children nodes, they will became the first node if we are removing the
39    /// first node. Otherwise they will become orphan nodes.
40    ///
41    /// It will consume the [`NodeId`].
42    ///
43    /// # Errors
44    ///
45    /// Fails if the [`NodeId`] is invalid.
46    pub fn remove(&mut self, id: NodeId) -> Result<T, Error> {
47        let index = self.index(&id).ok_or(Error::Invalid("passed"))?;
48        let entry = self.free_node(index);
49
50        let node = entry.unwrap();
51
52        // Replace with next sibling or first child, there is no previous sibling
53        if Some(index) == self.first_node {
54            self.first_node = node.next_sibling.or(node.first_child);
55        }
56
57        // Replace with prev sibling or parent, there is no next sibling
58        if Some(index) == self.last_node {
59            self.last_node = node.prev_sibling.or(node.parent);
60        }
61
62        // Check if this is a parent first/last child
63        if let Some(parent_index) = node.parent {
64            let parent = self.nodes[parent_index].unwrap_mut();
65
66            if parent.first_child == Some(index) {
67                parent.first_child = node.next_sibling;
68            }
69
70            if parent.last_child == Some(index) {
71                parent.last_child = node.prev_sibling;
72            }
73        }
74
75        // Connect next sibling with previous sibling
76        if let Some(index) = node.next_sibling {
77            let next_sibling = self.nodes[index].unwrap_mut();
78            next_sibling.prev_sibling = node.prev_sibling;
79        }
80
81        if let Some(index) = node.prev_sibling {
82            let prev_sibling = self.nodes[index].unwrap_mut();
83            prev_sibling.next_sibling = node.next_sibling;
84        }
85
86        // Remove parent from child nodes
87        let mut child_index = node.first_child;
88        while let Some(index) = child_index {
89            let child = self.nodes[index].unwrap_mut();
90            child.parent = None;
91
92            child_index = child.next_sibling;
93        }
94
95        Ok(node.value)
96    }
97
98    #[must_use]
99    pub fn first_node_id(&self) -> Option<NodeId> {
100        self.first_node.map(NodeId::new)
101    }
102
103    #[must_use]
104    pub fn last_node_id(&self) -> Option<NodeId> {
105        self.last_node.map(NodeId::new)
106    }
107
108    /// Insert the last child for a given index.
109    pub(crate) fn insert_child_at(&mut self, index: usize, value: T) -> usize {
110        let mut node = Node::new(value);
111        let node_index = self.get_first_free();
112
113        node.parent = Some(index);
114
115        if Some(index) == self.last_node {
116            self.last_node = Some(node_index);
117        }
118
119        let parent = self.nodes[index].unwrap_mut();
120
121        let last_child = parent.last_child.replace(node_index);
122
123        match last_child {
124            Some(sibling_index) => {
125                let sibling = self.nodes[sibling_index].unwrap_mut();
126                sibling.next_sibling = Some(node_index);
127                node.prev_sibling = Some(sibling_index);
128            }
129            None => {
130                parent.first_child = Some(node_index);
131                parent.last_child = Some(node_index);
132            }
133        }
134
135        let index = self.allocate_node(node);
136        debug_assert_eq!(index, node_index);
137
138        node_index
139    }
140
141    /// Insert the next sibling for a given index.
142    pub(crate) fn insert_sibling_at(&mut self, index: usize, value: T) -> usize {
143        let node_index = self.get_first_free();
144        let mut node = Node::new(value);
145
146        node.prev_sibling = Some(index);
147
148        let sibling = self.nodes[index].unwrap_mut();
149        let next_sibling = sibling.next_sibling.replace(node_index);
150
151        node.next_sibling = next_sibling;
152        node.parent = sibling.parent;
153
154        if node.next_sibling.is_none() {
155            if let Some(parent) = node.parent {
156                self.nodes[parent].unwrap_mut().last_child = Some(node_index);
157            }
158        }
159
160        if Some(index) == self.last_node {
161            self.last_node = Some(node_index);
162        }
163
164        let index = self.allocate_node(node);
165        debug_assert_eq!(index, node_index);
166
167        node_index
168    }
169
170    /// Appends the value to the last element of the three as its child. If None creates a new root.
171    pub fn append_child(&mut self, value: T) -> NodeId {
172        let index = match self.last_node {
173            Some(tail_index) => self.insert_child_at(tail_index, value),
174            None => {
175                let index = self.allocate_node(Node::new(value));
176                self.first_node = Some(index);
177                self.last_node = Some(index);
178
179                index
180            }
181        };
182
183        NodeId::new(index)
184    }
185
186    /// Appends the value to the last element of the three as its sibling. If None creates a new
187    /// root.
188    pub fn append_sibling(&mut self, value: T) -> NodeId {
189        let index = match self.last_node {
190            Some(tail_index) => self.insert_sibling_at(tail_index, value),
191            None => {
192                let index = self.allocate_node(Node::new(value));
193                self.first_node = Some(index);
194                self.last_node = Some(index);
195
196                index
197            }
198        };
199
200        NodeId::new(index)
201    }
202
203    /// Appends a new node as child of the given one
204    ///
205    /// # Errors
206    ///
207    /// Will error if the given node id was removed.
208    pub fn append_child_to(&mut self, id: &NodeId, value: T) -> Result<NodeId, Error> {
209        let index = self.index(id).ok_or(Error::Invalid("passed"))?;
210
211        let index = self.insert_child_at(index, value);
212
213        Ok(NodeId::new(index))
214    }
215
216    /// Insert a new node after the as the sibling of the given one
217    ///
218    /// # Errors
219    ///
220    /// Will error if the given node id was removed.
221    pub fn insert_sibling_after(&mut self, id: &NodeId, value: T) -> Result<NodeId, Error> {
222        let index = self.index(id).ok_or(Error::Invalid("passed"))?;
223
224        let index = self.insert_sibling_at(index, value);
225
226        Ok(NodeId::new(index))
227    }
228}
229
230impl<T> Default for Tree<T> {
231    fn default() -> Self {
232        Self {
233            first_free: Option::default(),
234            first_node: Option::default(),
235            last_node: Option::default(),
236            nodes: Vec::default(),
237        }
238    }
239}
240
241#[cfg(test)]
242mod test {
243    use crate::{entry::Entry, node::Node};
244    use pretty_assertions::assert_eq;
245
246    use super::Tree;
247
248    #[test]
249    pub fn should_create_root_on_append_child() {
250        let mut tree: Tree<i32> = Tree::new();
251        tree.append_child(42);
252
253        assert_eq!(Some(0), tree.first_node);
254        assert_eq!(Some(0), tree.last_node);
255
256        let node = Node {
257            value: 42,
258            parent: None,
259            first_child: None,
260            last_child: None,
261            next_sibling: None,
262            prev_sibling: None,
263        };
264
265        assert_eq!(Entry::Occupied(node), tree.nodes[0]);
266    }
267
268    #[test]
269    pub fn should_append_child() {
270        let mut tree: Tree<i32> = Tree::new();
271        tree.append_child(1);
272        tree.append_child(2);
273
274        assert_eq!(Some(0), tree.first_node);
275        assert_eq!(Some(1), tree.last_node);
276
277        let first = Node {
278            value: 1,
279            parent: None,
280            first_child: Some(1),
281            last_child: Some(1),
282            next_sibling: None,
283            prev_sibling: None,
284        };
285
286        assert_eq!(Entry::Occupied(first), tree.nodes[0]);
287
288        let second = Node {
289            value: 2,
290            parent: Some(0),
291            first_child: None,
292            last_child: None,
293            next_sibling: None,
294            prev_sibling: None,
295        };
296
297        assert_eq!(Entry::Occupied(second), tree.nodes[1]);
298    }
299
300    #[test]
301    pub fn should_create_root_on_append_sibling() {
302        let mut tree: Tree<i32> = Tree::new();
303        tree.append_sibling(42);
304
305        assert_eq!(Some(0), tree.first_node);
306        assert_eq!(Some(0), tree.last_node);
307
308        let node = Node {
309            value: 42,
310            parent: None,
311            first_child: None,
312            last_child: None,
313            next_sibling: None,
314            prev_sibling: None,
315        };
316
317        assert_eq!(Entry::Occupied(node), tree.nodes[0]);
318    }
319
320    #[test]
321    pub fn should_append_sibling() {
322        let mut tree: Tree<i32> = Tree::new();
323        tree.append_sibling(1);
324        tree.append_sibling(2);
325
326        assert_eq!(Some(0), tree.first_node);
327        assert_eq!(Some(1), tree.last_node);
328
329        let first = Node {
330            value: 1,
331            parent: None,
332            first_child: None,
333            last_child: None,
334            next_sibling: Some(1),
335            prev_sibling: None,
336        };
337
338        assert_eq!(Entry::Occupied(first), tree.nodes[0]);
339
340        let second = Node {
341            value: 2,
342            parent: None,
343            first_child: None,
344            last_child: None,
345            next_sibling: None,
346            prev_sibling: Some(0),
347        };
348
349        assert_eq!(Entry::Occupied(second), tree.nodes[1]);
350    }
351
352    #[test]
353    fn should_append_child_and_siblings() {
354        let mut tree: Tree<i32> = Tree::new();
355
356        let root = tree.append_child(0);
357
358        let first = tree.append_child_to(&root, 1).unwrap();
359        tree.insert_sibling_after(&first, 2).unwrap();
360
361        let root = Node {
362            value: 0,
363            parent: None,
364            first_child: Some(1),
365            last_child: Some(2),
366            next_sibling: None,
367            prev_sibling: None,
368        };
369        assert_eq!(Entry::Occupied(root), tree.nodes[0]);
370
371        let first = Node {
372            value: 1,
373            parent: Some(0),
374            first_child: None,
375            last_child: None,
376            next_sibling: Some(2),
377            prev_sibling: None,
378        };
379        assert_eq!(Entry::Occupied(first), tree.nodes[1]);
380
381        let second = Node {
382            value: 2,
383            parent: Some(0),
384            first_child: None,
385            last_child: None,
386            next_sibling: None,
387            prev_sibling: Some(1),
388        };
389        assert_eq!(Entry::Occupied(second), tree.nodes[2]);
390    }
391
392    #[test]
393    fn should_remove() {
394        let mut tree = Tree::new();
395
396        tree.append_child(1);
397
398        let id = tree.append_child(2);
399
400        tree.append_sibling(3);
401        tree.append_child(4);
402
403        assert_eq!(Ok(2), tree.remove(id));
404
405        assert_eq!(Some(1), tree.first_free);
406        assert_eq!(Some(0), tree.first_node);
407
408        assert_eq!(Entry::Free { next_free: None }, tree.nodes[1]);
409
410        assert_eq!(None, tree.nodes[2].unwrap_ref().prev_sibling);
411
412        assert_eq!(1, *tree.get(&tree.first_node_id().unwrap()).unwrap());
413        assert_eq!(4, *tree.get(&tree.last_node_id().unwrap()).unwrap());
414    }
415
416    #[test]
417    fn should_remove_first_node() {
418        let mut tree = Tree::new();
419
420        let id = tree.append_child(1);
421
422        tree.append_child(2);
423        tree.append_sibling(3);
424        tree.append_child(4);
425
426        assert_eq!(Ok(1), tree.remove(id));
427
428        assert_eq!(Some(0), tree.first_free);
429        assert_eq!(Some(1), tree.first_node);
430
431        assert_eq!(Entry::Free { next_free: None }, tree.nodes[0]);
432
433        assert_eq!(None, tree.nodes[1].unwrap_ref().parent);
434        assert_eq!(None, tree.nodes[2].unwrap_ref().parent);
435
436        assert_eq!(2, *tree.get(&tree.first_node_id().unwrap()).unwrap());
437        assert_eq!(4, *tree.get(&tree.last_node_id().unwrap()).unwrap());
438    }
439}