solana_data_structs/
flat_graph.rs

1use borsh::{BorshDeserialize, BorshSerialize};
2use rkyv::{Archive, Deserialize, Serialize};
3
4use crate::{graph_node::GraphNode, GraphEdge};
5
6#[derive(Debug, Archive, Deserialize, Serialize, BorshSerialize, BorshDeserialize)]
7pub struct FlatGraph<D, E> {
8    pub nodes: Vec<GraphNode<D, E>>,
9}
10
11impl<D, E> FlatGraph<D, E>
12where
13    D: Clone,
14    E: Clone,
15{
16    pub fn new(root_data: &D) -> Self {
17        Self {
18            nodes: vec![GraphNode::new(root_data.clone())],
19        }
20    }
21
22    pub fn append(&mut self, prev: usize, edge_data: &E, node_data: &D) {
23        let node = GraphNode::new(node_data.clone());
24        self.nodes.push(node);
25        let index = self.nodes.len() - 1;
26        self.nodes[prev]
27            .edges
28            .push(GraphEdge::new(edge_data.clone(), index));
29    }
30}
31
32#[cfg(test)]
33mod flat_graph_tests {
34    use super::*;
35
36    #[test]
37    fn create_root() {
38        let root_data = "Hello, world!";
39        let graph: FlatGraph<&str, &str> = FlatGraph::new(&root_data);
40        assert_eq!(graph.nodes.len(), 1);
41        assert_eq!(graph.nodes[0].data, root_data);
42        println!("{:?}", graph);
43    }
44
45    #[test]
46    fn append_child() {
47        let root_data = "Hello, world!";
48        let mut graph: FlatGraph<&str, &str> = FlatGraph::new(&root_data);
49        let child_data = "Hello, child!";
50        graph.append(0, &"to child", &child_data);
51        assert_eq!(graph.nodes.len(), 2);
52        assert_eq!(graph.nodes[0].edges.len(), 1);
53        assert_eq!(graph.nodes[0].edges[0].data, "to child");
54        assert_eq!(graph.nodes[0].edges[0].node, 1);
55        assert_eq!(graph.nodes[1].data, child_data);
56
57        let child_data = "Hello, other child!";
58        graph.append(0, &"to other child", &child_data);
59        assert_eq!(graph.nodes.len(), 3);
60        assert_eq!(graph.nodes[0].edges.len(), 2);
61        assert_eq!(graph.nodes[0].edges[1].data, "to other child");
62        assert_eq!(graph.nodes[0].edges[1].node, 2);
63        assert_eq!(graph.nodes[2].data, child_data);
64
65        println!("{:?}", graph);
66    }
67}