smalltree/
lib.rs

1#![no_std]
2use smallgraph::*;
3use smallvec::*;
4
5pub struct SmallTree<T> {
6    pub graph: SmallGraph<T>,
7    pub root: NodeHandle,
8}
9
10impl<T> SmallTree<T> {
11    pub fn new(root: T) -> SmallTree<T> {
12        let mut g = SmallGraph::<T>::new();
13        let root = g.insert(root);
14        SmallTree {
15            graph: g,
16            root: root,
17        }
18    }
19
20    pub fn attach(&mut self, parent: NodeHandle, child: T) -> NodeHandle {
21        let n = self.graph.insert(child);
22        self.graph.connect_to(parent, n);
23        n
24    }
25
26    pub fn children(&self, parent: NodeHandle) -> SmallVec<[NodeHandle;8]>{
27        self.graph.neighbors(parent)
28    }
29
30    pub fn remove(&mut self, node: NodeHandle) -> Option<T> {
31        if node == self.root {
32            panic!("cannot remove root node of tree");
33        }
34        for c in self.children(node) {
35            self.remove(c);
36        }
37        self.graph.remove(node)
38    }
39
40    pub fn get(&self, node: NodeHandle) -> Option<&T> {
41        self.graph.get(node)
42    }
43
44    pub fn get_mut(&mut self, node: NodeHandle) -> Option<&mut T> {
45        self.graph.get_mut(node)
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    // Note this useful idiom: importing names from outer (for mod tests) scope.
52    use super::*;
53
54    #[derive(Debug,PartialEq)]
55    struct Foo{
56        v:u8
57    }
58
59    #[test]
60    fn test_basic_0() {
61        let mut g = SmallTree::<Foo>::new(Foo{v:44});
62        let c1 = g.attach(g.root,Foo{v:55});
63        let c2 = g.attach(g.root,Foo{v:66});
64        assert_eq!(44,g.get(g.root).unwrap().v);
65        assert_eq!(55,g.get(c1).unwrap().v);
66        assert_eq!(66,g.get(c2).unwrap().v);
67        assert_eq!(2,g.children(g.root).len());
68        assert_eq!(55,g.get(g.children(g.root)[0]).unwrap().v);
69        assert_eq!(66,g.get(g.children(g.root)[1]).unwrap().v);
70        g.get_mut(c2).unwrap().v = 77;
71        assert_eq!(77,g.get(g.children(g.root)[1]).unwrap().v);
72    }
73
74    #[test]
75    fn test_basic_1() {
76        let mut g = SmallTree::<Foo>::new(Foo{v:44});
77        let c1 = g.attach(g.root,Foo{v:55});
78        g.attach(c1,Foo{v:66});
79        assert_eq!(3,g.graph.node_count());
80        g.remove(c1);
81        assert_eq!(1,g.graph.node_count());
82    }
83}