Skip to main content

outils/tree/
generic.rs

1//!
2//! Generic, general purpose tree data structures.
3//!
4pub use self::error::TreeError;
5use slab;
6use std::ops::{Index, IndexMut};
7use crate::tree::traversal::Traversable;
8use crate::types::{Children, DefaultIndexType, IndexType, NodeIndex, Tgf, Values, ValueType};
9
10#[cfg(test)]
11mod tests;
12
13pub mod error;
14
15/// This trait defines the fundamental operations of a generic forest.
16pub trait GenericForest<V, Ix = DefaultIndexType>: Traversable<V, Ix>
17    where
18        V: ValueType,
19        Ix: IndexType,
20{
21    /// Inserts `value` into the forest as a new root node and return the assigned `NodeIndex`.
22    fn insert(&mut self, value: V) -> NodeIndex<Ix>;
23
24    /// Inserts `value` into the forest as a new node. which will be the last child of the
25    /// node indexed by `parent`. If the operation has been completed successfully, the
26    /// index of the new child is returned. Otherwise, in particular if `parent` is not a
27    /// valid node index, an error is returned.
28    fn insert_child(
29        &mut self,
30        parent: NodeIndex<Ix>,
31        value: V,
32    ) -> Result<NodeIndex<Ix>, TreeError<Ix>>;
33
34    /// Inserts `value` into the forest as a new node. which will be a child of the
35    /// node indexed by `parent` at the position specified by `pos`. If `pos` is greater than or
36    /// equal to the number of children of `parent`, the new child will be the new last child.
37    /// If the operation has been completed successfully, the index of the new child is returned.
38    /// Otherwise, if `parent` is not a valid node index, an error is returned.
39    fn insert_child_at(
40        &mut self,
41        parent: NodeIndex<Ix>,
42        pos: usize,
43        value: V,
44    ) -> Result<NodeIndex<Ix>, TreeError<Ix>>;
45
46    /// Removes the tree node indexed by `node`, returning its content in case of a valid index.
47    /// If the removed node has children, they will become children of the parent of the removed node,
48    /// replacing the removed node. If the removed node has no parent, its children will become roots.
49    fn remove(&mut self, node: NodeIndex<Ix>) -> Result<V, TreeError<Ix>>;
50
51    /// Removes the tree node indexed by `node` and its subtree, returning the contents of the
52    /// removed nodes in case of a valid index. The returned values will be collected in pre-order.
53    fn remove_subtree(&mut self, node: NodeIndex<Ix>)
54                      -> Result<Vec<(NodeIndex, V)>, TreeError<Ix>>;
55
56    /// Adds the root node `child` as the new last child of the node indexed by `parent`. If the operation has
57    /// been completed successfully, `Ok(())` is returned. If the forest has not been changed, an error
58    /// is returned. This will be the case if:
59    ///
60    /// - the node indexed by `child` is not a tree root, i.e. has a parent.
61    /// - the node indexed by `parent` is a node in the tree rooted in `child`.
62    /// - either `parent` or `child` is not a valid node index.
63    fn set_as_child(
64        &mut self,
65        parent: NodeIndex<Ix>,
66        child: NodeIndex<Ix>,
67    ) -> Result<(), TreeError<Ix>>;
68
69    /// Adds the root node `child` as a child of the node indexed by `parent` at the position specified
70    /// by `pos`. If `pos` is greater than or equal to the number of children of `parent`, the new
71    /// child will be the new last child. If the operation has been completed successfully, `Ok(())`
72    /// is returned. If the forest has not been changed, an error is returned. This will be the case if:
73    ///
74    /// - the node indexed by `child` is not a tree root, i.e. has a parent.
75    /// - the node indexed by `parent` is a node in the tree rooted in `child`.
76    /// - either `parent` or `child` is not a valid node index.
77    fn set_as_child_at(
78        &mut self,
79        parent: NodeIndex<Ix>,
80        child: NodeIndex<Ix>,
81        pos: usize,
82    ) -> Result<(), TreeError<Ix>>;
83
84    /// Removes the node indexed by `node` as a child of its parent, thus making it a new root
85    /// node of the forest. If the operation has been completed successfully, `Ok(())` is returned.
86    /// If `node` is not a valid not index, an error is returned.
87    fn remove_as_child(&mut self, node: NodeIndex<Ix>) -> Result<(), TreeError<Ix>>;
88}
89
90#[derive(Debug, Clone)]
91struct Node<V>
92    where
93        V: ValueType,
94{
95    value: V,
96    child_count: usize,
97    context: NodeContext,
98}
99
100impl<V> Node<V>
101    where
102        V: ValueType,
103{
104    fn new(value: V) -> Self {
105        Node {
106            value,
107            child_count: 0,
108            context: NodeContext::new(),
109        }
110    }
111}
112
113#[derive(Copy, Clone, Debug)]
114struct NodeContext {
115    parent: Option<NodeIndex>,
116    first_child: Option<NodeIndex>,
117    last_child: Option<NodeIndex>,
118    prev_sibling: Option<NodeIndex>,
119    next_sibling: Option<NodeIndex>,
120}
121
122impl NodeContext {
123    fn new() -> Self {
124        NodeContext {
125            parent: None,
126            first_child: None,
127            last_child: None,
128            prev_sibling: None,
129            next_sibling: None,
130        }
131    }
132}
133
134struct ChildIterator<'slf, V>
135    where
136        V: ValueType,
137{
138    forest: &'slf Forest<V>,
139    current: Option<NodeIndex>,
140}
141
142impl<'slf, V> ChildIterator<'slf, V>
143    where
144        V: 'slf + ValueType,
145{
146    fn new(forest: &'slf Forest<V>, node: NodeIndex) -> Self {
147        ChildIterator {
148            forest,
149            current: forest
150                .arena
151                .get(node.index())
152                .and_then(|n| n.context.first_child),
153        }
154    }
155}
156
157impl<'slf, V> Iterator for ChildIterator<'slf, V>
158    where
159        V: 'slf + ValueType,
160{
161    type Item = NodeIndex;
162    fn next(&mut self) -> Option<NodeIndex> {
163        let ret = self.current;
164        match ret {
165            Some(n) => {
166                self.current = self.forest.arena[n.index()].context.next_sibling;
167                ret
168            }
169            None => None,
170        }
171    }
172}
173
174/// `Forest<V>` is a general purpose data structure for holding a forest of trees. Its tree nodes
175/// are held in a [memory arena][1] and are addressed through their associated `NodeIndex`.
176///
177/// `Forest` is parameterized over:
178/// - Associated values of type `V`, where `V` must implement the trait [`ValueType`][2]
179///
180/// The tree nodes of the forest are organized in a first child/next-sibling representation,
181/// augmented by last child/previous sibling links. In other words, the children of tree node are
182/// maintained in doubly linked list, where the head and tail of the list are the first and last
183/// child values of the children's parent node.
184///
185/// Therefore, no allocations and re-allocations are necessary when adding children to nodes.
186/// Re-allocation will only take place if the underlying memory arena has reached its capacity.
187///
188/// However, care must be taken when accessing a child node by its position, that is, by using
189/// the method [`child(node, pos)`][3] of the [`Traversal`][4] trait, because to access a child by
190/// its position in the list, the list has to be iterated from the beginning. Using access by
191/// position is therefore not very efficient. This caveat also applies to the generic traversal
192/// iterators provided by the [`traversal`][5] module, which are build on access by position.
193///
194/// In order to iterate over the children of node, the trait [`Children`][6] is available.
195///
196/// To illustrate the above explations see the following example:
197///
198/// ```
199/// use outils::prelude::*;
200/// use outils::tree::traversal::GeneralDfsValues;
201/// let mut forest = Forest::new(10);
202///
203/// // Create a root with 9 child nodes.
204/// let root = forest.insert(9);
205/// for i in (0..9) {
206///     forest.insert_child(root, i);
207/// }
208///
209/// // Inefficient iteration:
210/// for pos in (0..9) {
211///     let index = forest.child(root, pos).expect("Should not fail here!"); // Inefficient!
212///     let value = forest.value(index).expect("Should not fail here!");
213///     assert_eq!(*value, pos);
214/// }
215///
216/// // Also inefficient is using the provided, generic traversals:
217/// let seq: Vec<&usize> = GeneralDfsValues::new(&forest, root).collect(); // Will use child()!
218/// assert_eq!(seq, vec![&9, &0, &1, &2, &3, &4, &5, &6, &7, &8]);
219///
220/// // Efficient iteration:
221/// let mut pos = 0;
222/// for child in forest.children(root) {
223///     let value = forest.value(child).expect("Should not fail here!");
224///     assert_eq!(*value, pos);
225///     pos += 1;
226/// }
227/// ```
228///
229/// [1]: https://en.wikipedia.org/wiki/Region-based_memory_management
230/// [2]: ../../types/trait.ValueType.html
231/// [3]: ../traversal/trait.Traversable.html#tymethod.child
232/// [4]: ../traversal/trait.Traversable.html
233/// [5]: ../traversal/index.html
234/// [6]: ../../types/trait.Children.html
235#[derive(Clone, Debug)]
236pub struct Forest<V>
237    where
238        V: ValueType,
239{
240    arena: slab::Slab<Node<V>>,
241    roots: Vec<NodeIndex>,
242}
243
244impl<V> Forest<V>
245    where
246        V: ValueType,
247{
248    /// Construct a new empty `Forest` with an initial capacity of `size`.
249    pub fn new(size: usize) -> Self {
250        Forest {
251            arena: slab::Slab::with_capacity(size),
252            roots: Vec::new(),
253        }
254    }
255
256    /// Returns the index of the first child node of the tree node indexed by `node`. If the node
257    /// has no children or `node` is not a valid index, `None` is returned.
258    ///
259    /// ```
260    /// use outils::prelude::*;
261    ///
262    /// let mut tree = Forest::new(10);
263    /// let root = tree.insert(1);
264    /// let first_child = tree.insert_child(root, 2).expect("Should not fail here");
265    /// let second_child = tree.insert_child(root, 3).expect("Should not fail here");
266    ///
267    /// assert_eq!(tree.first_child(root), Some(first_child));
268    /// ```
269    pub fn first_child(&self, parent: NodeIndex) -> Option<NodeIndex> {
270        self.arena
271            .get(parent.index())
272            .and_then(|p| p.context.first_child)
273    }
274
275    /// Returns the index of the last child node of the tree node indexed by `node`. If the node
276    /// has no children or `node` is not a valid index, `None` is returned.
277    ///
278    /// ```
279    /// use outils::prelude::*;
280    ///
281    /// let mut tree = Forest::new(10);
282    /// let root = tree.insert(1);
283    /// let first_child = tree.insert_child(root, 2).expect("Should not fail here");
284    /// let second_child = tree.insert_child(root, 3).expect("Should not fail here");
285    ///
286    /// assert_eq!(tree.last_child(root), Some(second_child));
287    /// ```
288    pub fn last_child(&self, parent: NodeIndex) -> Option<NodeIndex> {
289        self.arena
290            .get(parent.index())
291            .and_then(|p| p.context.last_child)
292    }
293
294    /// Returns the index of the previous sibling node of the tree node indexed by `node`. If the
295    /// node is the first child of its parent or `node` is not a valid index, `None` is returned.
296    ///
297    /// ```
298    /// use outils::prelude::*;
299    ///
300    /// let mut tree = Forest::new(10);
301    /// let root = tree.insert(1);
302    /// let first_child = tree.insert_child(root, 2).expect("Should not fail here");
303    /// let second_child = tree.insert_child(root, 3).expect("Should not fail here");
304    ///
305    /// assert_eq!(tree.prev_sibling(second_child), Some(first_child));
306    /// ```
307    pub fn prev_sibling(&self, node: NodeIndex) -> Option<NodeIndex> {
308        self.arena
309            .get(node.index())
310            .and_then(|n| n.context.prev_sibling)
311    }
312
313    /// Returns the index of the next sibling node of the tree node indexed by `node`. If the
314    /// node is the last child of its parent or `node` is not a valid index, `None` is returned.
315    ///
316    /// ```
317    /// use outils::prelude::*;
318    ///
319    /// let mut tree = Forest::new(10);
320    /// let root = tree.insert(1);
321    /// let first_child = tree.insert_child(root, 2).expect("Should not fail here");
322    /// let second_child = tree.insert_child(root, 3).expect("Should not fail here");
323    ///
324    /// assert_eq!(tree.next_sibling(first_child), Some(second_child));
325    /// ```
326    pub fn next_sibling(&self, node: NodeIndex) -> Option<NodeIndex> {
327        self.arena
328            .get(node.index())
329            .and_then(|n| n.context.next_sibling)
330    }
331
332    /// Returns the list of root node indices of this forest. The values are not returned in any
333    /// particular order.
334    ///
335    /// ```
336    /// use outils::prelude::*;
337    ///
338    /// let mut tree = Forest::new(10);
339    /// let first_root = tree.insert(1);
340    /// let second_root = tree.insert(2);
341    ///
342    /// let roots = tree.roots();
343    /// assert!(roots.contains(&first_root));
344    /// assert!(roots.contains(&second_root));
345    /// ```
346    pub fn roots(&self) -> &Vec<NodeIndex> {
347        &self.roots
348    }
349}
350
351impl<'slf, V> Children<'slf> for Forest<V>
352    where
353        V: 'slf + ValueType,
354{
355    fn children(&'slf self, node: NodeIndex) -> Box<dyn Iterator<Item=NodeIndex> + 'slf> {
356        Box::new(ChildIterator::new(self, node))
357    }
358}
359
360impl<V> Index<NodeIndex> for Forest<V>
361    where
362        V: ValueType,
363{
364    type Output = V;
365    fn index(&self, index: NodeIndex) -> &V {
366        &self.arena[index.index()].value
367    }
368}
369
370impl<V> IndexMut<NodeIndex> for Forest<V>
371    where
372        V: ValueType,
373{
374    fn index_mut(&mut self, index: NodeIndex) -> &mut V {
375        &mut self.arena[index.index()].value
376    }
377}
378
379impl<V> Traversable<V> for Forest<V>
380    where
381        V: ValueType,
382{
383    /// Returns the index of the root node of the tree containing the tree node indexed by `node`.
384    fn root(&self, node: NodeIndex) -> Option<NodeIndex> {
385        if let Some(_n) = self.arena.get(node.index()) {
386            let mut child = node;
387            while let Some(parent) = self.arena[child.index()].context.parent {
388                child = parent;
389            }
390            return Some(child);
391        }
392        None
393    }
394
395    /// Immutably access the value stored in the tree node indexed by `node`.
396    fn value(&self, node: NodeIndex) -> Option<&V> {
397        self.arena.get(node.index()).map(|n| &n.value)
398    }
399
400    /// Mutably access the value stored in the tree node indexed by `node`.
401    fn value_mut(&mut self, node: NodeIndex) -> Option<&mut V> {
402        self.arena.get_mut(node.index()).map(|n| &mut n.value)
403    }
404
405    /// Returns the index of parent node tree node indexed by `node`.
406    fn parent(&self, node: NodeIndex) -> Option<NodeIndex> {
407        self.arena.get(node.index()).and_then(|n| n.context.parent)
408    }
409
410    /// Returns the index of the child node at position `pos` of  the tree node indexed by `node`.
411    fn child(&self, node: NodeIndex, pos: usize) -> Option<NodeIndex> {
412        ChildIterator::new(self, node).nth(pos)
413    }
414
415    /// Returns the number of child nodes of the tree node indexed by `node`.
416    fn child_count(&self, node: NodeIndex) -> usize {
417        self.arena.get(node.index()).map_or(0, |n| n.child_count)
418    }
419
420    /// Returns the total number of tree nodes of the tree `self`.
421    fn node_count(&self) -> usize {
422        self.arena.len()
423    }
424}
425
426impl<'slf, V> Values<'slf, V> for Forest<V>
427    where
428        V: 'slf + ValueType,
429{
430    /// Returns a boxed iterator over the stored values and their corresponding
431    /// tree node indices held by `self`.
432    fn values(&'slf self) -> Box<dyn Iterator<Item=(NodeIndex, &'slf V)> + 'slf> {
433        Box::new(self.arena.iter().map(|(i, v)| (NodeIndex(i), &v.value)))
434    }
435}
436
437impl<V> GenericForest<V> for Forest<V>
438    where
439        V: ValueType,
440{
441    /// Inserts `value` into the forest as a new root node and return the assigned `NodeIndex`.
442    fn insert(&mut self, value: V) -> NodeIndex {
443        let node = NodeIndex(self.arena.insert(Node::new(value)));
444        self.roots.push(node);
445        node
446    }
447
448    /// Inserts `value` into the forest as a new node. which will be the last child of the
449    /// node indexed by `parent`. If the operation has been completed successfully, the
450    /// index of the new child is returned. Otherwise, in particular if `parent` is not a
451    /// valid node index, an error is returned.
452    fn insert_child(&mut self, parent: NodeIndex, value: V) -> Result<NodeIndex, TreeError> {
453        if !self.arena.contains(parent.index()) {
454            return Err(TreeError::invalid_node_index("insert_child()", parent));
455        }
456        let child = NodeIndex(self.arena.insert(Node::new(value)));
457
458        match self.arena[parent.index()].context.last_child {
459            Some(last) => {
460                self.arena[last.index()].context.next_sibling = Some(child);
461                self.arena[parent.index()].context.last_child = Some(child);
462                self.arena[child.index()].context.prev_sibling = Some(last);
463            }
464            None => {
465                self.arena[parent.index()].context.first_child = Some(child);
466                self.arena[parent.index()].context.last_child = Some(child);
467            }
468        }
469        self.arena[child.index()].context.parent = Some(parent);
470        self.arena[parent.index()].child_count += 1;
471        Ok(child)
472    }
473
474    /// Inserts `value` into the forest as a new node. which will be a child of the
475    /// node indexed by `parent` at the position specified by `pos`. If `pos` is greater than or
476    /// equal to the number of children of `parent`, the new child will be the new last child.
477    /// If the operation has been completed successfully, the index of the new child is returned.
478    /// Otherwise, if `parent` is not a valid node index, an error is returned.
479    fn insert_child_at(
480        &mut self,
481        parent: NodeIndex,
482        pos: usize,
483        value: V,
484    ) -> Result<NodeIndex, TreeError> {
485        if !self.arena.contains(parent.index()) {
486            return Err(TreeError::invalid_node_index("insert_child_at()", parent));
487        }
488        let child = NodeIndex(self.arena.insert(Node::new(value)));
489
490        let mut prev = None;
491        let mut next = self.arena[parent.index()].context.first_child;
492        let mut i = 0;
493
494        while i < pos {
495            match next {
496                Some(n) => {
497                    prev = next;
498                    next = self.arena[n.index()].context.next_sibling;
499                    i += 1;
500                }
501                None => {
502                    break;
503                }
504            }
505        }
506        match (prev, next) {
507            (None, Some(n)) => {
508                self.arena[n.index()].context.prev_sibling = Some(child);
509                self.arena[parent.index()].context.first_child = Some(child);
510            }
511            (Some(p), Some(n)) => {
512                self.arena[n.index()].context.prev_sibling = Some(child);
513                self.arena[p.index()].context.next_sibling = Some(child);
514            }
515            (Some(p), None) => {
516                self.arena[p.index()].context.next_sibling = Some(child);
517                self.arena[parent.index()].context.last_child = Some(child);
518            }
519            (None, None) => {
520                self.arena[parent.index()].context.first_child = Some(child);
521                self.arena[parent.index()].context.last_child = Some(child);
522            }
523        }
524        self.arena[child.index()].context.parent = Some(parent);
525        self.arena[child.index()].context.prev_sibling = prev;
526        self.arena[child.index()].context.next_sibling = next;
527        self.arena[parent.index()].child_count += 1;
528        Ok(child)
529    }
530
531    /// Removes the tree node indexed by `node`, returning its content in case of a valid index.
532    /// If the removed node has children, they will become children of the parent of the removed node,
533    /// replacing the removed node. If the removed node has no parent, its children will become roots.
534    fn remove(&mut self, node: NodeIndex) -> Result<V, TreeError> {
535        if !self.arena.contains(node.index()) {
536            return Err(TreeError::invalid_node_index("remove()", node));
537        }
538
539        let context = self.arena[node.index()].context;
540        match context.parent {
541            Some(parent) => {
542                match (
543                    context.first_child,
544                    context.last_child,
545                    context.prev_sibling,
546                    context.next_sibling,
547                ) {
548                    (Some(first), Some(last), Some(prev), Some(next)) => {
549                        self.arena[prev.index()].context.next_sibling = Some(first);
550                        self.arena[next.index()].context.prev_sibling = Some(last);
551                        self.arena[first.index()].context.prev_sibling = Some(prev);
552                        self.arena[last.index()].context.next_sibling = Some(next);
553                    }
554                    (Some(first), Some(last), Some(prev), None) => {
555                        self.arena[parent.index()].context.last_child = Some(last);
556                        self.arena[first.index()].context.prev_sibling = Some(prev);
557                        self.arena[prev.index()].context.next_sibling = Some(first);
558                    }
559                    (Some(first), Some(last), None, Some(next)) => {
560                        self.arena[parent.index()].context.first_child = Some(first);
561                        self.arena[last.index()].context.next_sibling = Some(next);
562                        self.arena[next.index()].context.prev_sibling = Some(last);
563                    }
564                    (Some(first), Some(last), None, None) => {
565                        self.arena[parent.index()].context.first_child = Some(first);
566                        self.arena[parent.index()].context.last_child = Some(last);
567                    }
568                    (None, None, Some(prev), Some(next)) => {
569                        self.arena[prev.index()].context.next_sibling = Some(next);
570                        self.arena[next.index()].context.prev_sibling = Some(prev);
571                    }
572
573                    (None, None, Some(prev), None) => {
574                        self.arena[parent.index()].context.last_child = Some(prev);
575                        self.arena[prev.index()].context.next_sibling = None;
576                    }
577
578                    (None, None, None, Some(next)) => {
579                        self.arena[parent.index()].context.first_child = Some(next);
580                        self.arena[next.index()].context.prev_sibling = None;
581                    }
582
583                    (None, None, None, None) => {
584                        self.arena[parent.index()].context.first_child = None;
585                        self.arena[parent.index()].context.last_child = None;
586                    }
587                    _ => panic!("remove(): first and last child indices are incorrect"),
588                }
589                let mut child = self.arena[node.index()].context.first_child;
590                while let Some(c) = child {
591                    child = self.arena[c.index()].context.next_sibling;
592                    self.arena[c.index()].context.parent = Some(parent);
593                }
594                self.arena[parent.index()].child_count -= 1;
595                self.arena[parent.index()].child_count += self.arena[node.index()].child_count;
596            }
597            None => {
598                self.roots.retain(|&r| r != node);
599                let mut child = self.arena[node.index()].context.first_child;
600                while let Some(c) = child {
601                    child = self.arena[c.index()].context.next_sibling;
602                    self.arena[c.index()].context.parent = None;
603                    self.arena[c.index()].context.prev_sibling = None;
604                    self.arena[c.index()].context.next_sibling = None;
605                    self.roots.push(c);
606                }
607            }
608        }
609        Ok(self.arena.remove(node.index()).value)
610    }
611
612    /// Removes the tree node indexed by `node` and its subtree, returning the contents of the
613    /// removed nodes in case of a valid index. The returned values will be collected in pre-order.
614    fn remove_subtree(&mut self, node: NodeIndex) -> Result<Vec<(NodeIndex, V)>, TreeError> {
615        if self.remove_as_child(node).is_err() {
616            return Err(TreeError::invalid_node_index("remove_subtree()", node));
617        }
618
619        let mut stack = Vec::with_capacity(self.arena[node.index()].child_count + 1);
620        let mut ret = Vec::with_capacity(stack.capacity());
621        stack.push(node);
622        while let Some(parent) = stack.pop() {
623            let mut child = self.arena[parent.index()].context.last_child;
624            while let Some(c) = child {
625                stack.push(c);
626                child = self.arena[c.index()].context.prev_sibling;
627            }
628            ret.push((parent, self.arena.remove(parent.index()).value));
629        }
630        self.roots.retain(|&r| r != node);
631        Ok(ret)
632    }
633
634    /// Adds the root node `child` as the new last child of the node indexed by `parent`. If the operation has
635    /// been completed successfully, `Ok(())` is returned. If the forest has not been changed, an error
636    /// is returned. This will be the case if:
637    ///
638    /// - the node indexed by `child` is not a tree root, i.e. has a parent.
639    /// - the node indexed by `parent` is a node in the tree rooted in `child`.
640    /// - either `parent` or `child` is not a valid node index.
641    fn set_as_child(&mut self, parent: NodeIndex, child: NodeIndex) -> Result<(), TreeError> {
642        if !self.arena.contains(parent.index()) {
643            return Err(TreeError::invalid_node_index("set_as_child()", parent));
644        }
645        if !self.arena.contains(child.index()) {
646            return Err(TreeError::invalid_node_index("set_as_child()", child));
647        }
648        if self.arena[child.index()].context.parent.is_some() {
649            return Err(TreeError::expected_root_node("set_as_child()", child));
650        }
651        if self.root(parent) == Some(child) {
652            return Err(TreeError::expected_non_ancestor_node(
653                "set_as_child()",
654                parent,
655                child,
656            ));
657        }
658
659        match self.arena[parent.index()].context.last_child {
660            Some(last) => {
661                self.arena[last.index()].context.next_sibling = Some(child);
662                self.arena[child.index()].context.prev_sibling = Some(last);
663                self.arena[parent.index()].context.last_child = Some(child);
664            }
665            None => {
666                self.arena[parent.index()].context.first_child = Some(child);
667                self.arena[parent.index()].context.last_child = Some(child);
668            }
669        }
670        self.arena[child.index()].context.parent = Some(parent);
671        self.arena[parent.index()].child_count += 1;
672        self.roots.retain(|&r| r != child);
673        Ok(())
674    }
675
676    /// Adds the root node `child` as a child of the node indexed by `parent` at the position specified
677    /// by `pos`. If `pos` is greater than or equal to the number of children of `parent`, the new
678    /// child will be the new last child. If the operation has been completed successfully, `Ok(())`
679    /// is returned. If the forest has not been changed, an error is returned. This will be the case if:
680    ///
681    /// - the node indexed by `child` is not a tree root, i.e. has a parent.
682    /// - the node indexed by `parent` is a node in the tree rooted in `child`.
683    /// - either `parent` or `child` is not a valid node index.
684    fn set_as_child_at(
685        &mut self,
686        parent: NodeIndex,
687        child: NodeIndex,
688        pos: usize,
689    ) -> Result<(), TreeError> {
690        if !self.arena.contains(parent.index()) {
691            return Err(TreeError::invalid_node_index("set_as_child_at()", parent));
692        }
693        if !self.arena.contains(child.index()) {
694            return Err(TreeError::invalid_node_index("set_as_child_at()", child));
695        }
696        if self.arena[child.index()].context.parent.is_some() {
697            return Err(TreeError::expected_root_node("set_as_child_at()", child));
698        }
699        if self.root(parent) == Some(child) {
700            return Err(TreeError::expected_non_ancestor_node(
701                "set_as_child_at()",
702                parent,
703                child,
704            ));
705        }
706
707        let mut prev = None;
708        let mut next = self.arena[parent.index()].context.first_child;
709        let mut i = 0;
710
711        while i < pos {
712            match next {
713                Some(n) => {
714                    prev = next;
715                    next = self.arena[n.index()].context.next_sibling;
716                    i += 1;
717                }
718                None => {
719                    break;
720                }
721            }
722        }
723        match (prev, next) {
724            (None, Some(n)) => {
725                self.arena[n.index()].context.prev_sibling = Some(child);
726                self.arena[parent.index()].context.first_child = Some(child);
727            }
728            (Some(p), Some(n)) => {
729                self.arena[n.index()].context.prev_sibling = Some(child);
730                self.arena[p.index()].context.next_sibling = Some(child);
731            }
732            (Some(p), None) => {
733                self.arena[p.index()].context.next_sibling = Some(child);
734                self.arena[parent.index()].context.last_child = Some(child);
735            }
736            (None, None) => {
737                self.arena[parent.index()].context.first_child = Some(child);
738                self.arena[parent.index()].context.last_child = Some(child);
739            }
740        }
741        self.arena[child.index()].context.parent = Some(parent);
742        self.arena[child.index()].context.prev_sibling = prev;
743        self.arena[child.index()].context.next_sibling = next;
744        self.arena[parent.index()].child_count += 1;
745        self.roots.retain(|&r| r != child);
746        Ok(())
747    }
748
749    /// Removes the node indexed by `node` as a child of its parent, thus making it a new root
750    /// node of the forest. If the operation has been completed successfully, `Ok(())` is returned.
751    /// If `node` is not a valid not index, an error is returned.
752    fn remove_as_child(&mut self, node: NodeIndex) -> Result<(), TreeError> {
753        if !self.arena.contains(node.index()) {
754            return Err(TreeError::invalid_node_index("remove_as_child()", node));
755        }
756        let context = self.arena[node.index()].context;
757
758        if let Some(parent) = context.parent {
759            match (context.prev_sibling, context.next_sibling) {
760                (Some(prev), Some(next)) => {
761                    self.arena[prev.index()].context.next_sibling = Some(next);
762                    self.arena[next.index()].context.prev_sibling = Some(prev);
763                }
764                (Some(prev), None) => {
765                    self.arena[prev.index()].context.next_sibling = None;
766                    self.arena[parent.index()].context.last_child = Some(prev);
767                }
768                (None, Some(next)) => {
769                    self.arena[next.index()].context.prev_sibling = None;
770                    self.arena[parent.index()].context.first_child = Some(next);
771                }
772                (None, None) => {
773                    self.arena[parent.index()].context.first_child = None;
774                    self.arena[parent.index()].context.last_child = None;
775                }
776            }
777            self.arena[parent.index()].child_count -= 1;
778            self.roots.push(node);
779        }
780        self.arena[node.index()].context = NodeContext {
781            parent: None,
782            first_child: context.first_child,
783            last_child: context.last_child,
784            prev_sibling: None,
785            next_sibling: None,
786        };
787        Ok(())
788    }
789}
790
791impl<V> Tgf for Forest<V>
792    where
793        V: ValueType,
794{
795    fn to_tgf(&self) -> String {
796        let mut nodes = String::from("");
797        let mut edges = String::from("");
798        let iter = self.arena.iter();
799        for (index, node) in iter {
800            nodes.push_str(format!("{}", index).as_str());
801            nodes.push_str(" [K = ");
802            nodes.push_str(format!("{}", index).as_str());
803            nodes.push_str(", V = ");
804            nodes.push_str(format!("{:?}", node.value).as_str());
805            nodes.push_str("]\n");
806
807            for child in self.children(NodeIndex(index)).enumerate() {
808                edges.push_str(format!("{}", index).as_str());
809                edges.push_str(" ");
810                edges.push_str(format!("{}", child.1.index()).as_str());
811                edges.push_str(" ");
812                edges.push_str(format!("{}", child.0).as_str());
813                edges.push_str("\n");
814            }
815        }
816        nodes.push_str("#\n");
817        nodes.push_str(edges.as_str());
818        nodes
819    }
820}