Skip to main content

petgraph/graph_impl/stable_graph/
mod.rs

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