-
Notifications
You must be signed in to change notification settings - Fork 320
/
mod.rs
2054 lines (1890 loc) · 63.7 KB
/
mod.rs
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! `StableGraph` keeps indices stable across removals.
//!
//! Depends on `feature = "stable_graph"`.
//!
use std::cmp;
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::mem::replace;
use std::mem::size_of;
use std::ops::{Index, IndexMut};
use std::slice;
use fixedbitset::FixedBitSet;
use crate::{Directed, Direction, EdgeType, Graph, Incoming, Outgoing, Undirected};
use crate::iter_format::{DebugMap, IterFormatExt, NoPretty};
use crate::iter_utils::IterUtilsExt;
use super::{index_twice, Edge, Frozen, Node, Pair, DIRECTIONS};
use crate::visit;
use crate::visit::{EdgeIndexable, EdgeRef, IntoEdgeReferences, NodeIndexable};
use crate::IntoWeightedEdge;
// reexport those things that are shared with Graph
#[doc(no_inline)]
pub use crate::graph::{
edge_index, node_index, DefaultIx, EdgeIndex, GraphIndex, IndexType, NodeIndex,
};
use crate::util::enumerate;
#[cfg(feature = "serde-1")]
mod serialization;
/// `StableGraph<N, E, Ty, Ix>` is a graph datastructure using an adjacency
/// list representation.
///
/// The graph **does not invalidate** any unrelated node or edge indices when
/// items are removed.
///
/// `StableGraph` is parameterized over:
///
/// - Associated data `N` for nodes and `E` for edges, also called *weights*.
/// The associated data can be of arbitrary type.
/// - Edge type `Ty` that determines whether the graph edges are directed or undirected.
/// - Index type `Ix`, which determines the maximum size of the graph.
///
/// The graph uses **O(|V| + |E|)** space, and allows fast node and edge insert
/// and efficient graph search.
///
/// It implements **O(e')** edge lookup and edge and node removals, where **e'**
/// is some local measure of edge count.
///
/// - Nodes and edges are each numbered in an interval from *0* to some number
/// *m*, but *not all* indices in the range are valid, since gaps are formed
/// by deletions.
///
/// - You can select graph index integer type after the size of the graph. A smaller
/// size may have better performance.
///
/// - Using indices allows mutation while traversing the graph, see `Dfs`.
///
/// - The `StableGraph` is a regular rust collection and is `Send` and `Sync`
/// (as long as associated data `N` and `E` are).
///
/// - Indices don't allow as much compile time checking as references.
///
/// Depends on crate feature `stable_graph` (default). *Stable Graph is still
/// missing a few methods compared to Graph. You can contribute to help it
/// achieve parity.*
pub struct StableGraph<N, E, Ty = Directed, Ix = DefaultIx> {
g: Graph<Option<N>, Option<E>, Ty, Ix>,
node_count: usize,
edge_count: usize,
// node and edge free lists (both work the same way)
//
// free_node, if not NodeIndex::end(), points to a node index
// that is vacant (after a deletion).
// The free nodes form a doubly linked list using the fields Node.next[0]
// for forward references and Node.next[1] for backwards ones.
// The nodes are stored as EdgeIndex, and the _into_edge()/_into_node()
// methods convert.
// free_edge, if not EdgeIndex::end(), points to a free edge.
// The edges only form a singly linked list using Edge.next[0] to store
// the forward reference.
free_node: NodeIndex<Ix>,
free_edge: EdgeIndex<Ix>,
}
/// A `StableGraph` with directed edges.
///
/// For example, an edge from *1* to *2* is distinct from an edge from *2* to
/// *1*.
pub type StableDiGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Directed, Ix>;
/// A `StableGraph` with undirected edges.
///
/// For example, an edge between *1* and *2* is equivalent to an edge between
/// *2* and *1*.
pub type StableUnGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Undirected, Ix>;
impl<N, E, Ty, Ix> fmt::Debug for StableGraph<N, E, Ty, Ix>
where
N: fmt::Debug,
E: fmt::Debug,
Ty: EdgeType,
Ix: IndexType,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let etype = if self.is_directed() {
"Directed"
} else {
"Undirected"
};
let mut fmt_struct = f.debug_struct("StableGraph");
fmt_struct.field("Ty", &etype);
fmt_struct.field("node_count", &self.node_count);
fmt_struct.field("edge_count", &self.edge_count);
if self.g.edges.iter().any(|e| e.weight.is_some()) {
fmt_struct.field(
"edges",
&self
.g
.edges
.iter()
.filter(|e| e.weight.is_some())
.map(|e| NoPretty((e.source().index(), e.target().index())))
.format(", "),
);
}
// skip weights if they are ZST!
if size_of::<N>() != 0 {
fmt_struct.field(
"node weights",
&DebugMap(|| {
self.g
.nodes
.iter()
.map(|n| n.weight.as_ref())
.enumerate()
.filter_map(|(i, wo)| wo.map(move |w| (i, w)))
}),
);
}
if size_of::<E>() != 0 {
fmt_struct.field(
"edge weights",
&DebugMap(|| {
self.g
.edges
.iter()
.map(|n| n.weight.as_ref())
.enumerate()
.filter_map(|(i, wo)| wo.map(move |w| (i, w)))
}),
);
}
fmt_struct.field("free_node", &self.free_node);
fmt_struct.field("free_edge", &self.free_edge);
fmt_struct.finish()
}
}
impl<N, E> StableGraph<N, E, Directed> {
/// Create a new `StableGraph` with directed edges.
///
/// This is a convenience method. See `StableGraph::with_capacity`
/// or `StableGraph::default` for a constructor that is generic in all the
/// type parameters of `StableGraph`.
pub fn new() -> Self {
Self::with_capacity(0, 0)
}
}
impl<N, E, Ty, Ix> StableGraph<N, E, Ty, Ix>
where
Ty: EdgeType,
Ix: IndexType,
{
/// Create a new `StableGraph` with estimated capacity.
pub fn with_capacity(nodes: usize, edges: usize) -> Self {
StableGraph {
g: Graph::with_capacity(nodes, edges),
node_count: 0,
edge_count: 0,
free_node: NodeIndex::end(),
free_edge: EdgeIndex::end(),
}
}
/// Return the current node and edge capacity of the graph.
pub fn capacity(&self) -> (usize, usize) {
self.g.capacity()
}
/// Reverse the direction of all edges
pub fn reverse(&mut self) {
// swap edge endpoints,
// edge incoming / outgoing lists,
// node incoming / outgoing lists
for edge in &mut self.g.edges {
edge.node.swap(0, 1);
edge.next.swap(0, 1);
}
for node in &mut self.g.nodes {
node.next.swap(0, 1);
}
}
/// Remove all nodes and edges
pub fn clear(&mut self) {
self.node_count = 0;
self.edge_count = 0;
self.free_node = NodeIndex::end();
self.free_edge = EdgeIndex::end();
self.g.clear();
}
/// Remove all edges
pub fn clear_edges(&mut self) {
self.edge_count = 0;
self.free_edge = EdgeIndex::end();
self.g.edges.clear();
// clear edges without touching the free list
for node in &mut self.g.nodes {
if node.weight.is_some() {
node.next = [EdgeIndex::end(), EdgeIndex::end()];
}
}
}
/// Return the number of nodes (vertices) in the graph.
///
/// Computes in **O(1)** time.
pub fn node_count(&self) -> usize {
self.node_count
}
/// Return the number of edges in the graph.
///
/// Computes in **O(1)** time.
pub fn edge_count(&self) -> usize {
self.edge_count
}
/// Whether the graph has directed edges or not.
#[inline]
pub fn is_directed(&self) -> bool {
Ty::is_directed()
}
/// Add a node (also called vertex) with associated data `weight` to the graph.
///
/// Computes in **O(1)** time.
///
/// Return the index of the new node.
///
/// **Panics** if the `StableGraph` is at the maximum number of nodes for
/// its index type.
pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
if self.free_node != NodeIndex::end() {
let node_idx = self.free_node;
self.occupy_vacant_node(node_idx, weight);
node_idx
} else {
self.node_count += 1;
self.g.add_node(Some(weight))
}
}
/// free_node: Which free list to update for the vacancy
fn add_vacant_node(&mut self, free_node: &mut NodeIndex<Ix>) {
let node_idx = self.g.add_node(None);
// link the free list
let node_slot = &mut self.g.nodes[node_idx.index()];
node_slot.next = [free_node._into_edge(), EdgeIndex::end()];
if *free_node != NodeIndex::end() {
self.g.nodes[free_node.index()].next[1] = node_idx._into_edge();
}
*free_node = node_idx;
}
/// Remove `a` from the graph if it exists, and return its weight.
/// If it doesn't exist in the graph, return `None`.
///
/// The node index `a` is invalidated, but none other.
/// Edge indices are invalidated as they would be following the removal of
/// each edge with an endpoint in `a`.
///
/// Computes in **O(e')** time, where **e'** is the number of affected
/// edges, including *n* calls to `.remove_edge()` where *n* is the number
/// of edges with an endpoint in `a`.
pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N> {
let node_weight = self.g.nodes.get_mut(a.index())?.weight.take()?;
for d in &DIRECTIONS {
let k = d.index();
// Remove all edges from and to this node.
loop {
let next = self.g.nodes[a.index()].next[k];
if next == EdgeIndex::end() {
break;
}
let ret = self.remove_edge(next);
debug_assert!(ret.is_some());
let _ = ret;
}
}
let node_slot = &mut self.g.nodes[a.index()];
//let node_weight = replace(&mut self.g.nodes[a.index()].weight, Entry::Empty(self.free_node));
//self.g.nodes[a.index()].next = [EdgeIndex::end(), EdgeIndex::end()];
node_slot.next = [self.free_node._into_edge(), EdgeIndex::end()];
if self.free_node != NodeIndex::end() {
self.g.nodes[self.free_node.index()].next[1] = a._into_edge();
}
self.free_node = a;
self.node_count -= 1;
Some(node_weight)
}
pub fn contains_node(&self, a: NodeIndex<Ix>) -> bool {
self.get_node(a).is_some()
}
// Return the Node if it is not vacant (non-None weight)
fn get_node(&self, a: NodeIndex<Ix>) -> Option<&Node<Option<N>, Ix>> {
self.g
.nodes
.get(a.index())
.and_then(|node| node.weight.as_ref().map(move |_| node))
}
/// Add an edge from `a` to `b` to the graph, with its associated
/// data `weight`.
///
/// Return the index of the new edge.
///
/// Computes in **O(1)** time.
///
/// **Panics** if any of the nodes don't exist.<br>
/// **Panics** if the `StableGraph` is at the maximum number of edges for
/// its index type.
///
/// **Note:** `StableGraph` allows adding parallel (“duplicate”) edges.
pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
let edge_idx;
let mut new_edge = None::<Edge<_, _>>;
{
let edge: &mut Edge<_, _>;
if self.free_edge != EdgeIndex::end() {
edge_idx = self.free_edge;
edge = &mut self.g.edges[edge_idx.index()];
let _old = replace(&mut edge.weight, Some(weight));
debug_assert!(_old.is_none());
self.free_edge = edge.next[0];
edge.node = [a, b];
} else {
edge_idx = EdgeIndex::new(self.g.edges.len());
assert!(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx);
new_edge = Some(Edge {
weight: Some(weight),
node: [a, b],
next: [EdgeIndex::end(); 2],
});
edge = new_edge.as_mut().unwrap();
}
let wrong_index = match index_twice(&mut self.g.nodes, a.index(), b.index()) {
Pair::None => Some(cmp::max(a.index(), b.index())),
Pair::One(an) => {
if an.weight.is_none() {
Some(a.index())
} else {
edge.next = an.next;
an.next[0] = edge_idx;
an.next[1] = edge_idx;
None
}
}
Pair::Both(an, bn) => {
// a and b are different indices
if an.weight.is_none() {
Some(a.index())
} else if bn.weight.is_none() {
Some(b.index())
} else {
edge.next = [an.next[0], bn.next[1]];
an.next[0] = edge_idx;
bn.next[1] = edge_idx;
None
}
}
};
if let Some(i) = wrong_index {
panic!(
"StableGraph::add_edge: node index {} is not a node in the graph",
i
);
}
self.edge_count += 1;
}
if let Some(edge) = new_edge {
self.g.edges.push(edge);
}
edge_idx
}
/// free_edge: Which free list to update for the vacancy
fn add_vacant_edge(&mut self, free_edge: &mut EdgeIndex<Ix>) {
let edge_idx = EdgeIndex::new(self.g.edges.len());
debug_assert!(edge_idx != EdgeIndex::end());
let mut edge = Edge {
weight: None,
node: [NodeIndex::end(); 2],
next: [EdgeIndex::end(); 2],
};
edge.next[0] = *free_edge;
*free_edge = edge_idx;
self.g.edges.push(edge);
}
/// Add or update an edge from `a` to `b`.
/// If the edge already exists, its weight is updated.
///
/// Return the index of the affected edge.
///
/// Computes in **O(e')** time, where **e'** is the number of edges
/// connected to `a` (and `b`, if the graph edges are undirected).
///
/// **Panics** if any of the nodes don't exist.
pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
if let Some(ix) = self.find_edge(a, b) {
self[ix] = weight;
return ix;
}
self.add_edge(a, b, weight)
}
/// Remove an edge and return its edge weight, or `None` if it didn't exist.
///
/// Invalidates the edge index `e` but no other.
///
/// Computes in **O(e')** time, where **e'** is the number of edges
/// connected to the same endpoints as `e`.
pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
// every edge is part of two lists,
// outgoing and incoming edges.
// Remove it from both
let (is_edge, edge_node, edge_next) = match self.g.edges.get(e.index()) {
None => return None,
Some(x) => (x.weight.is_some(), x.node, x.next),
};
if !is_edge {
return None;
}
// Remove the edge from its in and out lists by replacing it with
// a link to the next in the list.
self.g.change_edge_links(edge_node, e, edge_next);
// Clear the edge and put it in the free list
let edge = &mut self.g.edges[e.index()];
edge.next = [self.free_edge, EdgeIndex::end()];
edge.node = [NodeIndex::end(), NodeIndex::end()];
self.free_edge = e;
self.edge_count -= 1;
edge.weight.take()
}
/// Access the weight for node `a`.
///
/// Also available with indexing syntax: `&graph[a]`.
pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
match self.g.nodes.get(a.index()) {
Some(no) => no.weight.as_ref(),
None => None,
}
}
/// Access the weight for node `a`, mutably.
///
/// Also available with indexing syntax: `&mut graph[a]`.
pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
match self.g.nodes.get_mut(a.index()) {
Some(no) => no.weight.as_mut(),
None => None,
}
}
/// Return an iterator yielding immutable access to all node weights.
///
/// The order in which weights are yielded matches the order of their node
/// indices.
pub fn node_weights(&self) -> impl Iterator<Item = &N> {
self.g
.node_weights()
.filter_map(|maybe_node| maybe_node.as_ref())
}
/// Return an iterator yielding mutable access to all node weights.
///
/// The order in which weights are yielded matches the order of their node
/// indices.
pub fn node_weights_mut(&mut self) -> impl Iterator<Item = &mut N> {
self.g
.node_weights_mut()
.filter_map(|maybe_node| maybe_node.as_mut())
}
/// Return an iterator over the node indices of the graph
pub fn node_indices(&self) -> NodeIndices<N, Ix> {
NodeIndices {
iter: enumerate(self.raw_nodes()),
}
}
/// Access the weight for edge `e`.
///
/// Also available with indexing syntax: `&graph[e]`.
pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
match self.g.edges.get(e.index()) {
Some(ed) => ed.weight.as_ref(),
None => None,
}
}
/// Access the weight for edge `e`, mutably
///
/// Also available with indexing syntax: `&mut graph[e]`.
pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
match self.g.edges.get_mut(e.index()) {
Some(ed) => ed.weight.as_mut(),
None => None,
}
}
/// Return an iterator yielding immutable access to all edge weights.
///
/// The order in which weights are yielded matches the order of their edge
/// indices.
pub fn edge_weights(&self) -> impl Iterator<Item = &E> {
self.g
.edge_weights()
.filter_map(|maybe_edge| maybe_edge.as_ref())
}
/// Return an iterator yielding mutable access to all edge weights.
///
/// The order in which weights are yielded matches the order of their edge
/// indices.
pub fn edge_weights_mut(&mut self) -> impl Iterator<Item = &mut E> {
self.g
.edge_weights_mut()
.filter_map(|maybe_edge| maybe_edge.as_mut())
}
/// Access the source and target nodes for `e`.
pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)> {
match self.g.edges.get(e.index()) {
Some(ed) if ed.weight.is_some() => Some((ed.source(), ed.target())),
_otherwise => None,
}
}
/// Return an iterator over the edge indices of the graph
pub fn edge_indices(&self) -> EdgeIndices<E, Ix> {
EdgeIndices {
iter: enumerate(self.raw_edges()),
}
}
/// Lookup if there is an edge from `a` to `b`.
///
/// Computes in **O(e')** time, where **e'** is the number of edges
/// connected to `a` (and `b`, if the graph edges are undirected).
pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
self.find_edge(a, b).is_some()
}
/// Lookup an edge from `a` to `b`.
///
/// Computes in **O(e')** time, where **e'** is the number of edges
/// connected to `a` (and `b`, if the graph edges are undirected).
pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>> {
if !self.is_directed() {
self.find_edge_undirected(a, b).map(|(ix, _)| ix)
} else {
match self.get_node(a) {
None => None,
Some(node) => self.g.find_edge_directed_from_node(node, b),
}
}
}
/// Lookup an edge between `a` and `b`, in either direction.
///
/// If the graph is undirected, then this is equivalent to `.find_edge()`.
///
/// Return the edge index and its directionality, with `Outgoing` meaning
/// from `a` to `b` and `Incoming` the reverse,
/// or `None` if the edge does not exist.
pub fn find_edge_undirected(
&self,
a: NodeIndex<Ix>,
b: NodeIndex<Ix>,
) -> Option<(EdgeIndex<Ix>, Direction)> {
match self.get_node(a) {
None => None,
Some(node) => self.g.find_edge_undirected_from_node(node, b),
}
}
/// Return an iterator of all nodes with an edge starting from `a`.
///
/// - `Directed`: Outgoing edges from `a`.
/// - `Undirected`: All edges connected to `a`.
///
/// Produces an empty iterator if the node doesn't exist.<br>
/// Iterator element type is `NodeIndex<Ix>`.
///
/// Use [`.neighbors(a).detach()`][1] to get a neighbor walker that does
/// not borrow from the graph.
///
/// [1]: struct.Neighbors.html#method.detach
pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
self.neighbors_directed(a, Outgoing)
}
/// Return an iterator of all neighbors that have an edge between them and `a`,
/// in the specified direction.
/// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
///
/// - `Directed`, `Outgoing`: All edges from `a`.
/// - `Directed`, `Incoming`: All edges to `a`.
/// - `Undirected`: All edges connected to `a`.
///
/// Produces an empty iterator if the node doesn't exist.<br>
/// Iterator element type is `NodeIndex<Ix>`.
///
/// Use [`.neighbors_directed(a, dir).detach()`][1] to get a neighbor walker that does
/// not borrow from the graph.
///
/// [1]: struct.Neighbors.html#method.detach
pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix> {
let mut iter = self.neighbors_undirected(a);
if self.is_directed() {
let k = dir.index();
iter.next[1 - k] = EdgeIndex::end();
iter.skip_start = NodeIndex::end();
}
iter
}
/// Return an iterator of all neighbors that have an edge between them and `a`,
/// in either direction.
/// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
///
/// - `Directed` and `Undirected`: All edges connected to `a`.
///
/// Produces an empty iterator if the node doesn't exist.<br>
/// Iterator element type is `NodeIndex<Ix>`.
///
/// Use [`.neighbors_undirected(a).detach()`][1] to get a neighbor walker that does
/// not borrow from the graph.
///
/// [1]: struct.Neighbors.html#method.detach
pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
Neighbors {
skip_start: a,
edges: &self.g.edges,
next: match self.get_node(a) {
None => [EdgeIndex::end(), EdgeIndex::end()],
Some(n) => n.next,
},
}
}
/// Return an iterator of all edges of `a`.
///
/// - `Directed`: Outgoing edges from `a`.
/// - `Undirected`: All edges connected to `a`.
///
/// Produces an empty iterator if the node doesn't exist.<br>
/// Iterator element type is `EdgeReference<E, Ix>`.
pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
self.edges_directed(a, Outgoing)
}
/// Return an iterator of all edges of `a`, in the specified direction.
///
/// - `Directed`, `Outgoing`: All edges from `a`.
/// - `Directed`, `Incoming`: All edges to `a`.
/// - `Undirected`, `Outgoing`: All edges connected to `a`, with `a` being the source of each
/// edge.
/// - `Undirected`, `Incoming`: All edges connected to `a`, with `a` being the target of each
/// edge.
///
/// Produces an empty iterator if the node `a` doesn't exist.<br>
/// Iterator element type is `EdgeReference<E, Ix>`.
pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix> {
Edges {
skip_start: a,
edges: &self.g.edges,
direction: dir,
next: match self.get_node(a) {
None => [EdgeIndex::end(), EdgeIndex::end()],
Some(n) => n.next,
},
ty: PhantomData,
}
}
/// Return an iterator over either the nodes without edges to them
/// (`Incoming`) or from them (`Outgoing`).
///
/// An *internal* node has both incoming and outgoing edges.
/// The nodes in `.externals(Incoming)` are the source nodes and
/// `.externals(Outgoing)` are the sinks of the graph.
///
/// For a graph with undirected edges, both the sinks and the sources are
/// just the nodes without edges.
///
/// The whole iteration computes in **O(|V|)** time.
pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix> {
Externals {
iter: self.raw_nodes().iter().enumerate(),
dir,
ty: PhantomData,
}
}
/// Index the `StableGraph` by two indices, any combination of
/// node or edge indices is fine.
///
/// **Panics** if the indices are equal or if they are out of bounds.
pub fn index_twice_mut<T, U>(
&mut self,
i: T,
j: U,
) -> (
&mut <Self as Index<T>>::Output,
&mut <Self as Index<U>>::Output,
)
where
Self: IndexMut<T> + IndexMut<U>,
T: GraphIndex,
U: GraphIndex,
{
assert!(T::is_node_index() != U::is_node_index() || i.index() != j.index());
// Allow two mutable indexes here -- they are nonoverlapping
unsafe {
let self_mut = self as *mut _;
(
<Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
<Self as IndexMut<U>>::index_mut(&mut *self_mut, j),
)
}
}
/// Keep all nodes that return `true` from the `visit` closure,
/// remove the others.
///
/// `visit` is provided a proxy reference to the graph, so that
/// the graph can be walked and associated data modified.
///
/// The order nodes are visited is not specified.
///
/// The node indices of the removed nodes are invalidated, but none other.
/// Edge indices are invalidated as they would be following the removal of
/// each edge with an endpoint in a removed node.
///
/// Computes in **O(n + e')** time, where **n** is the number of node indices and
/// **e'** is the number of affected edges, including *n* calls to `.remove_edge()`
/// where *n* is the number of edges with an endpoint in a removed node.
pub fn retain_nodes<F>(&mut self, mut visit: F)
where
F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,
{
for i in 0..self.node_bound() {
let ix = node_index(i);
if self.contains_node(ix) && !visit(Frozen(self), ix) {
self.remove_node(ix);
}
}
self.check_free_lists();
}
/// Keep all edges that return `true` from the `visit` closure,
/// remove the others.
///
/// `visit` is provided a proxy reference to the graph, so that
/// the graph can be walked and associated data modified.
///
/// The order edges are visited is not specified.
///
/// The edge indices of the removed edes are invalidated, but none other.
///
/// Computes in **O(e'')** time, **e'** is the number of affected edges,
/// including the calls to `.remove_edge()` for each removed edge.
pub fn retain_edges<F>(&mut self, mut visit: F)
where
F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,
{
for i in 0..self.edge_bound() {
let ix = edge_index(i);
if self.edge_weight(ix).is_some() && !visit(Frozen(self), ix) {
self.remove_edge(ix);
}
}
self.check_free_lists();
}
/// Create a new `StableGraph` from an iterable of edges.
///
/// Node weights `N` are set to default values.
/// Edge weights `E` may either be specified in the list,
/// or they are filled with default values.
///
/// Nodes are inserted automatically to match the edges.
///
/// ```
/// use petgraph::stable_graph::StableGraph;
///
/// let gr = StableGraph::<(), i32>::from_edges(&[
/// (0, 1), (0, 2), (0, 3),
/// (1, 2), (1, 3),
/// (2, 3),
/// ]);
/// ```
pub fn from_edges<I>(iterable: I) -> Self
where
I: IntoIterator,
I::Item: IntoWeightedEdge<E>,
<I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
N: Default,
{
let mut g = Self::with_capacity(0, 0);
g.extend_with_edges(iterable);
g
}
/// Create a new `StableGraph` by mapping node and
/// edge weights to new values.
///
/// The resulting graph has the same structure and the same
/// graph indices as `self`.
pub fn map<'a, F, G, N2, E2>(
&'a self,
mut node_map: F,
mut edge_map: G,
) -> StableGraph<N2, E2, Ty, Ix>
where
F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
{
let g = self.g.map(
move |i, w| w.as_ref().map(|w| node_map(i, w)),
move |i, w| w.as_ref().map(|w| edge_map(i, w)),
);
StableGraph {
g,
node_count: self.node_count,
edge_count: self.edge_count,
free_node: self.free_node,
free_edge: self.free_edge,
}
}
/// Create a new `StableGraph` by mapping nodes and edges.
/// A node or edge may be mapped to `None` to exclude it from
/// the resulting graph.
///
/// Nodes are mapped first with the `node_map` closure, then
/// `edge_map` is called for the edges that have not had any endpoint
/// removed.
///
/// The resulting graph has the structure of a subgraph of the original graph.
/// Nodes and edges that are not removed maintain their old node or edge
/// indices.
pub fn filter_map<'a, F, G, N2, E2>(
&'a self,
mut node_map: F,
mut edge_map: G,
) -> StableGraph<N2, E2, Ty, Ix>
where
F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
{
let node_bound = self.node_bound();
let edge_bound = self.edge_bound();
let mut result_g = StableGraph::with_capacity(node_bound, edge_bound);
// use separate free lists so that
// add_node / add_edge below do not reuse the tombstones
let mut free_node = NodeIndex::end();
let mut free_edge = EdgeIndex::end();
// the stable graph keeps the node map itself
for (i, node) in enumerate(self.raw_nodes()) {
if i >= node_bound {
break;
}
if let Some(node_weight) = node.weight.as_ref() {
if let Some(new_weight) = node_map(NodeIndex::new(i), node_weight) {
result_g.add_node(new_weight);
continue;
}
}
result_g.add_vacant_node(&mut free_node);
}
for (i, edge) in enumerate(self.raw_edges()) {
if i >= edge_bound {
break;
}
let source = edge.source();
let target = edge.target();
if let Some(edge_weight) = edge.weight.as_ref() {
if result_g.contains_node(source) && result_g.contains_node(target) {
if let Some(new_weight) = edge_map(EdgeIndex::new(i), edge_weight) {
result_g.add_edge(source, target, new_weight);
continue;
}
}
}
result_g.add_vacant_edge(&mut free_edge);
}
result_g.free_node = free_node;
result_g.free_edge = free_edge;
result_g.check_free_lists();
result_g
}
/// Extend the graph from an iterable of edges.
///
/// Node weights `N` are set to default values.
/// Edge weights `E` may either be specified in the list,
/// or they are filled with default values.
///
/// Nodes are inserted automatically to match the edges.
pub fn extend_with_edges<I>(&mut self, iterable: I)
where
I: IntoIterator,
I::Item: IntoWeightedEdge<E>,
<I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
N: Default,
{
let iter = iterable.into_iter();
for elt in iter {
let (source, target, weight) = elt.into_weighted_edge();
let (source, target) = (source.into(), target.into());
self.ensure_node_exists(source);
self.ensure_node_exists(target);
self.add_edge(source, target, weight);
}
}
//
// internal methods
//
fn raw_nodes(&self) -> &[Node<Option<N>, Ix>] {
self.g.raw_nodes()
}
fn raw_edges(&self) -> &[Edge<Option<E>, Ix>] {
self.g.raw_edges()
}
/// Create a new node using a vacant position,
/// updating the free nodes doubly linked list.
fn occupy_vacant_node(&mut self, node_idx: NodeIndex<Ix>, weight: N) {
let node_slot = &mut self.g.nodes[node_idx.index()];
let _old = replace(&mut node_slot.weight, Some(weight));
debug_assert!(_old.is_none());
let previous_node = node_slot.next[1];
let next_node = node_slot.next[0];
node_slot.next = [EdgeIndex::end(), EdgeIndex::end()];
if previous_node != EdgeIndex::end() {
self.g.nodes[previous_node.index()].next[0] = next_node;
}
if next_node != EdgeIndex::end() {
self.g.nodes[next_node.index()].next[1] = previous_node;
}
if self.free_node == node_idx {
self.free_node = next_node._into_node();
}
self.node_count += 1;
}
/// Create the node if it does not exist,
/// adding vacant nodes for padding if needed.
fn ensure_node_exists(&mut self, node_ix: NodeIndex<Ix>)
where
N: Default,