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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#![allow(dead_code)]
use std::fmt::{Formatter, Error, Debug};
use std::usize;
use std::collections::BitSet;
pub struct Graph<N,E> {
nodes: Vec<Node<N>> ,
edges: Vec<Edge<E>> ,
}
pub struct Node<N> {
first_edge: [EdgeIndex; 2],
pub data: N,
}
pub struct Edge<E> {
next_edge: [EdgeIndex; 2],
source: NodeIndex,
target: NodeIndex,
pub data: E,
}
impl<E: Debug> Debug for Edge<E> {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "Edge {{ next_edge: [{:?}, {:?}], source: {:?}, target: {:?}, data: {:?} }}",
self.next_edge[0], self.next_edge[1], self.source,
self.target, self.data)
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct NodeIndex(pub usize);
#[allow(non_upper_case_globals)]
pub const InvalidNodeIndex: NodeIndex = NodeIndex(usize::MAX);
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct EdgeIndex(pub usize);
#[allow(non_upper_case_globals)]
pub const InvalidEdgeIndex: EdgeIndex = EdgeIndex(usize::MAX);
#[derive(Copy, Clone, Debug)]
pub struct Direction { repr: usize }
#[allow(non_upper_case_globals)]
pub const Outgoing: Direction = Direction { repr: 0 };
#[allow(non_upper_case_globals)]
pub const Incoming: Direction = Direction { repr: 1 };
impl NodeIndex {
fn get(&self) -> usize { let NodeIndex(v) = *self; v }
pub fn node_id(&self) -> usize { self.get() }
}
impl EdgeIndex {
fn get(&self) -> usize { let EdgeIndex(v) = *self; v }
pub fn edge_id(&self) -> usize { self.get() }
}
impl<N,E> Graph<N,E> {
pub fn new() -> Graph<N,E> {
Graph {
nodes: Vec::new(),
edges: Vec::new(),
}
}
pub fn with_capacity(num_nodes: usize,
num_edges: usize) -> Graph<N,E> {
Graph {
nodes: Vec::with_capacity(num_nodes),
edges: Vec::with_capacity(num_edges),
}
}
#[inline]
pub fn all_nodes<'a>(&'a self) -> &'a [Node<N>] {
&self.nodes
}
#[inline]
pub fn all_edges<'a>(&'a self) -> &'a [Edge<E>] {
&self.edges
}
pub fn next_node_index(&self) -> NodeIndex {
NodeIndex(self.nodes.len())
}
pub fn add_node(&mut self, data: N) -> NodeIndex {
let idx = self.next_node_index();
self.nodes.push(Node {
first_edge: [InvalidEdgeIndex, InvalidEdgeIndex],
data: data
});
idx
}
pub fn mut_node_data<'a>(&'a mut self, idx: NodeIndex) -> &'a mut N {
&mut self.nodes[idx.get()].data
}
pub fn node_data<'a>(&'a self, idx: NodeIndex) -> &'a N {
&self.nodes[idx.get()].data
}
pub fn node<'a>(&'a self, idx: NodeIndex) -> &'a Node<N> {
&self.nodes[idx.get()]
}
pub fn next_edge_index(&self) -> EdgeIndex {
EdgeIndex(self.edges.len())
}
pub fn add_edge(&mut self,
source: NodeIndex,
target: NodeIndex,
data: E) -> EdgeIndex {
let idx = self.next_edge_index();
let source_first = self.nodes[source.get()]
.first_edge[Outgoing.repr];
let target_first = self.nodes[target.get()]
.first_edge[Incoming.repr];
self.edges.push(Edge {
next_edge: [source_first, target_first],
source: source,
target: target,
data: data
});
self.nodes[source.get()].first_edge[Outgoing.repr] = idx;
self.nodes[target.get()].first_edge[Incoming.repr] = idx;
return idx;
}
pub fn mut_edge_data<'a>(&'a mut self, idx: EdgeIndex) -> &'a mut E {
&mut self.edges[idx.get()].data
}
pub fn edge_data<'a>(&'a self, idx: EdgeIndex) -> &'a E {
&self.edges[idx.get()].data
}
pub fn edge<'a>(&'a self, idx: EdgeIndex) -> &'a Edge<E> {
&self.edges[idx.get()]
}
pub fn first_adjacent(&self, node: NodeIndex, dir: Direction) -> EdgeIndex {
self.nodes[node.get()].first_edge[dir.repr]
}
pub fn next_adjacent(&self, edge: EdgeIndex, dir: Direction) -> EdgeIndex {
self.edges[edge.get()].next_edge[dir.repr]
}
pub fn each_node<'a, F>(&'a self, mut f: F) -> bool where
F: FnMut(NodeIndex, &'a Node<N>) -> bool,
{
self.nodes.iter().enumerate().all(|(i, node)| f(NodeIndex(i), node))
}
pub fn each_edge<'a, F>(&'a self, mut f: F) -> bool where
F: FnMut(EdgeIndex, &'a Edge<E>) -> bool,
{
self.edges.iter().enumerate().all(|(i, edge)| f(EdgeIndex(i), edge))
}
pub fn each_outgoing_edge<'a, F>(&'a self, source: NodeIndex, f: F) -> bool where
F: FnMut(EdgeIndex, &'a Edge<E>) -> bool,
{
self.each_adjacent_edge(source, Outgoing, f)
}
pub fn each_incoming_edge<'a, F>(&'a self, target: NodeIndex, f: F) -> bool where
F: FnMut(EdgeIndex, &'a Edge<E>) -> bool,
{
self.each_adjacent_edge(target, Incoming, f)
}
pub fn each_adjacent_edge<'a, F>(&'a self,
node: NodeIndex,
dir: Direction,
mut f: F)
-> bool where
F: FnMut(EdgeIndex, &'a Edge<E>) -> bool,
{
let mut edge_idx = self.first_adjacent(node, dir);
while edge_idx != InvalidEdgeIndex {
let edge = &self.edges[edge_idx.get()];
if !f(edge_idx, edge) {
return false;
}
edge_idx = edge.next_edge[dir.repr];
}
return true;
}
pub fn iterate_until_fixed_point<'a, F>(&'a self, mut op: F) where
F: FnMut(usize, EdgeIndex, &'a Edge<E>) -> bool,
{
let mut iteration = 0;
let mut changed = true;
while changed {
changed = false;
iteration += 1;
for (i, edge) in self.edges.iter().enumerate() {
changed |= op(iteration, EdgeIndex(i), edge);
}
}
}
pub fn depth_traverse<'a>(&'a self, start: NodeIndex) -> DepthFirstTraversal<'a, N, E> {
DepthFirstTraversal {
graph: self,
stack: vec![start],
visited: BitSet::new()
}
}
}
pub struct DepthFirstTraversal<'g, N:'g, E:'g> {
graph: &'g Graph<N, E>,
stack: Vec<NodeIndex>,
visited: BitSet
}
impl<'g, N, E> Iterator for DepthFirstTraversal<'g, N, E> {
type Item = &'g N;
fn next(&mut self) -> Option<&'g N> {
while let Some(idx) = self.stack.pop() {
if !self.visited.insert(idx.node_id()) {
continue;
}
self.graph.each_outgoing_edge(idx, |_, e| -> bool {
if !self.visited.contains(&e.target().node_id()) {
self.stack.push(e.target());
}
true
});
return Some(self.graph.node_data(idx));
}
return None;
}
}
pub fn each_edge_index<F>(max_edge_index: EdgeIndex, mut f: F) where
F: FnMut(EdgeIndex) -> bool,
{
let mut i = 0;
let n = max_edge_index.get();
while i < n {
if !f(EdgeIndex(i)) {
return;
}
i += 1;
}
}
impl<E> Edge<E> {
pub fn source(&self) -> NodeIndex {
self.source
}
pub fn target(&self) -> NodeIndex {
self.target
}
}
#[cfg(test)]
mod test {
use middle::graph::*;
use std::fmt::Debug;
type TestNode = Node<&'static str>;
type TestEdge = Edge<&'static str>;
type TestGraph = Graph<&'static str, &'static str>;
fn create_graph() -> TestGraph {
let mut graph = Graph::new();
let a = graph.add_node("A");
let b = graph.add_node("B");
let c = graph.add_node("C");
let d = graph.add_node("D");
let e = graph.add_node("E");
let f = graph.add_node("F");
graph.add_edge(a, b, "AB");
graph.add_edge(b, c, "BC");
graph.add_edge(b, d, "BD");
graph.add_edge(d, e, "DE");
graph.add_edge(e, c, "EC");
graph.add_edge(f, b, "FB");
return graph;
}
#[test]
fn each_node() {
let graph = create_graph();
let expected = ["A", "B", "C", "D", "E", "F"];
graph.each_node(|idx, node| {
assert_eq!(&expected[idx.get()], graph.node_data(idx));
assert_eq!(expected[idx.get()], node.data);
true
});
}
#[test]
fn each_edge() {
let graph = create_graph();
let expected = ["AB", "BC", "BD", "DE", "EC", "FB"];
graph.each_edge(|idx, edge| {
assert_eq!(&expected[idx.get()], graph.edge_data(idx));
assert_eq!(expected[idx.get()], edge.data);
true
});
}
fn test_adjacent_edges<N:PartialEq+Debug,E:PartialEq+Debug>(graph: &Graph<N,E>,
start_index: NodeIndex,
start_data: N,
expected_incoming: &[(E,N)],
expected_outgoing: &[(E,N)]) {
assert!(graph.node_data(start_index) == &start_data);
let mut counter = 0;
graph.each_incoming_edge(start_index, |edge_index, edge| {
assert!(graph.edge_data(edge_index) == &edge.data);
assert!(counter < expected_incoming.len());
debug!("counter={:?} expected={:?} edge_index={:?} edge={:?}",
counter, expected_incoming[counter], edge_index, edge);
match expected_incoming[counter] {
(ref e, ref n) => {
assert!(e == &edge.data);
assert!(n == graph.node_data(edge.source));
assert!(start_index == edge.target);
}
}
counter += 1;
true
});
assert_eq!(counter, expected_incoming.len());
let mut counter = 0;
graph.each_outgoing_edge(start_index, |edge_index, edge| {
assert!(graph.edge_data(edge_index) == &edge.data);
assert!(counter < expected_outgoing.len());
debug!("counter={:?} expected={:?} edge_index={:?} edge={:?}",
counter, expected_outgoing[counter], edge_index, edge);
match expected_outgoing[counter] {
(ref e, ref n) => {
assert!(e == &edge.data);
assert!(start_index == edge.source);
assert!(n == graph.node_data(edge.target));
}
}
counter += 1;
true
});
assert_eq!(counter, expected_outgoing.len());
}
#[test]
fn each_adjacent_from_a() {
let graph = create_graph();
test_adjacent_edges(&graph, NodeIndex(0), "A",
&[],
&[("AB", "B")]);
}
#[test]
fn each_adjacent_from_b() {
let graph = create_graph();
test_adjacent_edges(&graph, NodeIndex(1), "B",
&[("FB", "F"), ("AB", "A"),],
&[("BD", "D"), ("BC", "C"),]);
}
#[test]
fn each_adjacent_from_c() {
let graph = create_graph();
test_adjacent_edges(&graph, NodeIndex(2), "C",
&[("EC", "E"), ("BC", "B")],
&[]);
}
#[test]
fn each_adjacent_from_d() {
let graph = create_graph();
test_adjacent_edges(&graph, NodeIndex(3), "D",
&[("BD", "B")],
&[("DE", "E")]);
}
}