1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use std::collections::BTreeMap;
use std::collections::btree_map::Values;

/// Holds the nodes of the graph
#[derive(Debug, Clone)]
pub struct DirectedLabelGraph<D>
{
    nodes: BTreeMap<String, LabelNode<D>>,
}

impl<D> DirectedLabelGraph<D> {
    pub fn new() -> Self {
        DirectedLabelGraph {
            nodes: BTreeMap::new()
        }
    }

    fn get_node(&self, node_label: &str) -> Option<&LabelNode<D>> {
        self.nodes.get(node_label)
    }

    fn get_mut_node(&mut self, node_label: &str) -> Option<&mut LabelNode<D>> {
        self.nodes.get_mut(node_label)
    }

    pub fn iter_nodes(&self) -> Values<String, LabelNode<D>> {
        self.nodes.values()
    }

    pub fn node_exists(&self, node_label: &str) -> bool {
        self.nodes.contains_key(node_label)
    }

    pub fn add_node(&mut self, node_label: &str, node: LabelNode<D>) {
        self.nodes.insert(node_label.to_string(), node);
    }

    pub fn get_node_data(&self, node_label: &str) -> Option<&D> {
        self.get_node(node_label).map(|n| &n.data)
    }

    pub fn get_mut_node_data(&mut self, node_label: &str) -> Option<&mut D> {
        self.get_mut_node(node_label).map(|n| &mut n.data)
    }

    pub fn link_nodes(&mut self, from_node_label: &str, to_node_label: &str, weight: i64) {
        let mut from_exists = false;

        self.get_mut_node(from_node_label).map(|node| {
            from_exists = true;

            // have to do it this way, don't want to use nightly NLL feature.
            let updated = match node.connections.iter_mut().find(|edge| {
                edge.node_label == to_node_label.to_string()
                    && edge.direction == ConnectionDirection::To
            }) {
                Some(edge) => {
                    edge.weight = weight;
                    true
                }
                None => false,
            };

            if !updated {
                // create a new edge and push it
                node.connections.push(GraphEdge::new(
                    to_node_label.to_string(),
                    ConnectionDirection::To,
                    weight,
                ))
            }
        });

        // if from doesn't exist, return and don't modify to_node
        if !from_exists { return; }

        self.get_mut_node(to_node_label).map(|node| {
            let updated = match node.connections.iter_mut().find(|edge| {
                edge.node_label == from_node_label.to_string()
                    && edge.direction == ConnectionDirection::From
            }) {
                Some(edge) => {
                    edge.weight = weight;
                    true
                }
                None => false,
            };

            if !updated {
                // create a new edge and push it
                node.connections.push(GraphEdge::new(
                    from_node_label.to_string(),
                    ConnectionDirection::From,
                    weight,
                ))
            }
        });
    }

    pub fn get_inputs_for_node(&mut self, node_label: &str) -> Option<Vec<GraphEdge>> {
        let node = self.get_node(node_label);
        if node.is_some() {
            Some(
                node.unwrap()
                    .connections
                    .iter()
                    .filter(|edge| edge.direction == ConnectionDirection::From)
                    .map(|edge| edge.clone())
                    .collect(),
            )
        } else {
            None
        }
    }

    pub fn get_outputs_for_node(&mut self, node_label: &str) -> Option<Vec<GraphEdge>> {
        let node = self.get_node(node_label);
        if node.is_some() {
            Some(
                node.unwrap()
                    .connections
                    .iter()
                    .map(|edge| edge.clone())
                    .filter(|edge| edge.direction == ConnectionDirection::To)
                    .collect(),
            )
        } else {
            None
        }
    }
}

/// Edge direction.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ConnectionDirection {
    From,
    To,
}

/// Representation of a an edge between two nodes.
// todo: convert node_label property into node and store a reference to a node. Will need to have some method that drops the ref if the node is deleted
#[derive(Debug, Clone)]
pub struct GraphEdge {
    direction: ConnectionDirection,
    node_label: String,
    weight: i64,
}

impl GraphEdge {
    pub fn new(node_label: String, direction: ConnectionDirection, weight: i64) -> GraphEdge {
        GraphEdge {
            direction,
            node_label,
            weight,
        }
    }

    pub fn get_connection_direction(&self) -> ConnectionDirection {
        self.direction
    }

    pub fn get_connected_label(&self) -> String {
        self.node_label.clone()
    }

    pub fn get_edge_weight(&self) -> i64 {
        self.weight
    }
}

/// A node in the graph, which stores its data and its connections to other nodes.
#[derive(Debug, Clone)]
pub struct LabelNode<D> {
    connections: Vec<GraphEdge>,
    data: D,
}

// todo: is it good to be explicate about the Clone trait bound in this struct?
impl<D> LabelNode<D> {
    pub fn new(data: D) -> Self {
        LabelNode {
            connections: Vec::new(),
            data
        }
    }
}