1use petgraph::{
2 stable_graph::{StableGraph, EdgeIndex, NodeIndex}
3};
4use thiserror::Error;
5
6#[derive(Error, Debug)]
7pub enum TreeError {
8 #[error("node `{0}` is missing")]
9 NodeMissing(u32)
10}
11
12pub trait NodeTrait { }
13pub trait EdgeTrait { }
14pub type NodeId = NodeIndex<u32>;
15pub type EdgeId = EdgeIndex<u32>;
16pub type Node = Box<dyn NodeTrait>;
17pub type Edge = Box<dyn EdgeTrait>;
18pub type Tree = StableGraph<Node, ()>;
19
20pub fn add_node(tree: &mut Tree, node: Node) -> NodeId {
21 tree.add_node(node)
22}
23
24pub fn add_edge(tree: &mut Tree, from: NodeId, to: NodeId) -> EdgeId {
25 tree.add_edge(from, to, ())
26}
27
28pub fn add_child(tree: &mut Tree, parent: NodeId, child: Node) -> (NodeId, EdgeId) {
29 let node_id : NodeId = add_node(tree, child);
30 (node_id, add_edge(tree, node_id, parent))
31}
32
33pub fn add_parent(tree: &mut Tree, child: NodeId, parent: Node) -> (NodeId, EdgeId) {
34 let node_id : NodeId = add_node(tree, parent);
35 (node_id, add_edge(tree, child, node_id))
36}
37
38pub fn remove_node(tree: &mut Tree, node_id: NodeId) {
39 tree.remove_node(node_id);
40}
41
42pub fn remove_edge(tree: &mut Tree, edge_id: EdgeId) {
43 tree.remove_edge(edge_id);
44}
45
46#[cfg(test)]
47mod tests {
48 use crate::tree::*;
49
50 struct Node(u32);
51 impl NodeTrait for Node {}
53 #[test]
56 fn add_node_test() {
57 let mut tree = Tree::new();
58 let a = Box::new(Node(1));
59 let b = Box::new(Node(2));
60 add_node(&mut tree, a);
61 add_node(&mut tree, b);
62 }
63
64 #[test]
65 fn remove_node_test() {
66 let mut tree = Tree::new();
67 let a = Box::new(Node(1));
68 let b = Box::new(Node(2));
69 let a_id = add_node(&mut tree, a);
70 let b_id = add_node(&mut tree, b);
71 remove_node(&mut tree, a_id);
72 remove_node(&mut tree, b_id);
73 }
74
75 #[test]
76 fn parent_child_test() {
77 let mut tree = Tree::new();
78 let a = Box::new(Node(1));
79 let b = Box::new(Node(2));
80 let c = Box::new(Node(3));
81 let a_id = add_node(&mut tree, a);
82 let (_b_id, _ab_id) = add_parent(&mut tree, a_id, b);
85 let (_c_id, _ac_id) = add_child(&mut tree, a_id, c);
86 }
87}