petgraph/graph_impl/stable_graph/
mod.rs

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