1 //! `StableGraph` keeps indices stable across removals.
2 //!
3 //! Depends on `feature = "stable_graph"`.
4 //!
5 
6 use std::cmp;
7 use std::fmt;
8 use std::iter;
9 use std::marker::PhantomData;
10 use std::mem::replace;
11 use std::mem::size_of;
12 use std::ops::{Index, IndexMut};
13 use std::slice;
14 
15 use fixedbitset::FixedBitSet;
16 
17 use crate::{Directed, Direction, EdgeType, Graph, Incoming, Outgoing, Undirected};
18 
19 use crate::iter_format::{DebugMap, IterFormatExt, NoPretty};
20 use crate::iter_utils::IterUtilsExt;
21 
22 use super::{index_twice, Edge, Frozen, Node, Pair, DIRECTIONS};
23 use crate::visit;
24 use crate::visit::{EdgeIndexable, EdgeRef, IntoEdgeReferences, NodeIndexable};
25 use crate::IntoWeightedEdge;
26 
27 // reexport those things that are shared with Graph
28 #[doc(no_inline)]
29 pub use crate::graph::{
30     edge_index, node_index, DefaultIx, EdgeIndex, GraphIndex, IndexType, NodeIndex,
31 };
32 
33 use crate::util::enumerate;
34 
35 #[cfg(feature = "serde-1")]
36 mod serialization;
37 
38 /// `StableGraph<N, E, Ty, Ix>` is a graph datastructure using an adjacency
39 /// list representation.
40 ///
41 /// The graph **does not invalidate** any unrelated node or edge indices when
42 /// items are removed.
43 ///
44 /// `StableGraph` is parameterized over:
45 ///
46 /// - Associated data `N` for nodes and `E` for edges, also called *weights*.
47 ///   The associated data can be of arbitrary type.
48 /// - Edge type `Ty` that determines whether the graph edges are directed or undirected.
49 /// - Index type `Ix`, which determines the maximum size of the graph.
50 ///
51 /// The graph uses **O(|V| + |E|)** space, and allows fast node and edge insert
52 /// and efficient graph search.
53 ///
54 /// It implements **O(e')** edge lookup and edge and node removals, where **e'**
55 /// is some local measure of edge count.
56 ///
57 /// - Nodes and edges are each numbered in an interval from *0* to some number
58 /// *m*, but *not all* indices in the range are valid, since gaps are formed
59 /// by deletions.
60 ///
61 /// - You can select graph index integer type after the size of the graph. A smaller
62 /// size may have better performance.
63 ///
64 /// - Using indices allows mutation while traversing the graph, see `Dfs`.
65 ///
66 /// - The `StableGraph` is a regular rust collection and is `Send` and `Sync`
67 /// (as long as associated data `N` and `E` are).
68 ///
69 /// - Indices don't allow as much compile time checking as references.
70 ///
71 /// Depends on crate feature `stable_graph` (default). *Stable Graph is still
72 /// missing a few methods compared to Graph. You can contribute to help it
73 /// achieve parity.*
74 pub struct StableGraph<N, E, Ty = Directed, Ix = DefaultIx> {
75     g: Graph<Option<N>, Option<E>, Ty, Ix>,
76     node_count: usize,
77     edge_count: usize,
78 
79     // node and edge free lists (both work the same way)
80     //
81     // free_node, if not NodeIndex::end(), points to a node index
82     // that is vacant (after a deletion).
83     // The free nodes form a doubly linked list using the fields Node.next[0]
84     // for forward references and Node.next[1] for backwards ones.
85     // The nodes are stored as EdgeIndex, and the _into_edge()/_into_node()
86     // methods convert.
87     // free_edge, if not EdgeIndex::end(), points to a free edge.
88     // The edges only form a singly linked list using Edge.next[0] to store
89     // the forward reference.
90     free_node: NodeIndex<Ix>,
91     free_edge: EdgeIndex<Ix>,
92 }
93 
94 /// A `StableGraph` with directed edges.
95 ///
96 /// For example, an edge from *1* to *2* is distinct from an edge from *2* to
97 /// *1*.
98 pub type StableDiGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Directed, Ix>;
99 
100 /// A `StableGraph` with undirected edges.
101 ///
102 /// For example, an edge between *1* and *2* is equivalent to an edge between
103 /// *2* and *1*.
104 pub type StableUnGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Undirected, Ix>;
105 
106 impl<N, E, Ty, Ix> fmt::Debug for StableGraph<N, E, Ty, Ix>
107 where
108     N: fmt::Debug,
109     E: fmt::Debug,
110     Ty: EdgeType,
111     Ix: IndexType,
112 {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result113     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114         let etype = if self.is_directed() {
115             "Directed"
116         } else {
117             "Undirected"
118         };
119         let mut fmt_struct = f.debug_struct("StableGraph");
120         fmt_struct.field("Ty", &etype);
121         fmt_struct.field("node_count", &self.node_count);
122         fmt_struct.field("edge_count", &self.edge_count);
123         if self.g.edges.iter().any(|e| e.weight.is_some()) {
124             fmt_struct.field(
125                 "edges",
126                 &self
127                     .g
128                     .edges
129                     .iter()
130                     .filter(|e| e.weight.is_some())
131                     .map(|e| NoPretty((e.source().index(), e.target().index())))
132                     .format(", "),
133             );
134         }
135         // skip weights if they are ZST!
136         if size_of::<N>() != 0 {
137             fmt_struct.field(
138                 "node weights",
139                 &DebugMap(|| {
140                     self.g
141                         .nodes
142                         .iter()
143                         .map(|n| n.weight.as_ref())
144                         .enumerate()
145                         .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
146                 }),
147             );
148         }
149         if size_of::<E>() != 0 {
150             fmt_struct.field(
151                 "edge weights",
152                 &DebugMap(|| {
153                     self.g
154                         .edges
155                         .iter()
156                         .map(|n| n.weight.as_ref())
157                         .enumerate()
158                         .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
159                 }),
160             );
161         }
162         fmt_struct.field("free_node", &self.free_node);
163         fmt_struct.field("free_edge", &self.free_edge);
164         fmt_struct.finish()
165     }
166 }
167 
168 impl<N, E> StableGraph<N, E, Directed> {
169     /// Create a new `StableGraph` with directed edges.
170     ///
171     /// This is a convenience method. See `StableGraph::with_capacity`
172     /// or `StableGraph::default` for a constructor that is generic in all the
173     /// type parameters of `StableGraph`.
new() -> Self174     pub fn new() -> Self {
175         Self::with_capacity(0, 0)
176     }
177 }
178 
179 impl<N, E, Ty, Ix> StableGraph<N, E, Ty, Ix>
180 where
181     Ty: EdgeType,
182     Ix: IndexType,
183 {
184     /// Create a new `StableGraph` with estimated capacity.
with_capacity(nodes: usize, edges: usize) -> Self185     pub fn with_capacity(nodes: usize, edges: usize) -> Self {
186         StableGraph {
187             g: Graph::with_capacity(nodes, edges),
188             node_count: 0,
189             edge_count: 0,
190             free_node: NodeIndex::end(),
191             free_edge: EdgeIndex::end(),
192         }
193     }
194 
195     /// Return the current node and edge capacity of the graph.
capacity(&self) -> (usize, usize)196     pub fn capacity(&self) -> (usize, usize) {
197         self.g.capacity()
198     }
199 
200     /// Reverse the direction of all edges
reverse(&mut self)201     pub fn reverse(&mut self) {
202         // swap edge endpoints,
203         // edge incoming / outgoing lists,
204         // node incoming / outgoing lists
205         for edge in &mut self.g.edges {
206             edge.node.swap(0, 1);
207             edge.next.swap(0, 1);
208         }
209         for node in &mut self.g.nodes {
210             node.next.swap(0, 1);
211         }
212     }
213 
214     /// Remove all nodes and edges
clear(&mut self)215     pub fn clear(&mut self) {
216         self.node_count = 0;
217         self.edge_count = 0;
218         self.free_node = NodeIndex::end();
219         self.free_edge = EdgeIndex::end();
220         self.g.clear();
221     }
222 
223     /// Remove all edges
clear_edges(&mut self)224     pub fn clear_edges(&mut self) {
225         self.edge_count = 0;
226         self.free_edge = EdgeIndex::end();
227         self.g.edges.clear();
228         // clear edges without touching the free list
229         for node in &mut self.g.nodes {
230             if node.weight.is_some() {
231                 node.next = [EdgeIndex::end(), EdgeIndex::end()];
232             }
233         }
234     }
235 
236     /// Return the number of nodes (vertices) in the graph.
237     ///
238     /// Computes in **O(1)** time.
node_count(&self) -> usize239     pub fn node_count(&self) -> usize {
240         self.node_count
241     }
242 
243     /// Return the number of edges in the graph.
244     ///
245     /// Computes in **O(1)** time.
edge_count(&self) -> usize246     pub fn edge_count(&self) -> usize {
247         self.edge_count
248     }
249 
250     /// Whether the graph has directed edges or not.
251     #[inline]
is_directed(&self) -> bool252     pub fn is_directed(&self) -> bool {
253         Ty::is_directed()
254     }
255 
256     /// Add a node (also called vertex) with associated data `weight` to the graph.
257     ///
258     /// Computes in **O(1)** time.
259     ///
260     /// Return the index of the new node.
261     ///
262     /// **Panics** if the `StableGraph` is at the maximum number of nodes for
263     /// its index type.
add_node(&mut self, weight: N) -> NodeIndex<Ix>264     pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
265         if self.free_node != NodeIndex::end() {
266             let node_idx = self.free_node;
267             self.occupy_vacant_node(node_idx, weight);
268             node_idx
269         } else {
270             self.node_count += 1;
271             self.g.add_node(Some(weight))
272         }
273     }
274 
275     /// free_node: Which free list to update for the vacancy
add_vacant_node(&mut self, free_node: &mut NodeIndex<Ix>)276     fn add_vacant_node(&mut self, free_node: &mut NodeIndex<Ix>) {
277         let node_idx = self.g.add_node(None);
278         // link the free list
279         let node_slot = &mut self.g.nodes[node_idx.index()];
280         node_slot.next = [free_node._into_edge(), EdgeIndex::end()];
281         if *free_node != NodeIndex::end() {
282             self.g.nodes[free_node.index()].next[1] = node_idx._into_edge();
283         }
284         *free_node = node_idx;
285     }
286 
287     /// Remove `a` from the graph if it exists, and return its weight.
288     /// If it doesn't exist in the graph, return `None`.
289     ///
290     /// The node index `a` is invalidated, but none other.
291     /// Edge indices are invalidated as they would be following the removal of
292     /// each edge with an endpoint in `a`.
293     ///
294     /// Computes in **O(e')** time, where **e'** is the number of affected
295     /// edges, including *n* calls to `.remove_edge()` where *n* is the number
296     /// of edges with an endpoint in `a`.
remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N>297     pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N> {
298         let node_weight = self.g.nodes.get_mut(a.index())?.weight.take()?;
299         for d in &DIRECTIONS {
300             let k = d.index();
301 
302             // Remove all edges from and to this node.
303             loop {
304                 let next = self.g.nodes[a.index()].next[k];
305                 if next == EdgeIndex::end() {
306                     break;
307                 }
308                 let ret = self.remove_edge(next);
309                 debug_assert!(ret.is_some());
310                 let _ = ret;
311             }
312         }
313 
314         let node_slot = &mut self.g.nodes[a.index()];
315         //let node_weight = replace(&mut self.g.nodes[a.index()].weight, Entry::Empty(self.free_node));
316         //self.g.nodes[a.index()].next = [EdgeIndex::end(), EdgeIndex::end()];
317         node_slot.next = [self.free_node._into_edge(), EdgeIndex::end()];
318         if self.free_node != NodeIndex::end() {
319             self.g.nodes[self.free_node.index()].next[1] = a._into_edge();
320         }
321         self.free_node = a;
322         self.node_count -= 1;
323 
324         Some(node_weight)
325     }
326 
contains_node(&self, a: NodeIndex<Ix>) -> bool327     pub fn contains_node(&self, a: NodeIndex<Ix>) -> bool {
328         self.get_node(a).is_some()
329     }
330 
331     // Return the Node if it is not vacant (non-None weight)
get_node(&self, a: NodeIndex<Ix>) -> Option<&Node<Option<N>, Ix>>332     fn get_node(&self, a: NodeIndex<Ix>) -> Option<&Node<Option<N>, Ix>> {
333         self.g
334             .nodes
335             .get(a.index())
336             .and_then(|node| node.weight.as_ref().map(move |_| node))
337     }
338 
339     /// Add an edge from `a` to `b` to the graph, with its associated
340     /// data `weight`.
341     ///
342     /// Return the index of the new edge.
343     ///
344     /// Computes in **O(1)** time.
345     ///
346     /// **Panics** if any of the nodes don't exist.<br>
347     /// **Panics** if the `StableGraph` is at the maximum number of edges for
348     /// its index type.
349     ///
350     /// **Note:** `StableGraph` allows adding parallel (“duplicate”) edges.
add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix>351     pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
352         let edge_idx;
353         let mut new_edge = None::<Edge<_, _>>;
354         {
355             let edge: &mut Edge<_, _>;
356 
357             if self.free_edge != EdgeIndex::end() {
358                 edge_idx = self.free_edge;
359                 edge = &mut self.g.edges[edge_idx.index()];
360                 let _old = replace(&mut edge.weight, Some(weight));
361                 debug_assert!(_old.is_none());
362                 self.free_edge = edge.next[0];
363                 edge.node = [a, b];
364             } else {
365                 edge_idx = EdgeIndex::new(self.g.edges.len());
366                 assert!(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx);
367                 new_edge = Some(Edge {
368                     weight: Some(weight),
369                     node: [a, b],
370                     next: [EdgeIndex::end(); 2],
371                 });
372                 edge = new_edge.as_mut().unwrap();
373             }
374 
375             let wrong_index = match index_twice(&mut self.g.nodes, a.index(), b.index()) {
376                 Pair::None => Some(cmp::max(a.index(), b.index())),
377                 Pair::One(an) => {
378                     if an.weight.is_none() {
379                         Some(a.index())
380                     } else {
381                         edge.next = an.next;
382                         an.next[0] = edge_idx;
383                         an.next[1] = edge_idx;
384                         None
385                     }
386                 }
387                 Pair::Both(an, bn) => {
388                     // a and b are different indices
389                     if an.weight.is_none() {
390                         Some(a.index())
391                     } else if bn.weight.is_none() {
392                         Some(b.index())
393                     } else {
394                         edge.next = [an.next[0], bn.next[1]];
395                         an.next[0] = edge_idx;
396                         bn.next[1] = edge_idx;
397                         None
398                     }
399                 }
400             };
401             if let Some(i) = wrong_index {
402                 panic!(
403                     "StableGraph::add_edge: node index {} is not a node in the graph",
404                     i
405                 );
406             }
407             self.edge_count += 1;
408         }
409         if let Some(edge) = new_edge {
410             self.g.edges.push(edge);
411         }
412         edge_idx
413     }
414 
415     /// free_edge: Which free list to update for the vacancy
add_vacant_edge(&mut self, free_edge: &mut EdgeIndex<Ix>)416     fn add_vacant_edge(&mut self, free_edge: &mut EdgeIndex<Ix>) {
417         let edge_idx = EdgeIndex::new(self.g.edges.len());
418         debug_assert!(edge_idx != EdgeIndex::end());
419         let mut edge = Edge {
420             weight: None,
421             node: [NodeIndex::end(); 2],
422             next: [EdgeIndex::end(); 2],
423         };
424         edge.next[0] = *free_edge;
425         *free_edge = edge_idx;
426         self.g.edges.push(edge);
427     }
428 
429     /// Add or update an edge from `a` to `b`.
430     /// If the edge already exists, its weight is updated.
431     ///
432     /// Return the index of the affected edge.
433     ///
434     /// Computes in **O(e')** time, where **e'** is the number of edges
435     /// connected to `a` (and `b`, if the graph edges are undirected).
436     ///
437     /// **Panics** if any of the nodes don't exist.
update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix>438     pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
439         if let Some(ix) = self.find_edge(a, b) {
440             self[ix] = weight;
441             return ix;
442         }
443         self.add_edge(a, b, weight)
444     }
445 
446     /// Remove an edge and return its edge weight, or `None` if it didn't exist.
447     ///
448     /// Invalidates the edge index `e` but no other.
449     ///
450     /// Computes in **O(e')** time, where **e'** is the number of edges
451     /// connected to the same endpoints as `e`.
remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E>452     pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
453         // every edge is part of two lists,
454         // outgoing and incoming edges.
455         // Remove it from both
456         let (is_edge, edge_node, edge_next) = match self.g.edges.get(e.index()) {
457             None => return None,
458             Some(x) => (x.weight.is_some(), x.node, x.next),
459         };
460         if !is_edge {
461             return None;
462         }
463 
464         // Remove the edge from its in and out lists by replacing it with
465         // a link to the next in the list.
466         self.g.change_edge_links(edge_node, e, edge_next);
467 
468         // Clear the edge and put it in the free list
469         let edge = &mut self.g.edges[e.index()];
470         edge.next = [self.free_edge, EdgeIndex::end()];
471         edge.node = [NodeIndex::end(), NodeIndex::end()];
472         self.free_edge = e;
473         self.edge_count -= 1;
474         edge.weight.take()
475     }
476 
477     /// Access the weight for node `a`.
478     ///
479     /// Also available with indexing syntax: `&graph[a]`.
node_weight(&self, a: NodeIndex<Ix>) -> Option<&N>480     pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
481         match self.g.nodes.get(a.index()) {
482             Some(no) => no.weight.as_ref(),
483             None => None,
484         }
485     }
486 
487     /// Access the weight for node `a`, mutably.
488     ///
489     /// Also available with indexing syntax: `&mut graph[a]`.
node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N>490     pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
491         match self.g.nodes.get_mut(a.index()) {
492             Some(no) => no.weight.as_mut(),
493             None => None,
494         }
495     }
496 
497     /// Return an iterator yielding immutable access to all node weights.
498     ///
499     /// The order in which weights are yielded matches the order of their node
500     /// indices.
node_weights(&self) -> impl Iterator<Item = &N>501     pub fn node_weights(&self) -> impl Iterator<Item = &N> {
502         self.g
503             .node_weights()
504             .filter_map(|maybe_node| maybe_node.as_ref())
505     }
506     /// Return an iterator yielding mutable access to all node weights.
507     ///
508     /// The order in which weights are yielded matches the order of their node
509     /// indices.
node_weights_mut(&mut self) -> impl Iterator<Item = &mut N>510     pub fn node_weights_mut(&mut self) -> impl Iterator<Item = &mut N> {
511         self.g
512             .node_weights_mut()
513             .filter_map(|maybe_node| maybe_node.as_mut())
514     }
515 
516     /// Return an iterator over the node indices of the graph
node_indices(&self) -> NodeIndices<N, Ix>517     pub fn node_indices(&self) -> NodeIndices<N, Ix> {
518         NodeIndices {
519             iter: enumerate(self.raw_nodes()),
520         }
521     }
522 
523     /// Access the weight for edge `e`.
524     ///
525     /// Also available with indexing syntax: `&graph[e]`.
edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E>526     pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
527         match self.g.edges.get(e.index()) {
528             Some(ed) => ed.weight.as_ref(),
529             None => None,
530         }
531     }
532 
533     /// Access the weight for edge `e`, mutably
534     ///
535     /// Also available with indexing syntax: `&mut graph[e]`.
edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E>536     pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
537         match self.g.edges.get_mut(e.index()) {
538             Some(ed) => ed.weight.as_mut(),
539             None => None,
540         }
541     }
542 
543     /// Return an iterator yielding immutable access to all edge weights.
544     ///
545     /// The order in which weights are yielded matches the order of their edge
546     /// indices.
edge_weights(&self) -> impl Iterator<Item = &E>547     pub fn edge_weights(&self) -> impl Iterator<Item = &E> {
548         self.g
549             .edge_weights()
550             .filter_map(|maybe_edge| maybe_edge.as_ref())
551     }
552     /// Return an iterator yielding mutable access to all edge weights.
553     ///
554     /// The order in which weights are yielded matches the order of their edge
555     /// indices.
edge_weights_mut(&mut self) -> impl Iterator<Item = &mut E>556     pub fn edge_weights_mut(&mut self) -> impl Iterator<Item = &mut E> {
557         self.g
558             .edge_weights_mut()
559             .filter_map(|maybe_edge| maybe_edge.as_mut())
560     }
561 
562     /// Access the source and target nodes for `e`.
edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)>563     pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)> {
564         match self.g.edges.get(e.index()) {
565             Some(ed) if ed.weight.is_some() => Some((ed.source(), ed.target())),
566             _otherwise => None,
567         }
568     }
569 
570     /// Return an iterator over the edge indices of the graph
edge_indices(&self) -> EdgeIndices<E, Ix>571     pub fn edge_indices(&self) -> EdgeIndices<E, Ix> {
572         EdgeIndices {
573             iter: enumerate(self.raw_edges()),
574         }
575     }
576 
577     /// Return an iterator over all the edges connecting `a` and `b`.
578     ///
579     /// - `Directed`: Outgoing edges from `a`.
580     /// - `Undirected`: All edges connected to `a`.
581     ///
582     /// Iterator element type is `EdgeReference<E, Ix>`.
edges_connecting( &self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, ) -> EdgesConnecting<E, Ty, Ix>583     pub fn edges_connecting(
584         &self,
585         a: NodeIndex<Ix>,
586         b: NodeIndex<Ix>,
587     ) -> EdgesConnecting<E, Ty, Ix> {
588         EdgesConnecting {
589             target_node: b,
590             edges: self.edges_directed(a, Direction::Outgoing),
591             ty: PhantomData,
592         }
593     }
594 
595     /// Lookup if there is an edge from `a` to `b`.
596     ///
597     /// Computes in **O(e')** time, where **e'** is the number of edges
598     /// connected to `a` (and `b`, if the graph edges are undirected).
contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool599     pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
600         self.find_edge(a, b).is_some()
601     }
602 
603     /// Lookup an edge from `a` to `b`.
604     ///
605     /// Computes in **O(e')** time, where **e'** is the number of edges
606     /// connected to `a` (and `b`, if the graph edges are undirected).
find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>>607     pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>> {
608         if !self.is_directed() {
609             self.find_edge_undirected(a, b).map(|(ix, _)| ix)
610         } else {
611             match self.get_node(a) {
612                 None => None,
613                 Some(node) => self.g.find_edge_directed_from_node(node, b),
614             }
615         }
616     }
617 
618     /// Lookup an edge between `a` and `b`, in either direction.
619     ///
620     /// If the graph is undirected, then this is equivalent to `.find_edge()`.
621     ///
622     /// Return the edge index and its directionality, with `Outgoing` meaning
623     /// from `a` to `b` and `Incoming` the reverse,
624     /// or `None` if the edge does not exist.
find_edge_undirected( &self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, ) -> Option<(EdgeIndex<Ix>, Direction)>625     pub fn find_edge_undirected(
626         &self,
627         a: NodeIndex<Ix>,
628         b: NodeIndex<Ix>,
629     ) -> Option<(EdgeIndex<Ix>, Direction)> {
630         match self.get_node(a) {
631             None => None,
632             Some(node) => self.g.find_edge_undirected_from_node(node, b),
633         }
634     }
635 
636     /// Return an iterator of all nodes with an edge starting from `a`.
637     ///
638     /// - `Directed`: Outgoing edges from `a`.
639     /// - `Undirected`: All edges connected to `a`.
640     ///
641     /// Produces an empty iterator if the node doesn't exist.<br>
642     /// Iterator element type is `NodeIndex<Ix>`.
643     ///
644     /// Use [`.neighbors(a).detach()`][1] to get a neighbor walker that does
645     /// not borrow from the graph.
646     ///
647     /// [1]: struct.Neighbors.html#method.detach
neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix>648     pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
649         self.neighbors_directed(a, Outgoing)
650     }
651 
652     /// Return an iterator of all neighbors that have an edge between them and `a`,
653     /// in the specified direction.
654     /// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
655     ///
656     /// - `Directed`, `Outgoing`: All edges from `a`.
657     /// - `Directed`, `Incoming`: All edges to `a`.
658     /// - `Undirected`: All edges connected to `a`.
659     ///
660     /// Produces an empty iterator if the node doesn't exist.<br>
661     /// Iterator element type is `NodeIndex<Ix>`.
662     ///
663     /// Use [`.neighbors_directed(a, dir).detach()`][1] to get a neighbor walker that does
664     /// not borrow from the graph.
665     ///
666     /// [1]: struct.Neighbors.html#method.detach
neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix>667     pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix> {
668         let mut iter = self.neighbors_undirected(a);
669         if self.is_directed() {
670             let k = dir.index();
671             iter.next[1 - k] = EdgeIndex::end();
672             iter.skip_start = NodeIndex::end();
673         }
674         iter
675     }
676 
677     /// Return an iterator of all neighbors that have an edge between them and `a`,
678     /// in either direction.
679     /// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
680     ///
681     /// - `Directed` and `Undirected`: All edges connected to `a`.
682     ///
683     /// Produces an empty iterator if the node doesn't exist.<br>
684     /// Iterator element type is `NodeIndex<Ix>`.
685     ///
686     /// Use [`.neighbors_undirected(a).detach()`][1] to get a neighbor walker that does
687     /// not borrow from the graph.
688     ///
689     /// [1]: struct.Neighbors.html#method.detach
neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix>690     pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
691         Neighbors {
692             skip_start: a,
693             edges: &self.g.edges,
694             next: match self.get_node(a) {
695                 None => [EdgeIndex::end(), EdgeIndex::end()],
696                 Some(n) => n.next,
697             },
698         }
699     }
700 
701     /// Return an iterator of all edges of `a`.
702     ///
703     /// - `Directed`: Outgoing edges from `a`.
704     /// - `Undirected`: All edges connected to `a`.
705     ///
706     /// Produces an empty iterator if the node doesn't exist.<br>
707     /// Iterator element type is `EdgeReference<E, Ix>`.
edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix>708     pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
709         self.edges_directed(a, Outgoing)
710     }
711 
712     /// Return an iterator of all edges of `a`, in the specified direction.
713     ///
714     /// - `Directed`, `Outgoing`: All edges from `a`.
715     /// - `Directed`, `Incoming`: All edges to `a`.
716     /// - `Undirected`, `Outgoing`: All edges connected to `a`, with `a` being the source of each
717     ///   edge.
718     /// - `Undirected`, `Incoming`: All edges connected to `a`, with `a` being the target of each
719     ///   edge.
720     ///
721     /// Produces an empty iterator if the node `a` doesn't exist.<br>
722     /// Iterator element type is `EdgeReference<E, Ix>`.
edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix>723     pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix> {
724         Edges {
725             skip_start: a,
726             edges: &self.g.edges,
727             direction: dir,
728             next: match self.get_node(a) {
729                 None => [EdgeIndex::end(), EdgeIndex::end()],
730                 Some(n) => n.next,
731             },
732             ty: PhantomData,
733         }
734     }
735 
736     /// Return an iterator over either the nodes without edges to them
737     /// (`Incoming`) or from them (`Outgoing`).
738     ///
739     /// An *internal* node has both incoming and outgoing edges.
740     /// The nodes in `.externals(Incoming)` are the source nodes and
741     /// `.externals(Outgoing)` are the sinks of the graph.
742     ///
743     /// For a graph with undirected edges, both the sinks and the sources are
744     /// just the nodes without edges.
745     ///
746     /// The whole iteration computes in **O(|V|)** time.
externals(&self, dir: Direction) -> Externals<N, Ty, Ix>747     pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix> {
748         Externals {
749             iter: self.raw_nodes().iter().enumerate(),
750             dir,
751             ty: PhantomData,
752         }
753     }
754 
755     /// Index the `StableGraph` by two indices, any combination of
756     /// node or edge indices is fine.
757     ///
758     /// **Panics** if the indices are equal or if they are out of bounds.
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,759     pub fn index_twice_mut<T, U>(
760         &mut self,
761         i: T,
762         j: U,
763     ) -> (
764         &mut <Self as Index<T>>::Output,
765         &mut <Self as Index<U>>::Output,
766     )
767     where
768         Self: IndexMut<T> + IndexMut<U>,
769         T: GraphIndex,
770         U: GraphIndex,
771     {
772         assert!(T::is_node_index() != U::is_node_index() || i.index() != j.index());
773 
774         // Allow two mutable indexes here -- they are nonoverlapping
775         unsafe {
776             let self_mut = self as *mut _;
777             (
778                 <Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
779                 <Self as IndexMut<U>>::index_mut(&mut *self_mut, j),
780             )
781         }
782     }
783 
784     /// Keep all nodes that return `true` from the `visit` closure,
785     /// remove the others.
786     ///
787     /// `visit` is provided a proxy reference to the graph, so that
788     /// the graph can be walked and associated data modified.
789     ///
790     /// The order nodes are visited is not specified.
791     ///
792     /// The node indices of the removed nodes are invalidated, but none other.
793     /// Edge indices are invalidated as they would be following the removal of
794     /// each edge with an endpoint in a removed node.
795     ///
796     /// Computes in **O(n + e')** time, where **n** is the number of node indices and
797     ///  **e'** is the number of affected edges, including *n* calls to `.remove_edge()`
798     /// where *n* is the number of edges with an endpoint in a removed node.
retain_nodes<F>(&mut self, mut visit: F) where F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,799     pub fn retain_nodes<F>(&mut self, mut visit: F)
800     where
801         F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,
802     {
803         for i in 0..self.node_bound() {
804             let ix = node_index(i);
805             if self.contains_node(ix) && !visit(Frozen(self), ix) {
806                 self.remove_node(ix);
807             }
808         }
809         self.check_free_lists();
810     }
811 
812     /// Keep all edges that return `true` from the `visit` closure,
813     /// remove the others.
814     ///
815     /// `visit` is provided a proxy reference to the graph, so that
816     /// the graph can be walked and associated data modified.
817     ///
818     /// The order edges are visited is not specified.
819     ///
820     /// The edge indices of the removed edes are invalidated, but none other.
821     ///
822     /// Computes in **O(e'')** time, **e'** is the number of affected edges,
823     /// including the calls to `.remove_edge()` for each removed edge.
retain_edges<F>(&mut self, mut visit: F) where F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,824     pub fn retain_edges<F>(&mut self, mut visit: F)
825     where
826         F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,
827     {
828         for i in 0..self.edge_bound() {
829             let ix = edge_index(i);
830             if self.edge_weight(ix).is_some() && !visit(Frozen(self), ix) {
831                 self.remove_edge(ix);
832             }
833         }
834         self.check_free_lists();
835     }
836 
837     /// Create a new `StableGraph` from an iterable of edges.
838     ///
839     /// Node weights `N` are set to default values.
840     /// Edge weights `E` may either be specified in the list,
841     /// or they are filled with default values.
842     ///
843     /// Nodes are inserted automatically to match the edges.
844     ///
845     /// ```
846     /// use petgraph::stable_graph::StableGraph;
847     ///
848     /// let gr = StableGraph::<(), i32>::from_edges(&[
849     ///     (0, 1), (0, 2), (0, 3),
850     ///     (1, 2), (1, 3),
851     ///     (2, 3),
852     /// ]);
853     /// ```
from_edges<I>(iterable: I) -> Self where I: IntoIterator, I::Item: IntoWeightedEdge<E>, <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>, N: Default,854     pub fn from_edges<I>(iterable: I) -> Self
855     where
856         I: IntoIterator,
857         I::Item: IntoWeightedEdge<E>,
858         <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
859         N: Default,
860     {
861         let mut g = Self::with_capacity(0, 0);
862         g.extend_with_edges(iterable);
863         g
864     }
865 
866     /// Create a new `StableGraph` by mapping node and
867     /// edge weights to new values.
868     ///
869     /// The resulting graph has the same structure and the same
870     /// graph indices as `self`.
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,871     pub fn map<'a, F, G, N2, E2>(
872         &'a self,
873         mut node_map: F,
874         mut edge_map: G,
875     ) -> StableGraph<N2, E2, Ty, Ix>
876     where
877         F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
878         G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
879     {
880         let g = self.g.map(
881             move |i, w| w.as_ref().map(|w| node_map(i, w)),
882             move |i, w| w.as_ref().map(|w| edge_map(i, w)),
883         );
884         StableGraph {
885             g,
886             node_count: self.node_count,
887             edge_count: self.edge_count,
888             free_node: self.free_node,
889             free_edge: self.free_edge,
890         }
891     }
892 
893     /// Create a new `StableGraph` by mapping nodes and edges.
894     /// A node or edge may be mapped to `None` to exclude it from
895     /// the resulting graph.
896     ///
897     /// Nodes are mapped first with the `node_map` closure, then
898     /// `edge_map` is called for the edges that have not had any endpoint
899     /// removed.
900     ///
901     /// The resulting graph has the structure of a subgraph of the original graph.
902     /// Nodes and edges that are not removed maintain their old node or edge
903     /// indices.
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>,904     pub fn filter_map<'a, F, G, N2, E2>(
905         &'a self,
906         mut node_map: F,
907         mut edge_map: G,
908     ) -> StableGraph<N2, E2, Ty, Ix>
909     where
910         F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
911         G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
912     {
913         let node_bound = self.node_bound();
914         let edge_bound = self.edge_bound();
915         let mut result_g = StableGraph::with_capacity(node_bound, edge_bound);
916         // use separate free lists so that
917         // add_node / add_edge below do not reuse the tombstones
918         let mut free_node = NodeIndex::end();
919         let mut free_edge = EdgeIndex::end();
920 
921         // the stable graph keeps the node map itself
922 
923         for (i, node) in enumerate(self.raw_nodes()) {
924             if i >= node_bound {
925                 break;
926             }
927             if let Some(node_weight) = node.weight.as_ref() {
928                 if let Some(new_weight) = node_map(NodeIndex::new(i), node_weight) {
929                     result_g.add_node(new_weight);
930                     continue;
931                 }
932             }
933             result_g.add_vacant_node(&mut free_node);
934         }
935         for (i, edge) in enumerate(self.raw_edges()) {
936             if i >= edge_bound {
937                 break;
938             }
939             let source = edge.source();
940             let target = edge.target();
941             if let Some(edge_weight) = edge.weight.as_ref() {
942                 if result_g.contains_node(source) && result_g.contains_node(target) {
943                     if let Some(new_weight) = edge_map(EdgeIndex::new(i), edge_weight) {
944                         result_g.add_edge(source, target, new_weight);
945                         continue;
946                     }
947                 }
948             }
949             result_g.add_vacant_edge(&mut free_edge);
950         }
951         result_g.free_node = free_node;
952         result_g.free_edge = free_edge;
953         result_g.check_free_lists();
954         result_g
955     }
956 
957     /// Extend the graph from an iterable of edges.
958     ///
959     /// Node weights `N` are set to default values.
960     /// Edge weights `E` may either be specified in the list,
961     /// or they are filled with default values.
962     ///
963     /// Nodes are inserted automatically to match the edges.
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,964     pub fn extend_with_edges<I>(&mut self, iterable: I)
965     where
966         I: IntoIterator,
967         I::Item: IntoWeightedEdge<E>,
968         <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
969         N: Default,
970     {
971         let iter = iterable.into_iter();
972 
973         for elt in iter {
974             let (source, target, weight) = elt.into_weighted_edge();
975             let (source, target) = (source.into(), target.into());
976             self.ensure_node_exists(source);
977             self.ensure_node_exists(target);
978             self.add_edge(source, target, weight);
979         }
980     }
981 
982     //
983     // internal methods
984     //
raw_nodes(&self) -> &[Node<Option<N>, Ix>]985     fn raw_nodes(&self) -> &[Node<Option<N>, Ix>] {
986         self.g.raw_nodes()
987     }
988 
raw_edges(&self) -> &[Edge<Option<E>, Ix>]989     fn raw_edges(&self) -> &[Edge<Option<E>, Ix>] {
990         self.g.raw_edges()
991     }
992 
993     /// Create a new node using a vacant position,
994     /// updating the free nodes doubly linked list.
occupy_vacant_node(&mut self, node_idx: NodeIndex<Ix>, weight: N)995     fn occupy_vacant_node(&mut self, node_idx: NodeIndex<Ix>, weight: N) {
996         let node_slot = &mut self.g.nodes[node_idx.index()];
997         let _old = replace(&mut node_slot.weight, Some(weight));
998         debug_assert!(_old.is_none());
999         let previous_node = node_slot.next[1];
1000         let next_node = node_slot.next[0];
1001         node_slot.next = [EdgeIndex::end(), EdgeIndex::end()];
1002         if previous_node != EdgeIndex::end() {
1003             self.g.nodes[previous_node.index()].next[0] = next_node;
1004         }
1005         if next_node != EdgeIndex::end() {
1006             self.g.nodes[next_node.index()].next[1] = previous_node;
1007         }
1008         if self.free_node == node_idx {
1009             self.free_node = next_node._into_node();
1010         }
1011         self.node_count += 1;
1012     }
1013 
1014     /// Create the node if it does not exist,
1015     /// adding vacant nodes for padding if needed.
ensure_node_exists(&mut self, node_ix: NodeIndex<Ix>) where N: Default,1016     fn ensure_node_exists(&mut self, node_ix: NodeIndex<Ix>)
1017     where
1018         N: Default,
1019     {
1020         if let Some(Some(_)) = self.g.node_weight(node_ix) {
1021             return;
1022         }
1023         while node_ix.index() >= self.g.node_count() {
1024             let mut free_node = self.free_node;
1025             self.add_vacant_node(&mut free_node);
1026             self.free_node = free_node;
1027         }
1028         self.occupy_vacant_node(node_ix, N::default());
1029     }
1030 
1031     #[cfg(feature = "serde-1")]
1032     /// Fix up node and edge links after deserialization
link_edges(&mut self) -> Result<(), NodeIndex<Ix>>1033     fn link_edges(&mut self) -> Result<(), NodeIndex<Ix>> {
1034         // set up free node list
1035         self.node_count = 0;
1036         self.edge_count = 0;
1037         let mut free_node = NodeIndex::end();
1038         for node_index in 0..self.g.node_count() {
1039             let node = &mut self.g.nodes[node_index];
1040             if node.weight.is_some() {
1041                 self.node_count += 1;
1042             } else {
1043                 // free node
1044                 node.next = [free_node._into_edge(), EdgeIndex::end()];
1045                 if free_node != NodeIndex::end() {
1046                     self.g.nodes[free_node.index()].next[1] = EdgeIndex::new(node_index);
1047                 }
1048                 free_node = NodeIndex::new(node_index);
1049             }
1050         }
1051         self.free_node = free_node;
1052 
1053         let mut free_edge = EdgeIndex::end();
1054         for (edge_index, edge) in enumerate(&mut self.g.edges) {
1055             if edge.weight.is_none() {
1056                 // free edge
1057                 edge.next = [free_edge, EdgeIndex::end()];
1058                 free_edge = EdgeIndex::new(edge_index);
1059                 continue;
1060             }
1061             let a = edge.source();
1062             let b = edge.target();
1063             let edge_idx = EdgeIndex::new(edge_index);
1064             match index_twice(&mut self.g.nodes, a.index(), b.index()) {
1065                 Pair::None => return Err(if a > b { a } else { b }),
1066                 Pair::One(an) => {
1067                     edge.next = an.next;
1068                     an.next[0] = edge_idx;
1069                     an.next[1] = edge_idx;
1070                 }
1071                 Pair::Both(an, bn) => {
1072                     // a and b are different indices
1073                     edge.next = [an.next[0], bn.next[1]];
1074                     an.next[0] = edge_idx;
1075                     bn.next[1] = edge_idx;
1076                 }
1077             }
1078             self.edge_count += 1;
1079         }
1080         self.free_edge = free_edge;
1081         Ok(())
1082     }
1083 
1084     #[cfg(not(debug_assertions))]
check_free_lists(&self)1085     fn check_free_lists(&self) {}
1086     #[cfg(debug_assertions)]
1087     // internal method to debug check the free lists (linked lists)
1088     // For the nodes, also check the backpointers of the doubly linked list.
check_free_lists(&self)1089     fn check_free_lists(&self) {
1090         let mut free_node = self.free_node;
1091         let mut prev_free_node = NodeIndex::end();
1092         let mut free_node_len = 0;
1093         while free_node != NodeIndex::end() {
1094             if let Some(n) = self.g.nodes.get(free_node.index()) {
1095                 if n.weight.is_none() {
1096                     debug_assert_eq!(n.next[1]._into_node(), prev_free_node);
1097                     prev_free_node = free_node;
1098                     free_node = n.next[0]._into_node();
1099                     free_node_len += 1;
1100                     continue;
1101                 }
1102                 debug_assert!(
1103                     false,
1104                     "Corrupt free list: pointing to existing {:?}",
1105                     free_node.index()
1106                 );
1107             }
1108             debug_assert!(false, "Corrupt free list: missing {:?}", free_node.index());
1109         }
1110         debug_assert_eq!(self.node_count(), self.raw_nodes().len() - free_node_len);
1111 
1112         let mut free_edge_len = 0;
1113         let mut free_edge = self.free_edge;
1114         while free_edge != EdgeIndex::end() {
1115             if let Some(n) = self.g.edges.get(free_edge.index()) {
1116                 if n.weight.is_none() {
1117                     free_edge = n.next[0];
1118                     free_edge_len += 1;
1119                     continue;
1120                 }
1121                 debug_assert!(
1122                     false,
1123                     "Corrupt free list: pointing to existing {:?}",
1124                     free_node.index()
1125                 );
1126             }
1127             debug_assert!(false, "Corrupt free list: missing {:?}", free_edge.index());
1128         }
1129         debug_assert_eq!(self.edge_count(), self.raw_edges().len() - free_edge_len);
1130     }
1131 }
1132 
1133 /// The resulting cloned graph has the same graph indices as `self`.
1134 impl<N, E, Ty, Ix: IndexType> Clone for StableGraph<N, E, Ty, Ix>
1135 where
1136     N: Clone,
1137     E: Clone,
1138 {
clone(&self) -> Self1139     fn clone(&self) -> Self {
1140         StableGraph {
1141             g: self.g.clone(),
1142             node_count: self.node_count,
1143             edge_count: self.edge_count,
1144             free_node: self.free_node,
1145             free_edge: self.free_edge,
1146         }
1147     }
1148 
clone_from(&mut self, rhs: &Self)1149     fn clone_from(&mut self, rhs: &Self) {
1150         self.g.clone_from(&rhs.g);
1151         self.node_count = rhs.node_count;
1152         self.edge_count = rhs.edge_count;
1153         self.free_node = rhs.free_node;
1154         self.free_edge = rhs.free_edge;
1155     }
1156 }
1157 
1158 /// Index the `StableGraph` by `NodeIndex` to access node weights.
1159 ///
1160 /// **Panics** if the node doesn't exist.
1161 impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1162 where
1163     Ty: EdgeType,
1164     Ix: IndexType,
1165 {
1166     type Output = N;
index(&self, index: NodeIndex<Ix>) -> &N1167     fn index(&self, index: NodeIndex<Ix>) -> &N {
1168         self.node_weight(index).unwrap()
1169     }
1170 }
1171 
1172 /// Index the `StableGraph` by `NodeIndex` to access node weights.
1173 ///
1174 /// **Panics** if the node doesn't exist.
1175 impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1176 where
1177     Ty: EdgeType,
1178     Ix: IndexType,
1179 {
index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N1180     fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1181         self.node_weight_mut(index).unwrap()
1182     }
1183 }
1184 
1185 /// Index the `StableGraph` by `EdgeIndex` to access edge weights.
1186 ///
1187 /// **Panics** if the edge doesn't exist.
1188 impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1189 where
1190     Ty: EdgeType,
1191     Ix: IndexType,
1192 {
1193     type Output = E;
index(&self, index: EdgeIndex<Ix>) -> &E1194     fn index(&self, index: EdgeIndex<Ix>) -> &E {
1195         self.edge_weight(index).unwrap()
1196     }
1197 }
1198 
1199 /// Index the `StableGraph` by `EdgeIndex` to access edge weights.
1200 ///
1201 /// **Panics** if the edge doesn't exist.
1202 impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1203 where
1204     Ty: EdgeType,
1205     Ix: IndexType,
1206 {
index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E1207     fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
1208         self.edge_weight_mut(index).unwrap()
1209     }
1210 }
1211 
1212 /// Create a new empty `StableGraph`.
1213 impl<N, E, Ty, Ix> Default for StableGraph<N, E, Ty, Ix>
1214 where
1215     Ty: EdgeType,
1216     Ix: IndexType,
1217 {
default() -> Self1218     fn default() -> Self {
1219         Self::with_capacity(0, 0)
1220     }
1221 }
1222 
1223 /// Convert a `Graph` into a `StableGraph`
1224 ///
1225 /// Computes in **O(|V| + |E|)** time.
1226 ///
1227 /// The resulting graph has the same node and edge indices as
1228 /// the original graph.
1229 impl<N, E, Ty, Ix> From<Graph<N, E, Ty, Ix>> for StableGraph<N, E, Ty, Ix>
1230 where
1231     Ty: EdgeType,
1232     Ix: IndexType,
1233 {
from(g: Graph<N, E, Ty, Ix>) -> Self1234     fn from(g: Graph<N, E, Ty, Ix>) -> Self {
1235         let nodes = g.nodes.into_iter().map(|e| Node {
1236             weight: Some(e.weight),
1237             next: e.next,
1238         });
1239         let edges = g.edges.into_iter().map(|e| Edge {
1240             weight: Some(e.weight),
1241             node: e.node,
1242             next: e.next,
1243         });
1244         StableGraph {
1245             node_count: nodes.len(),
1246             edge_count: edges.len(),
1247             g: Graph {
1248                 edges: edges.collect(),
1249                 nodes: nodes.collect(),
1250                 ty: g.ty,
1251             },
1252             free_node: NodeIndex::end(),
1253             free_edge: EdgeIndex::end(),
1254         }
1255     }
1256 }
1257 
1258 /// Convert a `StableGraph` into a `Graph`
1259 ///
1260 /// Computes in **O(|V| + |E|)** time.
1261 ///
1262 /// This translates the stable graph into a graph with node and edge indices in
1263 /// a compact interval without holes (like `Graph`s always are).
1264 ///
1265 /// Only if the stable graph had no vacancies after deletions (if node bound was
1266 /// equal to node count, and the same for edges), would the resulting graph have
1267 /// the same node and edge indices as the input.
1268 impl<N, E, Ty, Ix> From<StableGraph<N, E, Ty, Ix>> for Graph<N, E, Ty, Ix>
1269 where
1270     Ty: EdgeType,
1271     Ix: IndexType,
1272 {
from(graph: StableGraph<N, E, Ty, Ix>) -> Self1273     fn from(graph: StableGraph<N, E, Ty, Ix>) -> Self {
1274         let mut result_g = Graph::with_capacity(graph.node_count(), graph.edge_count());
1275         // mapping from old node index to new node index
1276         let mut node_index_map = vec![NodeIndex::end(); graph.node_bound()];
1277 
1278         for (i, node) in enumerate(graph.g.nodes) {
1279             if let Some(nw) = node.weight {
1280                 node_index_map[i] = result_g.add_node(nw);
1281             }
1282         }
1283         for edge in graph.g.edges {
1284             let source_index = edge.source().index();
1285             let target_index = edge.target().index();
1286             if let Some(ew) = edge.weight {
1287                 let source = node_index_map[source_index];
1288                 let target = node_index_map[target_index];
1289                 debug_assert!(source != NodeIndex::end());
1290                 debug_assert!(target != NodeIndex::end());
1291                 result_g.add_edge(source, target, ew);
1292             }
1293         }
1294         result_g
1295     }
1296 }
1297 
1298 /// Iterator over all nodes of a graph.
1299 #[derive(Debug, Clone)]
1300 pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
1301     iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1302 }
1303 
1304 impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
1305 where
1306     Ix: IndexType,
1307 {
1308     type Item = (NodeIndex<Ix>, &'a N);
1309 
next(&mut self) -> Option<Self::Item>1310     fn next(&mut self) -> Option<Self::Item> {
1311         self.iter
1312             .ex_find_map(|(i, node)| node.weight.as_ref().map(move |w| (node_index(i), w)))
1313     }
1314 
size_hint(&self) -> (usize, Option<usize>)1315     fn size_hint(&self) -> (usize, Option<usize>) {
1316         let (_, hi) = self.iter.size_hint();
1317         (0, hi)
1318     }
1319 }
1320 
1321 impl<'a, N, Ix> DoubleEndedIterator for NodeReferences<'a, N, Ix>
1322 where
1323     Ix: IndexType,
1324 {
next_back(&mut self) -> Option<Self::Item>1325     fn next_back(&mut self) -> Option<Self::Item> {
1326         self.iter
1327             .ex_rfind_map(|(i, node)| node.weight.as_ref().map(move |w| (node_index(i), w)))
1328     }
1329 }
1330 
1331 /// Reference to a `StableGraph` edge.
1332 #[derive(Debug)]
1333 pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
1334     index: EdgeIndex<Ix>,
1335     node: [NodeIndex<Ix>; 2],
1336     weight: &'a E,
1337 }
1338 
1339 impl<'a, E, Ix: IndexType> Clone for EdgeReference<'a, E, Ix> {
clone(&self) -> Self1340     fn clone(&self) -> Self {
1341         *self
1342     }
1343 }
1344 
1345 impl<'a, E, Ix: IndexType> Copy for EdgeReference<'a, E, Ix> {}
1346 
1347 impl<'a, E, Ix: IndexType> PartialEq for EdgeReference<'a, E, Ix>
1348 where
1349     E: PartialEq,
1350 {
eq(&self, rhs: &Self) -> bool1351     fn eq(&self, rhs: &Self) -> bool {
1352         self.index == rhs.index && self.weight == rhs.weight
1353     }
1354 }
1355 
1356 impl<'a, Ix, E> EdgeReference<'a, E, Ix>
1357 where
1358     Ix: IndexType,
1359 {
1360     /// Access the edge’s weight.
1361     ///
1362     /// **NOTE** that this method offers a longer lifetime
1363     /// than the trait (unfortunately they don't match yet).
weight(&self) -> &'a E1364     pub fn weight(&self) -> &'a E {
1365         self.weight
1366     }
1367 }
1368 
1369 /// Iterator over the edges of from or to a node
1370 #[derive(Debug, Clone)]
1371 pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1372 where
1373     Ty: EdgeType,
1374     Ix: IndexType,
1375 {
1376     /// starting node to skip over
1377     skip_start: NodeIndex<Ix>,
1378     edges: &'a [Edge<Option<E>, Ix>],
1379 
1380     /// Next edge to visit.
1381     next: [EdgeIndex<Ix>; 2],
1382 
1383     /// For directed graphs: the direction to iterate in
1384     /// For undirected graphs: the direction of edges
1385     direction: Direction,
1386     ty: PhantomData<Ty>,
1387 }
1388 
1389 impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1390 where
1391     Ty: EdgeType,
1392     Ix: IndexType,
1393 {
1394     type Item = EdgeReference<'a, E, Ix>;
1395 
next(&mut self) -> Option<Self::Item>1396     fn next(&mut self) -> Option<Self::Item> {
1397         //      type        direction    |    iterate over    reverse
1398         //                               |
1399         //    Directed      Outgoing     |      outgoing        no
1400         //    Directed      Incoming     |      incoming        no
1401         //   Undirected     Outgoing     |        both       incoming
1402         //   Undirected     Incoming     |        both       outgoing
1403 
1404         // For iterate_over, "both" is represented as None.
1405         // For reverse, "no" is represented as None.
1406         let (iterate_over, reverse) = if Ty::is_directed() {
1407             (Some(self.direction), None)
1408         } else {
1409             (None, Some(self.direction.opposite()))
1410         };
1411 
1412         if iterate_over.unwrap_or(Outgoing) == Outgoing {
1413             let i = self.next[0].index();
1414             if let Some(Edge {
1415                 node,
1416                 weight: Some(weight),
1417                 next,
1418             }) = self.edges.get(i)
1419             {
1420                 self.next[0] = next[0];
1421                 return Some(EdgeReference {
1422                     index: edge_index(i),
1423                     node: if reverse == Some(Outgoing) {
1424                         swap_pair(*node)
1425                     } else {
1426                         *node
1427                     },
1428                     weight,
1429                 });
1430             }
1431         }
1432 
1433         if iterate_over.unwrap_or(Incoming) == Incoming {
1434             while let Some(Edge { node, weight, next }) = self.edges.get(self.next[1].index()) {
1435                 debug_assert!(weight.is_some());
1436                 let edge_index = self.next[1];
1437                 self.next[1] = next[1];
1438                 // In any of the "both" situations, self-loops would be iterated over twice.
1439                 // Skip them here.
1440                 if iterate_over.is_none() && node[0] == self.skip_start {
1441                     continue;
1442                 }
1443 
1444                 return Some(EdgeReference {
1445                     index: edge_index,
1446                     node: if reverse == Some(Incoming) {
1447                         swap_pair(*node)
1448                     } else {
1449                         *node
1450                     },
1451                     weight: weight.as_ref().unwrap(),
1452                 });
1453             }
1454         }
1455 
1456         None
1457     }
1458 }
1459 
1460 /// Iterator over the multiple directed edges connecting a source node to a target node
1461 #[derive(Debug, Clone)]
1462 pub struct EdgesConnecting<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1463 where
1464     Ty: EdgeType,
1465     Ix: IndexType,
1466 {
1467     target_node: NodeIndex<Ix>,
1468     edges: Edges<'a, E, Ty, Ix>,
1469     ty: PhantomData<Ty>,
1470 }
1471 
1472 impl<'a, E, Ty, Ix> Iterator for EdgesConnecting<'a, E, Ty, Ix>
1473 where
1474     Ty: EdgeType,
1475     Ix: IndexType,
1476 {
1477     type Item = EdgeReference<'a, E, Ix>;
1478 
next(&mut self) -> Option<EdgeReference<'a, E, Ix>>1479     fn next(&mut self) -> Option<EdgeReference<'a, E, Ix>> {
1480         let target_node = self.target_node;
1481         self.edges
1482             .by_ref()
1483             .find(|&edge| edge.node[1] == target_node)
1484     }
size_hint(&self) -> (usize, Option<usize>)1485     fn size_hint(&self) -> (usize, Option<usize>) {
1486         let (_, upper) = self.edges.size_hint();
1487         (0, upper)
1488     }
1489 }
1490 
swap_pair<T>(mut x: [T; 2]) -> [T; 2]1491 fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1492     x.swap(0, 1);
1493     x
1494 }
1495 
1496 /// Iterator over all edges of a graph.
1497 #[derive(Debug, Clone)]
1498 pub struct EdgeReferences<'a, E: 'a, Ix: 'a = DefaultIx> {
1499     iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1500 }
1501 
1502 impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
1503 where
1504     Ix: IndexType,
1505 {
1506     type Item = EdgeReference<'a, E, Ix>;
1507 
next(&mut self) -> Option<Self::Item>1508     fn next(&mut self) -> Option<Self::Item> {
1509         self.iter.ex_find_map(|(i, edge)| {
1510             edge.weight.as_ref().map(move |weight| EdgeReference {
1511                 index: edge_index(i),
1512                 node: edge.node,
1513                 weight,
1514             })
1515         })
1516     }
1517 }
1518 
1519 impl<'a, E, Ix> DoubleEndedIterator for EdgeReferences<'a, E, Ix>
1520 where
1521     Ix: IndexType,
1522 {
next_back(&mut self) -> Option<Self::Item>1523     fn next_back(&mut self) -> Option<Self::Item> {
1524         self.iter.ex_rfind_map(|(i, edge)| {
1525             edge.weight.as_ref().map(move |weight| EdgeReference {
1526                 index: edge_index(i),
1527                 node: edge.node,
1528                 weight,
1529             })
1530         })
1531     }
1532 }
1533 
1534 /// An iterator over either the nodes without edges to them or from them.
1535 #[derive(Debug, Clone)]
1536 pub struct Externals<'a, N: 'a, Ty, Ix: IndexType = DefaultIx> {
1537     iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1538     dir: Direction,
1539     ty: PhantomData<Ty>,
1540 }
1541 
1542 impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix>
1543 where
1544     Ty: EdgeType,
1545     Ix: IndexType,
1546 {
1547     type Item = NodeIndex<Ix>;
next(&mut self) -> Option<NodeIndex<Ix>>1548     fn next(&mut self) -> Option<NodeIndex<Ix>> {
1549         let k = self.dir.index();
1550         loop {
1551             match self.iter.next() {
1552                 None => return None,
1553                 Some((index, node)) => {
1554                     if node.weight.is_some()
1555                         && node.next[k] == EdgeIndex::end()
1556                         && (Ty::is_directed() || node.next[1 - k] == EdgeIndex::end())
1557                     {
1558                         return Some(NodeIndex::new(index));
1559                     } else {
1560                         continue;
1561                     }
1562                 }
1563             }
1564         }
1565     }
size_hint(&self) -> (usize, Option<usize>)1566     fn size_hint(&self) -> (usize, Option<usize>) {
1567         let (_, upper) = self.iter.size_hint();
1568         (0, upper)
1569     }
1570 }
1571 
1572 /// Iterator over the neighbors of a node.
1573 ///
1574 /// Iterator element type is `NodeIndex`.
1575 #[derive(Debug, Clone)]
1576 pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx> {
1577     /// starting node to skip over
1578     skip_start: NodeIndex<Ix>,
1579     edges: &'a [Edge<Option<E>, Ix>],
1580     next: [EdgeIndex<Ix>; 2],
1581 }
1582 
1583 impl<'a, E, Ix> Neighbors<'a, E, Ix>
1584 where
1585     Ix: IndexType,
1586 {
1587     /// Return a “walker” object that can be used to step through the
1588     /// neighbors and edges from the origin node.
1589     ///
1590     /// Note: The walker does not borrow from the graph, this is to allow mixing
1591     /// edge walking with mutating the graph's weights.
detach(&self) -> WalkNeighbors<Ix>1592     pub fn detach(&self) -> WalkNeighbors<Ix> {
1593         WalkNeighbors {
1594             inner: super::WalkNeighbors {
1595                 skip_start: self.skip_start,
1596                 next: self.next,
1597             },
1598         }
1599     }
1600 }
1601 
1602 impl<'a, E, Ix> Iterator for Neighbors<'a, E, Ix>
1603 where
1604     Ix: IndexType,
1605 {
1606     type Item = NodeIndex<Ix>;
1607 
next(&mut self) -> Option<NodeIndex<Ix>>1608     fn next(&mut self) -> Option<NodeIndex<Ix>> {
1609         // First any outgoing edges
1610         match self.edges.get(self.next[0].index()) {
1611             None => {}
1612             Some(edge) => {
1613                 debug_assert!(edge.weight.is_some());
1614                 self.next[0] = edge.next[0];
1615                 return Some(edge.node[1]);
1616             }
1617         }
1618         // Then incoming edges
1619         // For an "undirected" iterator (traverse both incoming
1620         // and outgoing edge lists), make sure we don't double
1621         // count selfloops by skipping them in the incoming list.
1622         while let Some(edge) = self.edges.get(self.next[1].index()) {
1623             debug_assert!(edge.weight.is_some());
1624             self.next[1] = edge.next[1];
1625             if edge.node[0] != self.skip_start {
1626                 return Some(edge.node[0]);
1627             }
1628         }
1629         None
1630     }
1631 }
1632 
1633 /// A “walker” object that can be used to step through the edge list of a node.
1634 ///
1635 /// See [*.detach()*](struct.Neighbors.html#method.detach) for more information.
1636 ///
1637 /// The walker does not borrow from the graph, so it lets you step through
1638 /// neighbors or incident edges while also mutating graph weights, as
1639 /// in the following example:
1640 ///
1641 /// ```
1642 /// use petgraph::visit::Dfs;
1643 /// use petgraph::Incoming;
1644 /// use petgraph::stable_graph::StableGraph;
1645 ///
1646 /// let mut gr = StableGraph::new();
1647 /// let a = gr.add_node(0.);
1648 /// let b = gr.add_node(0.);
1649 /// let c = gr.add_node(0.);
1650 /// gr.add_edge(a, b, 3.);
1651 /// gr.add_edge(b, c, 2.);
1652 /// gr.add_edge(c, b, 1.);
1653 ///
1654 /// // step through the graph and sum incoming edges into the node weight
1655 /// let mut dfs = Dfs::new(&gr, a);
1656 /// while let Some(node) = dfs.next(&gr) {
1657 ///     // use a detached neighbors walker
1658 ///     let mut edges = gr.neighbors_directed(node, Incoming).detach();
1659 ///     while let Some(edge) = edges.next_edge(&gr) {
1660 ///         gr[node] += gr[edge];
1661 ///     }
1662 /// }
1663 ///
1664 /// // check the result
1665 /// assert_eq!(gr[a], 0.);
1666 /// assert_eq!(gr[b], 4.);
1667 /// assert_eq!(gr[c], 2.);
1668 /// ```
1669 pub struct WalkNeighbors<Ix> {
1670     inner: super::WalkNeighbors<Ix>,
1671 }
1672 
1673 impl<Ix: IndexType> Clone for WalkNeighbors<Ix> {
1674     clone_fields!(WalkNeighbors, inner);
1675 }
1676 
1677 impl<Ix: IndexType> WalkNeighbors<Ix> {
1678     /// Step to the next edge and its endpoint node in the walk for graph `g`.
1679     ///
1680     /// The next node indices are always the others than the starting point
1681     /// where the `WalkNeighbors` value was created.
1682     /// For an `Outgoing` walk, the target nodes,
1683     /// for an `Incoming` walk, the source nodes of the edge.
next<N, E, Ty: EdgeType>( &mut self, g: &StableGraph<N, E, Ty, Ix>, ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)>1684     pub fn next<N, E, Ty: EdgeType>(
1685         &mut self,
1686         g: &StableGraph<N, E, Ty, Ix>,
1687     ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
1688         self.inner.next(&g.g)
1689     }
1690 
next_node<N, E, Ty: EdgeType>( &mut self, g: &StableGraph<N, E, Ty, Ix>, ) -> Option<NodeIndex<Ix>>1691     pub fn next_node<N, E, Ty: EdgeType>(
1692         &mut self,
1693         g: &StableGraph<N, E, Ty, Ix>,
1694     ) -> Option<NodeIndex<Ix>> {
1695         self.next(g).map(|t| t.1)
1696     }
1697 
next_edge<N, E, Ty: EdgeType>( &mut self, g: &StableGraph<N, E, Ty, Ix>, ) -> Option<EdgeIndex<Ix>>1698     pub fn next_edge<N, E, Ty: EdgeType>(
1699         &mut self,
1700         g: &StableGraph<N, E, Ty, Ix>,
1701     ) -> Option<EdgeIndex<Ix>> {
1702         self.next(g).map(|t| t.0)
1703     }
1704 }
1705 
1706 /// Iterator over the node indices of a graph.
1707 #[derive(Debug, Clone)]
1708 pub struct NodeIndices<'a, N: 'a, Ix: 'a = DefaultIx> {
1709     iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1710 }
1711 
1712 impl<'a, N, Ix: IndexType> Iterator for NodeIndices<'a, N, Ix> {
1713     type Item = NodeIndex<Ix>;
1714 
next(&mut self) -> Option<Self::Item>1715     fn next(&mut self) -> Option<Self::Item> {
1716         self.iter.ex_find_map(|(i, node)| {
1717             if node.weight.is_some() {
1718                 Some(node_index(i))
1719             } else {
1720                 None
1721             }
1722         })
1723     }
size_hint(&self) -> (usize, Option<usize>)1724     fn size_hint(&self) -> (usize, Option<usize>) {
1725         let (_, upper) = self.iter.size_hint();
1726         (0, upper)
1727     }
1728 }
1729 
1730 impl<'a, N, Ix: IndexType> DoubleEndedIterator for NodeIndices<'a, N, Ix> {
next_back(&mut self) -> Option<Self::Item>1731     fn next_back(&mut self) -> Option<Self::Item> {
1732         self.iter.ex_rfind_map(|(i, node)| {
1733             if node.weight.is_some() {
1734                 Some(node_index(i))
1735             } else {
1736                 None
1737             }
1738         })
1739     }
1740 }
1741 
1742 /// Iterator over the edge indices of a graph.
1743 #[derive(Debug, Clone)]
1744 pub struct EdgeIndices<'a, E: 'a, Ix: 'a = DefaultIx> {
1745     iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1746 }
1747 
1748 impl<'a, E, Ix: IndexType> Iterator for EdgeIndices<'a, E, Ix> {
1749     type Item = EdgeIndex<Ix>;
1750 
next(&mut self) -> Option<Self::Item>1751     fn next(&mut self) -> Option<Self::Item> {
1752         self.iter.ex_find_map(|(i, node)| {
1753             if node.weight.is_some() {
1754                 Some(edge_index(i))
1755             } else {
1756                 None
1757             }
1758         })
1759     }
size_hint(&self) -> (usize, Option<usize>)1760     fn size_hint(&self) -> (usize, Option<usize>) {
1761         let (_, upper) = self.iter.size_hint();
1762         (0, upper)
1763     }
1764 }
1765 
1766 impl<'a, E, Ix: IndexType> DoubleEndedIterator for EdgeIndices<'a, E, Ix> {
next_back(&mut self) -> Option<Self::Item>1767     fn next_back(&mut self) -> Option<Self::Item> {
1768         self.iter.ex_rfind_map(|(i, node)| {
1769             if node.weight.is_some() {
1770                 Some(edge_index(i))
1771             } else {
1772                 None
1773             }
1774         })
1775     }
1776 }
1777 
1778 impl<N, E, Ty, Ix> visit::GraphBase for StableGraph<N, E, Ty, Ix>
1779 where
1780     Ix: IndexType,
1781 {
1782     type NodeId = NodeIndex<Ix>;
1783     type EdgeId = EdgeIndex<Ix>;
1784 }
1785 
1786 impl<N, E, Ty, Ix> visit::Visitable for StableGraph<N, E, Ty, Ix>
1787 where
1788     Ty: EdgeType,
1789     Ix: IndexType,
1790 {
1791     type Map = FixedBitSet;
visit_map(&self) -> FixedBitSet1792     fn visit_map(&self) -> FixedBitSet {
1793         FixedBitSet::with_capacity(self.node_bound())
1794     }
reset_map(&self, map: &mut Self::Map)1795     fn reset_map(&self, map: &mut Self::Map) {
1796         map.clear();
1797         map.grow(self.node_bound());
1798     }
1799 }
1800 
1801 impl<N, E, Ty, Ix> visit::Data for StableGraph<N, E, Ty, Ix>
1802 where
1803     Ty: EdgeType,
1804     Ix: IndexType,
1805 {
1806     type NodeWeight = N;
1807     type EdgeWeight = E;
1808 }
1809 
1810 impl<N, E, Ty, Ix> visit::GraphProp for StableGraph<N, E, Ty, Ix>
1811 where
1812     Ty: EdgeType,
1813     Ix: IndexType,
1814 {
1815     type EdgeType = Ty;
1816 }
1817 
1818 impl<'a, N, E: 'a, Ty, Ix> visit::IntoNodeIdentifiers for &'a StableGraph<N, E, Ty, Ix>
1819 where
1820     Ty: EdgeType,
1821     Ix: IndexType,
1822 {
1823     type NodeIdentifiers = NodeIndices<'a, N, Ix>;
node_identifiers(self) -> Self::NodeIdentifiers1824     fn node_identifiers(self) -> Self::NodeIdentifiers {
1825         StableGraph::node_indices(self)
1826     }
1827 }
1828 
1829 impl<N, E, Ty, Ix> visit::NodeCount for StableGraph<N, E, Ty, Ix>
1830 where
1831     Ty: EdgeType,
1832     Ix: IndexType,
1833 {
node_count(&self) -> usize1834     fn node_count(&self) -> usize {
1835         self.node_count()
1836     }
1837 }
1838 
1839 impl<'a, N, E, Ty, Ix> visit::IntoNodeReferences for &'a StableGraph<N, E, Ty, Ix>
1840 where
1841     Ty: EdgeType,
1842     Ix: IndexType,
1843 {
1844     type NodeRef = (NodeIndex<Ix>, &'a N);
1845     type NodeReferences = NodeReferences<'a, N, Ix>;
node_references(self) -> Self::NodeReferences1846     fn node_references(self) -> Self::NodeReferences {
1847         NodeReferences {
1848             iter: enumerate(self.raw_nodes()),
1849         }
1850     }
1851 }
1852 
1853 impl<N, E, Ty, Ix> visit::NodeIndexable for StableGraph<N, E, Ty, Ix>
1854 where
1855     Ty: EdgeType,
1856     Ix: IndexType,
1857 {
1858     /// Return an upper bound of the node indices in the graph
node_bound(&self) -> usize1859     fn node_bound(&self) -> usize {
1860         self.node_indices().next_back().map_or(0, |i| i.index() + 1)
1861     }
to_index(&self, ix: NodeIndex<Ix>) -> usize1862     fn to_index(&self, ix: NodeIndex<Ix>) -> usize {
1863         ix.index()
1864     }
from_index(&self, ix: usize) -> Self::NodeId1865     fn from_index(&self, ix: usize) -> Self::NodeId {
1866         NodeIndex::new(ix)
1867     }
1868 }
1869 
1870 impl<'a, N, E: 'a, Ty, Ix> visit::IntoNeighbors for &'a StableGraph<N, E, Ty, Ix>
1871 where
1872     Ty: EdgeType,
1873     Ix: IndexType,
1874 {
1875     type Neighbors = Neighbors<'a, E, Ix>;
neighbors(self, n: Self::NodeId) -> Self::Neighbors1876     fn neighbors(self, n: Self::NodeId) -> Self::Neighbors {
1877         (*self).neighbors(n)
1878     }
1879 }
1880 
1881 impl<'a, N, E: 'a, Ty, Ix> visit::IntoNeighborsDirected for &'a StableGraph<N, E, Ty, Ix>
1882 where
1883     Ty: EdgeType,
1884     Ix: IndexType,
1885 {
1886     type NeighborsDirected = Neighbors<'a, E, Ix>;
neighbors_directed(self, n: NodeIndex<Ix>, d: Direction) -> Self::NeighborsDirected1887     fn neighbors_directed(self, n: NodeIndex<Ix>, d: Direction) -> Self::NeighborsDirected {
1888         StableGraph::neighbors_directed(self, n, d)
1889     }
1890 }
1891 
1892 impl<'a, N, E, Ty, Ix> visit::IntoEdges for &'a StableGraph<N, E, Ty, Ix>
1893 where
1894     Ty: EdgeType,
1895     Ix: IndexType,
1896 {
1897     type Edges = Edges<'a, E, Ty, Ix>;
edges(self, a: Self::NodeId) -> Self::Edges1898     fn edges(self, a: Self::NodeId) -> Self::Edges {
1899         self.edges(a)
1900     }
1901 }
1902 
1903 impl<'a, Ix, E> visit::EdgeRef for EdgeReference<'a, E, Ix>
1904 where
1905     Ix: IndexType,
1906 {
1907     type NodeId = NodeIndex<Ix>;
1908     type EdgeId = EdgeIndex<Ix>;
1909     type Weight = E;
1910 
source(&self) -> Self::NodeId1911     fn source(&self) -> Self::NodeId {
1912         self.node[0]
1913     }
target(&self) -> Self::NodeId1914     fn target(&self) -> Self::NodeId {
1915         self.node[1]
1916     }
weight(&self) -> &E1917     fn weight(&self) -> &E {
1918         self.weight
1919     }
id(&self) -> Self::EdgeId1920     fn id(&self) -> Self::EdgeId {
1921         self.index
1922     }
1923 }
1924 
1925 impl<N, E, Ty, Ix> visit::EdgeIndexable for StableGraph<N, E, Ty, Ix>
1926 where
1927     Ty: EdgeType,
1928     Ix: IndexType,
1929 {
edge_bound(&self) -> usize1930     fn edge_bound(&self) -> usize {
1931         self.edge_references()
1932             .next_back()
1933             .map_or(0, |edge| edge.id().index() + 1)
1934     }
1935 
to_index(&self, ix: EdgeIndex<Ix>) -> usize1936     fn to_index(&self, ix: EdgeIndex<Ix>) -> usize {
1937         ix.index()
1938     }
1939 
from_index(&self, ix: usize) -> Self::EdgeId1940     fn from_index(&self, ix: usize) -> Self::EdgeId {
1941         EdgeIndex::new(ix)
1942     }
1943 }
1944 
1945 impl<'a, N, E, Ty, Ix> visit::IntoEdgesDirected for &'a StableGraph<N, E, Ty, Ix>
1946 where
1947     Ty: EdgeType,
1948     Ix: IndexType,
1949 {
1950     type EdgesDirected = Edges<'a, E, Ty, Ix>;
edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected1951     fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
1952         self.edges_directed(a, dir)
1953     }
1954 }
1955 
1956 impl<'a, N: 'a, E: 'a, Ty, Ix> visit::IntoEdgeReferences for &'a StableGraph<N, E, Ty, Ix>
1957 where
1958     Ty: EdgeType,
1959     Ix: IndexType,
1960 {
1961     type EdgeRef = EdgeReference<'a, E, Ix>;
1962     type EdgeReferences = EdgeReferences<'a, E, Ix>;
1963 
1964     /// Create an iterator over all edges in the graph, in indexed order.
1965     ///
1966     /// Iterator element type is `EdgeReference<E, Ix>`.
edge_references(self) -> Self::EdgeReferences1967     fn edge_references(self) -> Self::EdgeReferences {
1968         EdgeReferences {
1969             iter: self.g.edges.iter().enumerate(),
1970         }
1971     }
1972 }
1973 
1974 impl<N, E, Ty, Ix> visit::EdgeCount for StableGraph<N, E, Ty, Ix>
1975 where
1976     Ty: EdgeType,
1977     Ix: IndexType,
1978 {
1979     #[inline]
edge_count(&self) -> usize1980     fn edge_count(&self) -> usize {
1981         self.edge_count()
1982     }
1983 }
1984 
1985 #[test]
stable_graph()1986 fn stable_graph() {
1987     let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
1988     let a = gr.add_node(0);
1989     let b = gr.add_node(1);
1990     let c = gr.add_node(2);
1991     let _ed = gr.add_edge(a, b, 1);
1992     println!("{:?}", gr);
1993     gr.remove_node(b);
1994     println!("{:?}", gr);
1995     let d = gr.add_node(3);
1996     println!("{:?}", gr);
1997     gr.check_free_lists();
1998     gr.remove_node(a);
1999     gr.check_free_lists();
2000     gr.remove_node(c);
2001     gr.check_free_lists();
2002     println!("{:?}", gr);
2003     gr.add_edge(d, d, 2);
2004     println!("{:?}", gr);
2005 
2006     let e = gr.add_node(4);
2007     gr.add_edge(d, e, 3);
2008     println!("{:?}", gr);
2009     for neigh in gr.neighbors(d) {
2010         println!("edge {:?} -> {:?}", d, neigh);
2011     }
2012     gr.check_free_lists();
2013 }
2014 
2015 #[test]
dfs()2016 fn dfs() {
2017     use crate::visit::Dfs;
2018 
2019     let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
2020     let a = gr.add_node("a");
2021     let b = gr.add_node("b");
2022     let c = gr.add_node("c");
2023     let d = gr.add_node("d");
2024     gr.add_edge(a, b, 1);
2025     gr.add_edge(a, c, 2);
2026     gr.add_edge(b, c, 3);
2027     gr.add_edge(b, d, 4);
2028     gr.add_edge(c, d, 5);
2029     gr.add_edge(d, b, 6);
2030     gr.add_edge(c, b, 7);
2031     println!("{:?}", gr);
2032 
2033     let mut dfs = Dfs::new(&gr, a);
2034     while let Some(next) = dfs.next(&gr) {
2035         println!("dfs visit => {:?}, weight={:?}", next, &gr[next]);
2036     }
2037 }
2038 
2039 #[test]
test_retain_nodes()2040 fn test_retain_nodes() {
2041     let mut gr = StableGraph::<_, _>::with_capacity(6, 6);
2042     let a = gr.add_node("a");
2043     let f = gr.add_node("f");
2044     let b = gr.add_node("b");
2045     let c = gr.add_node("c");
2046     let d = gr.add_node("d");
2047     let e = gr.add_node("e");
2048     gr.add_edge(a, b, 1);
2049     gr.add_edge(a, c, 2);
2050     gr.add_edge(b, c, 3);
2051     gr.add_edge(b, d, 4);
2052     gr.add_edge(c, d, 5);
2053     gr.add_edge(d, b, 6);
2054     gr.add_edge(c, b, 7);
2055     gr.add_edge(d, e, 8);
2056     gr.remove_node(f);
2057 
2058     assert_eq!(gr.node_count(), 5);
2059     assert_eq!(gr.edge_count(), 8);
2060     gr.retain_nodes(|frozen_gr, ix| frozen_gr[ix] >= "c");
2061     assert_eq!(gr.node_count(), 3);
2062     assert_eq!(gr.edge_count(), 2);
2063 
2064     gr.check_free_lists();
2065 }
2066 
2067 #[test]
extend_with_edges()2068 fn extend_with_edges() {
2069     let mut gr = StableGraph::<_, _>::default();
2070     let a = gr.add_node("a");
2071     let b = gr.add_node("b");
2072     let c = gr.add_node("c");
2073     let _d = gr.add_node("d");
2074     gr.remove_node(a);
2075     gr.remove_node(b);
2076     gr.remove_node(c);
2077 
2078     gr.extend_with_edges(vec![(0, 1, ())]);
2079     assert_eq!(gr.node_count(), 3);
2080     assert_eq!(gr.edge_count(), 1);
2081     gr.check_free_lists();
2082 
2083     gr.extend_with_edges(vec![(5, 1, ())]);
2084     assert_eq!(gr.node_count(), 4);
2085     assert_eq!(gr.edge_count(), 2);
2086     gr.check_free_lists();
2087 }
2088 
2089 #[test]
test_reverse()2090 fn test_reverse() {
2091     let mut gr = StableGraph::<_, _>::default();
2092     let a = gr.add_node("a");
2093     let b = gr.add_node("b");
2094 
2095     gr.add_edge(a, b, 0);
2096 
2097     let mut reversed_gr = gr.clone();
2098     reversed_gr.reverse();
2099 
2100     for i in gr.node_indices() {
2101         itertools::assert_equal(gr.edges_directed(i, Incoming), reversed_gr.edges(i));
2102     }
2103 }
2104