petgraph/graph_impl/stable_graph/
mod.rs

1//! `StableGraph` keeps indices stable across removals.
2//!
3//! Depends on `feature = "stable_graph"`.
4//!
5
6use alloc::vec;
7use core::{
8    cmp, fmt, iter,
9    marker::PhantomData,
10    mem::size_of,
11    ops::{Index, IndexMut},
12    slice,
13};
14
15use fixedbitset::FixedBitSet;
16
17use super::{index_twice, Edge, Frozen, GraphError, Node, Pair, DIRECTIONS};
18use crate::iter_format::{DebugMap, IterFormatExt, NoPretty};
19use crate::iter_utils::IterUtilsExt;
20use crate::visit::{self, EdgeIndexable, EdgeRef, IntoEdgeReferences, NodeIndexable};
21use crate::{
22    Directed, Direction, EdgeType, Graph, Incoming, IntoWeightedEdge, Outgoing, Undirected,
23};
24
25// reexport those things that are shared with Graph
26#[doc(no_inline)]
27pub use crate::graph::{
28    edge_index, node_index, DefaultIx, EdgeIndex, GraphIndex, IndexType, NodeIndex,
29};
30
31#[cfg(feature = "serde-1")]
32mod serialization;
33
34/// `StableGraph<N, E, Ty, Ix>` is a graph datastructure using an adjacency
35/// list representation.
36///
37/// The graph **does not invalidate** any unrelated node or edge indices when
38/// items are removed.
39///
40/// `StableGraph` is parameterized over:
41///
42/// - Associated data `N` for nodes and `E` for edges, also called *weights*.
43///   The associated data can be of arbitrary type.
44/// - Edge type `Ty` that determines whether the graph edges are directed or undirected.
45/// - Index type `Ix`, which determines the maximum size of the graph.
46///
47/// The graph uses **O(|V| + |E|)** space where V is the set of nodes and E is the
48/// set of edges, and allows fast node and edge insert and efficient graph search.
49///
50/// It implements **O(e')** edge lookup and edge and node removals, where **e'**
51/// is some local measure of edge count.
52///
53/// - Nodes and edges are each numbered in an interval from *0* to some number
54///   *m*, but *not all* indices in the range are valid, since gaps are formed
55///   by deletions.
56///
57/// - You can select graph index integer type after the size of the graph. A smaller
58///   size may have better performance.
59///
60/// - Using indices allows mutation while traversing the graph, see `Dfs`.
61///
62/// - The `StableGraph` is a regular rust collection and is `Send` and `Sync`
63///   (as long as associated data `N` and `E` are).
64///
65/// - Indices don't allow as much compile time checking as references.
66///
67/// Depends on crate feature `stable_graph` (default). *Stable Graph is still
68/// missing a few methods compared to Graph. You can contribute to help it
69/// achieve parity.*
70pub struct StableGraph<N, E, Ty = Directed, Ix = DefaultIx> {
71    g: Graph<Option<N>, Option<E>, Ty, Ix>,
72    node_count: usize,
73    edge_count: usize,
74
75    // node and edge free lists (both work the same way)
76    //
77    // free_node, if not NodeIndex::end(), points to a node index
78    // that is vacant (after a deletion).
79    // The free nodes form a doubly linked list using the fields Node.next[0]
80    // for forward references and Node.next[1] for backwards ones.
81    // The nodes are stored as EdgeIndex, and the _into_edge()/_into_node()
82    // methods convert.
83    // free_edge, if not EdgeIndex::end(), points to a free edge.
84    // The edges only form a singly linked list using Edge.next[0] to store
85    // the forward reference.
86    free_node: NodeIndex<Ix>,
87    free_edge: EdgeIndex<Ix>,
88}
89
90/// A `StableGraph` with directed edges.
91///
92/// For example, an edge from *1* to *2* is distinct from an edge from *2* to
93/// *1*.
94pub type StableDiGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Directed, Ix>;
95
96/// A `StableGraph` with undirected edges.
97///
98/// For example, an edge between *1* and *2* is equivalent to an edge between
99/// *2* and *1*.
100pub type StableUnGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Undirected, Ix>;
101
102impl<N, E, Ty, Ix> fmt::Debug for StableGraph<N, E, Ty, Ix>
103where
104    N: fmt::Debug,
105    E: fmt::Debug,
106    Ty: EdgeType,
107    Ix: IndexType,
108{
109    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110        let etype = if self.is_directed() {
111            "Directed"
112        } else {
113            "Undirected"
114        };
115        let mut fmt_struct = f.debug_struct("StableGraph");
116        fmt_struct.field("Ty", &etype);
117        fmt_struct.field("node_count", &self.node_count);
118        fmt_struct.field("edge_count", &self.edge_count);
119        if self.g.edges.iter().any(|e| e.weight.is_some()) {
120            fmt_struct.field(
121                "edges",
122                &self
123                    .g
124                    .edges
125                    .iter()
126                    .filter(|e| e.weight.is_some())
127                    .map(|e| NoPretty((e.source().index(), e.target().index())))
128                    .format(", "),
129            );
130        }
131        // skip weights if they are ZST!
132        if size_of::<N>() != 0 {
133            fmt_struct.field(
134                "node weights",
135                &DebugMap(|| {
136                    self.g
137                        .nodes
138                        .iter()
139                        .map(|n| n.weight.as_ref())
140                        .enumerate()
141                        .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
142                }),
143            );
144        }
145        if size_of::<E>() != 0 {
146            fmt_struct.field(
147                "edge weights",
148                &DebugMap(|| {
149                    self.g
150                        .edges
151                        .iter()
152                        .map(|n| n.weight.as_ref())
153                        .enumerate()
154                        .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
155                }),
156            );
157        }
158        fmt_struct.field("free_node", &self.free_node);
159        fmt_struct.field("free_edge", &self.free_edge);
160        fmt_struct.finish()
161    }
162}
163
164#[derive(Debug)]
165pub struct StableGraphNode<N, Ix> {
166    pub index: NodeIndex<Ix>,
167    pub weight: N,
168}
169
170impl<N, Ix> Clone for StableGraphNode<N, Ix>
171where
172    N: Clone,
173    Ix: Copy,
174{
175    fn clone(&self) -> Self {
176        Self {
177            index: self.index,
178            weight: self.weight.clone(),
179        }
180    }
181}
182
183#[derive(Debug)]
184pub struct StableGraphEdge<E, Ix> {
185    pub index: EdgeIndex<Ix>,
186    pub source: NodeIndex<Ix>,
187    pub target: NodeIndex<Ix>,
188    pub weight: E,
189}
190
191impl<E, Ix> Clone for StableGraphEdge<E, Ix>
192where
193    E: Clone,
194    Ix: Copy,
195{
196    fn clone(&self) -> Self {
197        Self {
198            index: self.index,
199            source: self.source,
200            target: self.target,
201            weight: self.weight.clone(),
202        }
203    }
204}
205
206impl<N, E> StableGraph<N, E, Directed> {
207    /// Create a new `StableGraph` with directed edges.
208    ///
209    /// This is a convenience method. See `StableGraph::with_capacity`
210    /// or `StableGraph::default` for a constructor that is generic in all the
211    /// type parameters of `StableGraph`.
212    pub fn new() -> Self {
213        Self::with_capacity(0, 0)
214    }
215}
216
217impl<N, E, Ty, Ix> StableGraph<N, E, Ty, Ix>
218where
219    Ix: IndexType,
220{
221    /// Create a new `StableGraph` with estimated capacity.
222    pub fn with_capacity(nodes: usize, edges: usize) -> Self {
223        StableGraph {
224            g: Graph::with_capacity(nodes, edges),
225            node_count: 0,
226            edge_count: 0,
227            free_node: NodeIndex::end(),
228            free_edge: EdgeIndex::end(),
229        }
230    }
231}
232
233impl<N, E, Ty, Ix> StableGraph<N, E, Ty, Ix>
234where
235    Ty: EdgeType,
236    Ix: IndexType,
237{
238    /// Return the current node and edge capacity of the graph.
239    pub fn capacity(&self) -> (usize, usize) {
240        self.g.capacity()
241    }
242
243    /// Reverse the direction of all edges
244    pub fn reverse(&mut self) {
245        // swap edge endpoints,
246        // edge incoming / outgoing lists,
247        // node incoming / outgoing lists
248        for edge in &mut self.g.edges {
249            if edge.weight.is_some() {
250                edge.node.swap(0, 1);
251                edge.next.swap(0, 1);
252            }
253        }
254        for node in &mut self.g.nodes {
255            if node.weight.is_some() {
256                node.next.swap(0, 1);
257            }
258        }
259    }
260
261    /// Remove all nodes and edges
262    pub fn clear(&mut self) {
263        self.node_count = 0;
264        self.edge_count = 0;
265        self.free_node = NodeIndex::end();
266        self.free_edge = EdgeIndex::end();
267        self.g.clear();
268    }
269
270    /// Remove all edges
271    pub fn clear_edges(&mut self) {
272        self.edge_count = 0;
273        self.free_edge = EdgeIndex::end();
274        self.g.edges.clear();
275        // clear edges without touching the free list
276        for node in &mut self.g.nodes {
277            if node.weight.is_some() {
278                node.next = [EdgeIndex::end(), EdgeIndex::end()];
279            }
280        }
281    }
282
283    /// Return the number of nodes (also called vertices) in the graph.
284    ///
285    /// Computes in **O(1)** time.
286    pub fn node_count(&self) -> usize {
287        self.node_count
288    }
289
290    /// Return the number of edges in the graph.
291    ///
292    /// Computes in **O(1)** time.
293    pub fn edge_count(&self) -> usize {
294        self.edge_count
295    }
296
297    /// Reserves capacity for at least additional more nodes to be inserted in
298    /// the graph. Graph may reserve more space to avoid frequent reallocations.
299    ///
300    /// Panics if the new capacity overflows usize.
301    #[track_caller]
302    pub fn reserve_nodes(&mut self, additional: usize) {
303        self.g.reserve_nodes(additional);
304    }
305
306    /// Reserves capacity for at least additional more edges to be inserted in
307    /// the graph. Graph may reserve more space to avoid frequent reallocations.
308    ///
309    /// Panics if the new capacity overflows usize.
310    #[track_caller]
311    pub fn reserve_edges(&mut self, additional: usize) {
312        self.g.reserve_edges(additional);
313    }
314
315    /// Reserves the minimum capacity for exactly additional more nodes to be
316    /// inserted in the graph. Does nothing if the capacity is already
317    /// sufficient.
318    ///
319    /// Prefer reserve_nodes if future insertions are expected.
320    ///
321    /// Panics if the new capacity overflows usize.
322    #[track_caller]
323    pub fn reserve_exact_nodes(&mut self, additional: usize) {
324        self.g.reserve_exact_nodes(additional);
325    }
326
327    /// Reserves the minimum capacity for exactly additional more edges to be
328    /// inserted in the graph.
329    /// Does nothing if the capacity is already sufficient.
330    ///
331    /// Prefer reserve_edges if future insertions are expected.
332    ///
333    /// Panics if the new capacity overflows usize.
334    #[track_caller]
335    pub fn reserve_exact_edges(&mut self, additional: usize) {
336        self.g.reserve_exact_edges(additional);
337    }
338
339    /// Shrinks the capacity of the underlying nodes collection as much as possible.
340    pub fn shrink_to_fit_nodes(&mut self) {
341        self.g.shrink_to_fit_nodes();
342    }
343
344    /// Shrinks the capacity of the underlying edges collection as much as possible.
345    pub fn shrink_to_fit_edges(&mut self) {
346        self.g.shrink_to_fit_edges();
347    }
348
349    /// Shrinks the capacity of the graph as much as possible.
350    pub fn shrink_to_fit(&mut self) {
351        self.g.shrink_to_fit();
352    }
353
354    /// Whether the graph has directed edges or not.
355    #[inline]
356    pub fn is_directed(&self) -> bool {
357        Ty::is_directed()
358    }
359
360    /// Add a node (also called vertex) with associated data `weight` to the graph.
361    ///
362    /// Computes in **O(1)** time.
363    ///
364    /// Return the index of the new node.
365    ///
366    /// **Panics** if the `StableGraph` is at the maximum number of nodes for
367    /// its index type.
368    #[track_caller]
369    pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
370        self.try_add_node(weight).unwrap()
371    }
372
373    /// Add a node (also called vertex) with associated data `weight` to the graph.
374    ///
375    /// Computes in **O(1)** time.
376    ///
377    /// Return the index of the new node.
378    ///
379    /// Return [`GraphError::NodeIxLimit`] if the `StableGraph` is at the maximum number of nodes for its index.
380    pub fn try_add_node(&mut self, weight: N) -> Result<NodeIndex<Ix>, GraphError> {
381        if self.free_node != NodeIndex::end() {
382            let node_idx = self.free_node;
383            self.occupy_vacant_node(node_idx, weight);
384            Ok(node_idx)
385        } else {
386            self.node_count += 1;
387            self.g.try_add_node(Some(weight))
388        }
389    }
390
391    /// free_node: Which free list to update for the vacancy
392    fn add_vacant_node(&mut self, free_node: &mut NodeIndex<Ix>) {
393        let node_idx = self.g.add_node(None);
394        // link the free list
395        let node_slot = &mut self.g.nodes[node_idx.index()];
396        node_slot.next = [free_node._into_edge(), EdgeIndex::end()];
397        if *free_node != NodeIndex::end() {
398            self.g.nodes[free_node.index()].next[1] = node_idx._into_edge();
399        }
400        *free_node = node_idx;
401    }
402
403    /// Remove `a` from the graph if it exists, and return its weight.
404    /// If it doesn't exist in the graph, return `None`.
405    ///
406    /// The node index `a` is invalidated, but none other.
407    /// Edge indices are invalidated as they would be following the removal of
408    /// each edge with an endpoint in `a`.
409    ///
410    /// Computes in **O(e')** time, where **e'** is the number of affected
411    /// edges, including *n* calls to `.remove_edge()` where *n* is the number
412    /// of edges with an endpoint in `a`.
413    pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N> {
414        let node_weight = self.g.nodes.get_mut(a.index())?.weight.take()?;
415        for d in &DIRECTIONS {
416            let k = d.index();
417
418            // Remove all edges from and to this node.
419            loop {
420                let next = self.g.nodes[a.index()].next[k];
421                if next == EdgeIndex::end() {
422                    break;
423                }
424                let ret = self.remove_edge(next);
425                debug_assert!(ret.is_some());
426                let _ = ret;
427            }
428        }
429
430        let node_slot = &mut self.g.nodes[a.index()];
431        //let node_weight = replace(&mut self.g.nodes[a.index()].weight, Entry::Empty(self.free_node));
432        //self.g.nodes[a.index()].next = [EdgeIndex::end(), EdgeIndex::end()];
433        node_slot.next = [self.free_node._into_edge(), EdgeIndex::end()];
434        if self.free_node != NodeIndex::end() {
435            self.g.nodes[self.free_node.index()].next[1] = a._into_edge();
436        }
437        self.free_node = a;
438        self.node_count -= 1;
439
440        Some(node_weight)
441    }
442
443    pub fn contains_node(&self, a: NodeIndex<Ix>) -> bool {
444        self.get_node(a).is_some()
445    }
446
447    // Return the Node if it is not vacant (non-None weight)
448    fn get_node(&self, a: NodeIndex<Ix>) -> Option<&Node<Option<N>, Ix>> {
449        self.g
450            .nodes
451            .get(a.index())
452            .and_then(|node| node.weight.as_ref().map(move |_| node))
453    }
454
455    /// Add an edge from `a` to `b` to the graph, with its associated
456    /// data `weight`.
457    ///
458    /// Return the index of the new edge.
459    ///
460    /// Computes in **O(1)** time.
461    ///
462    /// **Panics** if any of the nodes don't exist.<br>
463    /// **Panics** if the `StableGraph` is at the maximum number of edges for
464    /// its index type.
465    ///
466    /// **Note:** `StableGraph` allows adding parallel (“duplicate”) edges.
467    #[track_caller]
468    pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
469        let res = self.try_add_edge(a, b, weight);
470        if let Err(GraphError::NodeMissed(i)) = res {
471            panic!(
472                "StableGraph::add_edge: node index {} is not a node in the graph",
473                i
474            );
475        }
476        res.unwrap()
477    }
478
479    /// Try to add an edge from `a` to `b` to the graph, with its associated
480    /// data `weight`.
481    ///
482    /// Return the index of the new edge.
483    ///
484    /// Computes in **O(1)** time.
485    ///
486    /// Possible errors:
487    /// - [`GraphError::NodeMissed`] - if any of the nodes don't exist.<br>
488    /// - [`GraphError::EdgeIxLimit`] if the `StableGraph` is at the maximum number of edges for its index
489    ///   type (N/A if usize).
490    ///
491    /// **Note:** `StableGraph` allows adding parallel (“duplicate”) edges.
492    pub fn try_add_edge(
493        &mut self,
494        a: NodeIndex<Ix>,
495        b: NodeIndex<Ix>,
496        weight: E,
497    ) -> Result<EdgeIndex<Ix>, GraphError> {
498        let edge_idx;
499        let mut new_edge = None::<Edge<_, _>>;
500        {
501            let edge: &mut Edge<_, _>;
502
503            if self.free_edge != EdgeIndex::end() {
504                edge_idx = self.free_edge;
505                edge = &mut self.g.edges[edge_idx.index()];
506                let _old = edge.weight.replace(weight);
507                debug_assert!(_old.is_none());
508                self.free_edge = edge.next[0];
509                edge.node = [a, b];
510            } else {
511                edge_idx = EdgeIndex::new(self.g.edges.len());
512                if !(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx) {
513                    return Err(GraphError::EdgeIxLimit);
514                }
515                new_edge = Some(Edge {
516                    weight: Some(weight),
517                    node: [a, b],
518                    next: [EdgeIndex::end(); 2],
519                });
520                edge = new_edge.as_mut().unwrap();
521            }
522
523            let wrong_index = match index_twice(&mut self.g.nodes, a.index(), b.index()) {
524                Pair::None => Some(cmp::max(a.index(), b.index())),
525                Pair::One(an) => {
526                    if an.weight.is_none() {
527                        Some(a.index())
528                    } else {
529                        edge.next = an.next;
530                        an.next[0] = edge_idx;
531                        an.next[1] = edge_idx;
532                        None
533                    }
534                }
535                Pair::Both(an, bn) => {
536                    // a and b are different indices
537                    if an.weight.is_none() {
538                        Some(a.index())
539                    } else if bn.weight.is_none() {
540                        Some(b.index())
541                    } else {
542                        edge.next = [an.next[0], bn.next[1]];
543                        an.next[0] = edge_idx;
544                        bn.next[1] = edge_idx;
545                        None
546                    }
547                }
548            };
549            if let Some(i) = wrong_index {
550                return Err(GraphError::NodeMissed(i));
551            }
552            self.edge_count += 1;
553        }
554        if let Some(edge) = new_edge {
555            self.g.edges.push(edge);
556        }
557        Ok(edge_idx)
558    }
559
560    /// free_edge: Which free list to update for the vacancy
561    fn add_vacant_edge(&mut self, free_edge: &mut EdgeIndex<Ix>) {
562        let edge_idx = EdgeIndex::new(self.g.edges.len());
563        debug_assert!(edge_idx != EdgeIndex::end());
564        let mut edge = Edge {
565            weight: None,
566            node: [NodeIndex::end(); 2],
567            next: [EdgeIndex::end(); 2],
568        };
569        edge.next[0] = *free_edge;
570        *free_edge = edge_idx;
571        self.g.edges.push(edge);
572    }
573
574    /// Add or update an edge from `a` to `b`.
575    /// If the edge already exists, its weight is updated.
576    ///
577    /// Return the index of the affected edge.
578    ///
579    /// Computes in **O(e')** time, where **e'** is the number of edges
580    /// connected to `a` (and `b`, if the graph edges are undirected).
581    ///
582    /// **Panics** if any of the nodes don't exist
583    /// or the stable graph is at the maximum number of edges for its index (when adding new edge).
584    #[track_caller]
585    pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
586        self.try_update_edge(a, b, weight).unwrap()
587    }
588
589    /// Try to add or update an edge from `a` to `b`.
590    /// If the edge already exists, its weight is updated.
591    ///
592    /// Return the index of the affected edge.
593    ///
594    /// Computes in **O(e')** time, where **e'** is the number of edges
595    /// connected to `a` (and `b`, if the graph edges are undirected).
596    ///
597    /// Possible errors:
598    /// - [`GraphError::NodeMissed`] - if any of the nodes don't exist.<br>
599    /// - [`GraphError::EdgeIxLimit`] if the `StableGraph` is at the maximum number of edges for its index
600    ///   type (N/A if usize).
601    pub fn try_update_edge(
602        &mut self,
603        a: NodeIndex<Ix>,
604        b: NodeIndex<Ix>,
605        weight: E,
606    ) -> Result<EdgeIndex<Ix>, GraphError> {
607        if let Some(ix) = self.find_edge(a, b) {
608            self[ix] = weight;
609            return Ok(ix);
610        }
611        self.try_add_edge(a, b, weight)
612    }
613
614    /// Remove an edge and return its edge weight, or `None` if it didn't exist.
615    ///
616    /// Invalidates the edge index `e` but no other.
617    ///
618    /// Computes in **O(e')** time, where **e'** is the number of edges
619    /// connected to the same endpoints as `e`.
620    pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
621        // every edge is part of two lists,
622        // outgoing and incoming edges.
623        // Remove it from both
624        let (is_edge, edge_node, edge_next) = match self.g.edges.get(e.index()) {
625            None => return None,
626            Some(x) => (x.weight.is_some(), x.node, x.next),
627        };
628        if !is_edge {
629            return None;
630        }
631
632        // Remove the edge from its in and out lists by replacing it with
633        // a link to the next in the list.
634        self.g.change_edge_links(edge_node, e, edge_next);
635
636        // Clear the edge and put it in the free list
637        let edge = &mut self.g.edges[e.index()];
638        edge.next = [self.free_edge, EdgeIndex::end()];
639        edge.node = [NodeIndex::end(), NodeIndex::end()];
640        self.free_edge = e;
641        self.edge_count -= 1;
642        edge.weight.take()
643    }
644
645    /// Access the weight for node `a`.
646    ///
647    /// Also available with indexing syntax: `&graph[a]`.
648    pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
649        match self.g.nodes.get(a.index()) {
650            Some(no) => no.weight.as_ref(),
651            None => None,
652        }
653    }
654
655    /// Access the weight for node `a`, mutably.
656    ///
657    /// Also available with indexing syntax: `&mut graph[a]`.
658    pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
659        match self.g.nodes.get_mut(a.index()) {
660            Some(no) => no.weight.as_mut(),
661            None => None,
662        }
663    }
664
665    /// Return an iterator yielding immutable access to all node weights.
666    ///
667    /// The order in which weights are yielded matches the order of their node
668    /// indices.
669    pub fn node_weights(&self) -> impl Iterator<Item = &N> {
670        self.g
671            .node_weights()
672            .filter_map(|maybe_node| maybe_node.as_ref())
673    }
674    /// Return an iterator yielding mutable access to all node weights.
675    ///
676    /// The order in which weights are yielded matches the order of their node
677    /// indices.
678    pub fn node_weights_mut(&mut self) -> impl Iterator<Item = &mut N> {
679        self.g
680            .node_weights_mut()
681            .filter_map(|maybe_node| maybe_node.as_mut())
682    }
683
684    /// Return an iterator over the node indices of the graph
685    pub fn node_indices(&self) -> NodeIndices<'_, N, Ix> {
686        NodeIndices {
687            iter: self.raw_nodes().iter().enumerate(),
688        }
689    }
690
691    /// Access the weight for edge `e`.
692    ///
693    /// Also available with indexing syntax: `&graph[e]`.
694    pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
695        match self.g.edges.get(e.index()) {
696            Some(ed) => ed.weight.as_ref(),
697            None => None,
698        }
699    }
700
701    /// Access the weight for edge `e`, mutably
702    ///
703    /// Also available with indexing syntax: `&mut graph[e]`.
704    pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
705        match self.g.edges.get_mut(e.index()) {
706            Some(ed) => ed.weight.as_mut(),
707            None => None,
708        }
709    }
710
711    /// Return an iterator yielding immutable access to all edge weights.
712    ///
713    /// The order in which weights are yielded matches the order of their edge
714    /// indices.
715    pub fn edge_weights(&self) -> impl Iterator<Item = &E> {
716        self.g
717            .edge_weights()
718            .filter_map(|maybe_edge| maybe_edge.as_ref())
719    }
720    /// Return an iterator yielding mutable access to all edge weights.
721    ///
722    /// The order in which weights are yielded matches the order of their edge
723    /// indices.
724    pub fn edge_weights_mut(&mut self) -> impl Iterator<Item = &mut E> {
725        self.g
726            .edge_weights_mut()
727            .filter_map(|maybe_edge| maybe_edge.as_mut())
728    }
729
730    /// Access the source and target nodes for `e`.
731    pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)> {
732        match self.g.edges.get(e.index()) {
733            Some(ed) if ed.weight.is_some() => Some((ed.source(), ed.target())),
734            _otherwise => None,
735        }
736    }
737
738    /// Return an iterator over the edge indices of the graph.
739    ///
740    /// Note: the iterator borrows a graph in contrast to the behavior of
741    /// [`Graph::edge_indices`](fn@crate::Graph::edge_indices).
742    pub fn edge_indices(&self) -> EdgeIndices<'_, E, Ix> {
743        EdgeIndices {
744            iter: self.raw_edges().iter().enumerate(),
745        }
746    }
747
748    /// Return an iterator over all the edges connecting `a` and `b`.
749    ///
750    /// - `Directed`: Outgoing edges from `a`.
751    /// - `Undirected`: All edges connected to `a`.
752    ///
753    /// Iterator element type is `EdgeReference<E, Ix>`.
754    pub fn edges_connecting(
755        &self,
756        a: NodeIndex<Ix>,
757        b: NodeIndex<Ix>,
758    ) -> EdgesConnecting<'_, E, Ty, Ix> {
759        EdgesConnecting {
760            target_node: b,
761            edges: self.edges_directed(a, Outgoing),
762            ty: PhantomData,
763        }
764    }
765
766    /// Lookup if there is an edge from `a` to `b`.
767    ///
768    /// Computes in **O(e')** time, where **e'** is the number of edges
769    /// connected to `a` (and `b`, if the graph edges are undirected).
770    pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
771        self.find_edge(a, b).is_some()
772    }
773
774    /// Lookup an edge from `a` to `b`.
775    ///
776    /// Computes in **O(e')** time, where **e'** is the number of edges
777    /// connected to `a` (and `b`, if the graph edges are undirected).
778    pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>> {
779        if !self.is_directed() {
780            self.find_edge_undirected(a, b).map(|(ix, _)| ix)
781        } else {
782            match self.get_node(a) {
783                None => None,
784                Some(node) => self.g.find_edge_directed_from_node(node, b),
785            }
786        }
787    }
788
789    /// Lookup an edge between `a` and `b`, in either direction.
790    ///
791    /// If the graph is undirected, then this is equivalent to `.find_edge()`.
792    ///
793    /// Return the edge index and its directionality, with `Outgoing` meaning
794    /// from `a` to `b` and `Incoming` the reverse,
795    /// or `None` if the edge does not exist.
796    pub fn find_edge_undirected(
797        &self,
798        a: NodeIndex<Ix>,
799        b: NodeIndex<Ix>,
800    ) -> Option<(EdgeIndex<Ix>, Direction)> {
801        match self.get_node(a) {
802            None => None,
803            Some(node) => self.g.find_edge_undirected_from_node(node, b),
804        }
805    }
806
807    /// Return an iterator of all nodes with an edge starting from `a`.
808    ///
809    /// - `Directed`: Outgoing edges from `a`.
810    /// - `Undirected`: All edges connected to `a`.
811    ///
812    /// Produces an empty iterator if the node doesn't exist.<br>
813    /// Iterator element type is `NodeIndex<Ix>`.
814    ///
815    /// For the iteration order for `Directed` and `Undirected` graphs respectively,
816    /// please refer to the documentation of [`Graph::neighbors_directed`].
817    ///
818    /// Use [`.neighbors(a).detach()`][1] to get a neighbor walker that does
819    /// not borrow from the graph.
820    ///
821    /// [1]: struct.Neighbors.html#method.detach
822    pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<'_, E, Ix> {
823        self.neighbors_directed(a, Outgoing)
824    }
825
826    /// Return an iterator of all neighbors that have an edge between them and `a`,
827    /// in the specified direction.
828    /// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
829    ///
830    /// - `Directed`, `Outgoing`: All edges from `a`.
831    /// - `Directed`, `Incoming`: All edges to `a`.
832    /// - `Undirected`: All edges connected to `a`.
833    ///
834    /// Produces an empty iterator if the node doesn't exist.<br>
835    /// Iterator element type is `NodeIndex<Ix>`.
836    ///
837    /// For a `Directed` graph, neighbors are listed in reverse order of their
838    /// addition to the graph, so the most recently added edge's neighbor is
839    /// listed first.
840    ///
841    /// For the ordering in case of an `Undirected` graph, please refer to
842    /// the documentation of [`Graph::neighbors_undirected`].
843    ///
844    /// Use [`.neighbors_directed(a, dir).detach()`][1] to get a neighbor walker that does
845    /// not borrow from the graph.
846    ///
847    /// [1]: struct.Neighbors.html#method.detach
848    pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<'_, E, Ix> {
849        let mut iter = self.neighbors_undirected(a);
850        if self.is_directed() {
851            let k = dir.index();
852            iter.next[1 - k] = EdgeIndex::end();
853            iter.skip_start = NodeIndex::end();
854        }
855        iter
856    }
857
858    /// Return an iterator of all neighbors that have an edge between them and `a`,
859    /// in either direction.
860    /// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
861    ///
862    /// - `Directed` and `Undirected`: All edges connected to `a`.
863    ///
864    /// Produces an empty iterator if the node doesn't exist.<br>
865    /// Iterator element type is `NodeIndex<Ix>`.
866    ///
867    /// All outgoing neighbors are listed first followed by all incoming neighbors.
868    /// The ordering among the outgoing and incoming neighbors respectively is the
869    /// reverse order of their addition to the graph. That is, the most recently
870    /// added edge's neighbor is listed first. Outgoing and incoming in this case
871    /// refer to the ordering in which the endpoints were listed when adding the
872    /// edge (`g.add_edge(a, b, w)` or `g.add_edge(b, a, w)`).
873    ///
874    /// Use [`.neighbors_undirected(a).detach()`][1] to get a neighbor walker that does
875    /// not borrow from the graph.
876    ///
877    /// [1]: struct.Neighbors.html#method.detach
878    pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<'_, E, Ix> {
879        Neighbors {
880            skip_start: a,
881            edges: &self.g.edges,
882            next: match self.get_node(a) {
883                None => [EdgeIndex::end(), EdgeIndex::end()],
884                Some(n) => n.next,
885            },
886        }
887    }
888
889    /// Return an iterator of all edges of `a`.
890    ///
891    /// - `Directed`: Outgoing edges from `a`.
892    /// - `Undirected`: All edges connected to `a`.
893    ///
894    /// Produces an empty iterator if the node doesn't exist.<br>
895    /// Iterator element type is `EdgeReference<E, Ix>`.
896    ///
897    /// For a `Directed` graph, edges are listed in reverse order of their
898    /// addition to the graph, so the most recently added edge is listed first.
899    ///
900    /// For the ordering in case of an `Undirected` graph, please refer to
901    /// the `Undirected` case in the documentation of [`Graph::edges_directed`].
902    pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<'_, E, Ty, Ix> {
903        self.edges_directed(a, Outgoing)
904    }
905
906    /// Return an iterator of all edges of `a`, in the specified direction.
907    ///
908    /// - `Directed`, `Outgoing`: All edges from `a`.
909    /// - `Directed`, `Incoming`: All edges to `a`.
910    /// - `Undirected`, `Outgoing`: All edges connected to `a`, with `a` being the source of each
911    ///   edge.
912    /// - `Undirected`, `Incoming`: All edges connected to `a`, with `a` being the target of each
913    ///   edge.
914    ///
915    /// Produces an empty iterator if the node `a` doesn't exist.<br>
916    /// Iterator element type is `EdgeReference<E, Ix>`.
917    ///
918    /// For a `Directed` graph, edges are listed in reverse order of their
919    /// addition to the graph, so the most recently added edge is listed first.
920    ///
921    /// For an `Undirected` graph, the outgoing edges are listed first, then
922    /// all incoming edges. The ordering among the outgoing and incoming edges
923    /// respectively is the reverse order of their addition to the graph,
924    /// similar to the `Directed` case. Outgoing and incoming in this case
925    /// refer to the ordering in which the endpoints were listed when adding the
926    /// edge (`g.add_edge(a, b, w)` or `g.add_edge(b, a, w)`).
927    pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<'_, E, Ty, Ix> {
928        Edges {
929            skip_start: a,
930            edges: &self.g.edges,
931            direction: dir,
932            next: match self.get_node(a) {
933                None => [EdgeIndex::end(), EdgeIndex::end()],
934                Some(n) => n.next,
935            },
936            ty: PhantomData,
937        }
938    }
939
940    /// Return an iterator over either the nodes without edges to them
941    /// (`Incoming`) or from them (`Outgoing`).
942    ///
943    /// An *internal* node has both incoming and outgoing edges.
944    /// The nodes in `.externals(Incoming)` are the source nodes and
945    /// `.externals(Outgoing)` are the sinks of the graph.
946    ///
947    /// For a graph with undirected edges, both the sinks and the sources are
948    /// just the nodes without edges.
949    ///
950    /// The whole iteration computes in **O(|V|)** time where V is the set of nodes.
951    pub fn externals(&self, dir: Direction) -> Externals<'_, N, Ty, Ix> {
952        Externals {
953            iter: self.raw_nodes().iter().enumerate(),
954            dir,
955            ty: PhantomData,
956        }
957    }
958
959    /// Convert the `StableGraph` into iterators of Nodes and Edges
960    pub fn into_nodes_edges_iters(
961        self,
962    ) -> (
963        impl Iterator<Item = StableGraphNode<N, Ix>>,
964        impl Iterator<Item = StableGraphEdge<E, Ix>>,
965    ) {
966        let (inner_nodes, inner_edges) = self.g.into_nodes_edges();
967
968        (
969            inner_nodes
970                .into_iter()
971                .enumerate()
972                .filter(|(_, node)| node.weight.is_some())
973                .map(|(index, node)| StableGraphNode {
974                    index: NodeIndex::new(index),
975                    weight: node.weight.unwrap(),
976                }),
977            inner_edges
978                .into_iter()
979                .enumerate()
980                .filter(|(_, edge)| edge.weight.is_some())
981                .map(|(index, edge)| StableGraphEdge {
982                    index: EdgeIndex::new(index),
983                    source: edge.source(),
984                    target: edge.target(),
985                    weight: edge.weight.unwrap(),
986                }),
987        )
988    }
989
990    /// Index the `StableGraph` by two indices, any combination of
991    /// node or edge indices is fine.
992    ///
993    /// **Panics** if the indices are equal or if they are not found.
994    #[track_caller]
995    pub fn index_twice_mut<T, U>(
996        &mut self,
997        i: T,
998        j: U,
999    ) -> (
1000        &mut <Self as Index<T>>::Output,
1001        &mut <Self as Index<U>>::Output,
1002    )
1003    where
1004        Self: IndexMut<T> + IndexMut<U>,
1005        T: GraphIndex,
1006        U: GraphIndex,
1007    {
1008        assert!(T::is_node_index() != U::is_node_index() || i.index() != j.index());
1009
1010        // Allow two mutable indexes here -- they are nonoverlapping
1011        unsafe {
1012            let self_mut = self as *mut _;
1013            (
1014                <Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
1015                <Self as IndexMut<U>>::index_mut(&mut *self_mut, j),
1016            )
1017        }
1018    }
1019
1020    /// Keep all nodes that return `true` from the `visit` closure,
1021    /// remove the others.
1022    ///
1023    /// `visit` is provided a proxy reference to the graph, so that
1024    /// the graph can be walked and associated data modified.
1025    ///
1026    /// The order nodes are visited is not specified.
1027    ///
1028    /// The node indices of the removed nodes are invalidated, but none other.
1029    /// Edge indices are invalidated as they would be following the removal of
1030    /// each edge with an endpoint in a removed node.
1031    ///
1032    /// Computes in **O(n + e')** time, where **n** is the number of node indices and
1033    ///  **e'** is the number of affected edges, including *n* calls to `.remove_edge()`
1034    /// where *n* is the number of edges with an endpoint in a removed node.
1035    pub fn retain_nodes<F>(&mut self, mut visit: F)
1036    where
1037        F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,
1038    {
1039        for i in 0..self.node_bound() {
1040            let ix = node_index(i);
1041            if self.contains_node(ix) && !visit(Frozen(self), ix) {
1042                self.remove_node(ix);
1043            }
1044        }
1045        self.check_free_lists();
1046    }
1047
1048    /// Keep all edges that return `true` from the `visit` closure,
1049    /// remove the others.
1050    ///
1051    /// `visit` is provided a proxy reference to the graph, so that
1052    /// the graph can be walked and associated data modified.
1053    ///
1054    /// The order edges are visited is not specified.
1055    ///
1056    /// The edge indices of the removed edes are invalidated, but none other.
1057    ///
1058    /// Computes in **O(e'')** time, **e'** is the number of affected edges,
1059    /// including the calls to `.remove_edge()` for each removed edge.
1060    pub fn retain_edges<F>(&mut self, mut visit: F)
1061    where
1062        F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,
1063    {
1064        for i in 0..self.edge_bound() {
1065            let ix = edge_index(i);
1066            if self.edge_weight(ix).is_some() && !visit(Frozen(self), ix) {
1067                self.remove_edge(ix);
1068            }
1069        }
1070        self.check_free_lists();
1071    }
1072
1073    /// Create a new `StableGraph` from an iterable of edges.
1074    ///
1075    /// Node weights `N` are set to default values.
1076    /// Edge weights `E` may either be specified in the list,
1077    /// or they are filled with default values.
1078    ///
1079    /// Nodes are inserted automatically to match the edges.
1080    ///
1081    /// ```
1082    /// use petgraph::stable_graph::StableGraph;
1083    ///
1084    /// let gr = StableGraph::<(), i32>::from_edges(&[
1085    ///     (0, 1), (0, 2), (0, 3),
1086    ///     (1, 2), (1, 3),
1087    ///     (2, 3),
1088    /// ]);
1089    /// ```
1090    pub fn from_edges<I>(iterable: I) -> Self
1091    where
1092        I: IntoIterator,
1093        I::Item: IntoWeightedEdge<E>,
1094        <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1095        N: Default,
1096    {
1097        let mut g = Self::with_capacity(0, 0);
1098        g.extend_with_edges(iterable);
1099        g
1100    }
1101
1102    /// Create a new `StableGraph` by mapping node and
1103    /// edge weights to new values.
1104    ///
1105    /// The resulting graph has the same structure and the same
1106    /// graph indices as `self`.
1107    ///
1108    /// If you want a consuming version of this function, see [`map_owned`](struct.StableGraph.html#method.map_owned).
1109    ///
1110    /// ```
1111    /// use petgraph::stable_graph::StableGraph;
1112    ///
1113    /// // Create an undirected graph with city names as node data and their distances as edge data.
1114    /// let mut g = StableGraph::<String, u32>::new();
1115    ///
1116    /// let bie = g.add_node("Bielefeld".to_owned());
1117    /// let del = g.add_node("New Delhi".to_owned());
1118    /// let mex = g.add_node("Mexico City".to_owned());
1119    /// let syd = g.add_node("Sydney".to_owned());
1120    ///
1121    /// // Add distances in kilometers as edge data.
1122    /// g.extend_with_edges(&[
1123    ///     (bie, del, 6_000),
1124    ///     (bie, mex, 10_000),
1125    ///     (bie, syd, 16_000),
1126    ///     (del, mex, 14_000),
1127    ///     (del, syd, 12_000),
1128    ///     (mex, syd, 15_000),
1129    /// ]);
1130    ///
1131    /// // We might now want to change up the distances to be in miles instead and to be strings.
1132    /// // We can do this using the `map` method, which takes two closures for the node and edge data,
1133    /// // respectively, and returns a new graph with the transformed data.
1134    /// let g_miles: StableGraph<String, i32> = g.map(
1135    ///     |_, city| city.to_owned(),
1136    ///     |_, &distance| (distance as f64 * 0.621371).round() as i32,
1137    /// );
1138    ///
1139    /// for &edge_weight in g_miles.edge_weights() {
1140    ///     assert!(edge_weight < 10_000);
1141    /// }
1142    /// ```
1143    pub fn map<'a, F, G, N2, E2>(
1144        &'a self,
1145        mut node_map: F,
1146        mut edge_map: G,
1147    ) -> StableGraph<N2, E2, Ty, Ix>
1148    where
1149        F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
1150        G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
1151    {
1152        let g = self.g.map(
1153            move |i, w| w.as_ref().map(|w| node_map(i, w)),
1154            move |i, w| w.as_ref().map(|w| edge_map(i, w)),
1155        );
1156        StableGraph {
1157            g,
1158            node_count: self.node_count,
1159            edge_count: self.edge_count,
1160            free_node: self.free_node,
1161            free_edge: self.free_edge,
1162        }
1163    }
1164
1165    /// Create a new `StableGraph` by mapping node and
1166    /// edge weights to new values, consuming the current graph.
1167    ///
1168    /// The resulting graph has the same structure and the same
1169    /// graph indices as `self`.
1170    ///
1171    /// If you want a non-consuming version of this function, see [`map`](struct.StableGraph.html#method.map).
1172    ///
1173    /// ```
1174    /// use petgraph::stable_graph::StableGraph;
1175    ///
1176    /// // Create an undirected graph with city names as node data and their distances as edge data.
1177    /// let mut g = StableGraph::<String, u32>::new();
1178    ///
1179    /// let bie = g.add_node("Bielefeld".to_owned());
1180    /// let del = g.add_node("New Delhi".to_owned());
1181    /// let mex = g.add_node("Mexico City".to_owned());
1182    /// let syd = g.add_node("Sydney".to_owned());
1183    ///
1184    /// // Add distances in kilometers as edge data.
1185    /// g.extend_with_edges(&[
1186    ///     (bie, del, 6_000),
1187    ///     (bie, mex, 10_000),
1188    ///     (bie, syd, 16_000),
1189    ///     (del, mex, 14_000),
1190    ///     (del, syd, 12_000),
1191    ///     (mex, syd, 15_000),
1192    /// ]);
1193    ///
1194    /// // We might now want to change up the distances to be in miles instead and to be strings.
1195    /// // We can do this using the `map` method, which takes two closures for the node and edge data,
1196    /// // respectively, and returns a new graph with the transformed data.
1197    /// let g_miles: StableGraph<String, i32> = g.map_owned(
1198    ///     |_, city| city,
1199    ///     |_, distance| (distance as f64 * 0.621371).round() as i32,
1200    /// );
1201    ///
1202    /// for &edge_weight in g_miles.edge_weights() {
1203    ///     assert!(edge_weight < 10_000);
1204    /// }
1205    /// ```
1206    pub fn map_owned<F, G, N2, E2>(
1207        self,
1208        mut node_map: F,
1209        mut edge_map: G,
1210    ) -> StableGraph<N2, E2, Ty, Ix>
1211    where
1212        F: FnMut(NodeIndex<Ix>, N) -> N2,
1213        G: FnMut(EdgeIndex<Ix>, E) -> E2,
1214    {
1215        let g = self.g.map_owned(
1216            move |i, w| w.map(|w| node_map(i, w)),
1217            move |i, w| w.map(|w| edge_map(i, w)),
1218        );
1219        StableGraph {
1220            g,
1221            node_count: self.node_count,
1222            edge_count: self.edge_count,
1223            free_node: self.free_node,
1224            free_edge: self.free_edge,
1225        }
1226    }
1227
1228    /// Create a new `StableGraph` by mapping nodes and edges.
1229    /// A node or edge may be mapped to `None` to exclude it from
1230    /// the resulting graph.
1231    ///
1232    /// Nodes are mapped first with the `node_map` closure, then
1233    /// `edge_map` is called for the edges that have not had any endpoint
1234    /// removed.
1235    ///
1236    /// The resulting graph has the structure of a subgraph of the original graph.
1237    /// Nodes and edges that are not removed maintain their old node or edge
1238    /// indices.
1239    ///
1240    /// If you want a consuming version of this function, see [`filter_map_owned`](struct.StableGraph.html#method.filter_map_owned).
1241    ///
1242    /// ```
1243    /// use petgraph::stable_graph::StableGraph;
1244    ///
1245    /// // Create a graph with integer node weights
1246    /// let mut g = StableGraph::<u32, ()>::new();
1247    /// let a = g.add_node(0);
1248    /// let b = g.add_node(2);
1249    /// let c = g.add_node(5);
1250    /// let d = g.add_node(7);
1251    /// let e = g.add_node(4);
1252    /// g.extend_with_edges(&[(a, b, ()), (a, c, ()), (b, d, ()), (c, d, ()), (d, e, ())]);
1253    ///
1254    /// // Filter the graph such that only nodes with weight greater than 2 are kept.
1255    /// let g_filtered = g.filter_map(
1256    ///     |_, &node_weight| if node_weight > 2 { Some(node_weight) } else { None },
1257    ///     |_, &edge_weight| Some(edge_weight),
1258    /// );
1259    ///
1260    /// assert_eq!(g_filtered.node_count(), 3);
1261    /// // Node and edge indices are preserved.
1262    /// assert_eq!(g_filtered.node_weight(c), Some(&5));
1263    /// ```
1264    pub fn filter_map<'a, F, G, N2, E2>(
1265        &'a self,
1266        mut node_map: F,
1267        mut edge_map: G,
1268    ) -> StableGraph<N2, E2, Ty, Ix>
1269    where
1270        F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
1271        G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
1272    {
1273        let node_bound = self.node_bound();
1274        let edge_bound = self.edge_bound();
1275        let mut result_g = StableGraph::with_capacity(node_bound, edge_bound);
1276        // use separate free lists so that
1277        // add_node / add_edge below do not reuse the tombstones
1278        let mut free_node = NodeIndex::end();
1279        let mut free_edge = EdgeIndex::end();
1280
1281        // the stable graph keeps the node map itself
1282
1283        for (i, node) in self.raw_nodes().iter().enumerate() {
1284            if i >= node_bound {
1285                break;
1286            }
1287            if let Some(node_weight) = node.weight.as_ref() {
1288                if let Some(new_weight) = node_map(NodeIndex::new(i), node_weight) {
1289                    result_g.add_node(new_weight);
1290                    continue;
1291                }
1292            }
1293            result_g.add_vacant_node(&mut free_node);
1294        }
1295        for (i, edge) in self.raw_edges().iter().enumerate() {
1296            if i >= edge_bound {
1297                break;
1298            }
1299            let source = edge.source();
1300            let target = edge.target();
1301            if let Some(edge_weight) = edge.weight.as_ref() {
1302                if result_g.contains_node(source) && result_g.contains_node(target) {
1303                    if let Some(new_weight) = edge_map(EdgeIndex::new(i), edge_weight) {
1304                        result_g.add_edge(source, target, new_weight);
1305                        continue;
1306                    }
1307                }
1308            }
1309            result_g.add_vacant_edge(&mut free_edge);
1310        }
1311        result_g.free_node = free_node;
1312        result_g.free_edge = free_edge;
1313        result_g.check_free_lists();
1314        result_g
1315    }
1316
1317    /// Create a new `StableGraph` by mapping nodes and edges, consuming the current graph.
1318    /// A node or edge may be mapped to `None` to exclude it from
1319    /// the resulting graph.
1320    ///
1321    /// Nodes are mapped first with the `node_map` closure, then
1322    /// `edge_map` is called for the edges that have not had any endpoint
1323    /// removed.
1324    ///
1325    /// The resulting graph has the structure of a subgraph of the original graph.
1326    /// Nodes and edges that are not removed maintain their old node or edge
1327    /// indices.
1328    ///
1329    /// If you want a non-consuming version of this function, see [`filter_map`](struct.StableGraph.html#method.filter_map).
1330    ///
1331    /// ```
1332    /// use petgraph::stable_graph::StableGraph;
1333    ///
1334    /// // Create a graph with integer node weights
1335    /// let mut g = StableGraph::<u32, ()>::new();
1336    /// let a = g.add_node(0);
1337    /// let b = g.add_node(2);
1338    /// let c = g.add_node(5);
1339    /// let d = g.add_node(7);
1340    /// let e = g.add_node(4);
1341    /// g.extend_with_edges(&[(a, b, ()), (a, c, ()), (b, d, ()), (c, d, ()), (d, e, ())]);
1342    ///
1343    /// // Filter the graph such that only nodes with weight greater than 2 are kept.
1344    /// let g_filtered = g.filter_map_owned(
1345    ///     |_, node_weight| if node_weight > 2 { Some(node_weight) } else { None },
1346    ///     |_, edge_weight| Some(edge_weight),
1347    /// );
1348    ///
1349    /// assert_eq!(g_filtered.node_count(), 3);
1350    /// // Node and edge indices are preserved.
1351    /// assert_eq!(g_filtered.node_weight(c), Some(&5));
1352    /// ```
1353    pub fn filter_map_owned<F, G, N2, E2>(
1354        self,
1355        mut node_map: F,
1356        mut edge_map: G,
1357    ) -> StableGraph<N2, E2, Ty, Ix>
1358    where
1359        F: FnMut(NodeIndex<Ix>, N) -> Option<N2>,
1360        G: FnMut(EdgeIndex<Ix>, E) -> Option<E2>,
1361    {
1362        let node_bound = self.node_bound();
1363        let edge_bound = self.edge_bound();
1364        let mut result_g = StableGraph::with_capacity(node_bound, edge_bound);
1365        // use separate free lists so that
1366        // add_node / add_edge below do not reuse the tombstones
1367        let mut free_node = NodeIndex::end();
1368        let mut free_edge = EdgeIndex::end();
1369
1370        // the stable graph keeps the node map itself
1371
1372        let (nodes, edges) = self.g.into_nodes_edges();
1373
1374        for (i, node) in nodes.into_iter().enumerate() {
1375            if i >= node_bound {
1376                break;
1377            }
1378            if let Some(node_weight) = node.weight {
1379                if let Some(new_weight) = node_map(NodeIndex::new(i), node_weight) {
1380                    result_g.add_node(new_weight);
1381                    continue;
1382                }
1383            }
1384            result_g.add_vacant_node(&mut free_node);
1385        }
1386        for (i, edge) in edges.into_iter().enumerate() {
1387            if i >= edge_bound {
1388                break;
1389            }
1390            let source = edge.source();
1391            let target = edge.target();
1392            if let Some(edge_weight) = edge.weight {
1393                if result_g.contains_node(source) && result_g.contains_node(target) {
1394                    if let Some(new_weight) = edge_map(EdgeIndex::new(i), edge_weight) {
1395                        result_g.add_edge(source, target, new_weight);
1396                        continue;
1397                    }
1398                }
1399            }
1400            result_g.add_vacant_edge(&mut free_edge);
1401        }
1402        result_g.free_node = free_node;
1403        result_g.free_edge = free_edge;
1404        result_g.check_free_lists();
1405        result_g
1406    }
1407
1408    /// Extend the graph from an iterable of edges.
1409    ///
1410    /// Node weights `N` are set to default values.
1411    /// Edge weights `E` may either be specified in the list,
1412    /// or they are filled with default values.
1413    ///
1414    /// Nodes are inserted automatically to match the edges.
1415    ///
1416    /// ```
1417    /// use petgraph::stable_graph::StableGraph;
1418    ///
1419    /// let mut g = StableGraph::<(), i32>::new();
1420    /// let a = g.add_node(());
1421    /// let b = g.add_node(());
1422    /// let c = g.add_node(());
1423    /// let d = g.add_node(());
1424    ///
1425    /// g.extend_with_edges(&[
1426    ///   (a, b, 7),
1427    ///   (a, c, 8),
1428    ///   (a, d, 9),
1429    ///  (b, c, 10),
1430    /// ]);
1431    /// ```
1432    pub fn extend_with_edges<I>(&mut self, iterable: I)
1433    where
1434        I: IntoIterator,
1435        I::Item: IntoWeightedEdge<E>,
1436        <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1437        N: Default,
1438    {
1439        let iter = iterable.into_iter();
1440
1441        for elt in iter {
1442            let (source, target, weight) = elt.into_weighted_edge();
1443            let (source, target) = (source.into(), target.into());
1444            self.ensure_node_exists(source);
1445            self.ensure_node_exists(target);
1446            self.add_edge(source, target, weight);
1447        }
1448    }
1449
1450    //
1451    // internal methods
1452    //
1453    fn raw_nodes(&self) -> &[Node<Option<N>, Ix>] {
1454        self.g.raw_nodes()
1455    }
1456
1457    fn raw_edges(&self) -> &[Edge<Option<E>, Ix>] {
1458        self.g.raw_edges()
1459    }
1460
1461    /// Create a new node using a vacant position,
1462    /// updating the free nodes doubly linked list.
1463    fn occupy_vacant_node(&mut self, node_idx: NodeIndex<Ix>, weight: N) {
1464        let node_slot = &mut self.g.nodes[node_idx.index()];
1465        let _old = node_slot.weight.replace(weight);
1466        debug_assert!(_old.is_none());
1467        let previous_node = node_slot.next[1];
1468        let next_node = node_slot.next[0];
1469        node_slot.next = [EdgeIndex::end(), EdgeIndex::end()];
1470        if previous_node != EdgeIndex::end() {
1471            self.g.nodes[previous_node.index()].next[0] = next_node;
1472        }
1473        if next_node != EdgeIndex::end() {
1474            self.g.nodes[next_node.index()].next[1] = previous_node;
1475        }
1476        if self.free_node == node_idx {
1477            self.free_node = next_node._into_node();
1478        }
1479        self.node_count += 1;
1480    }
1481
1482    /// Create the node if it does not exist,
1483    /// adding vacant nodes for padding if needed.
1484    fn ensure_node_exists(&mut self, node_ix: NodeIndex<Ix>)
1485    where
1486        N: Default,
1487    {
1488        if let Some(Some(_)) = self.g.node_weight(node_ix) {
1489            return;
1490        }
1491        while node_ix.index() >= self.g.node_count() {
1492            let mut free_node = self.free_node;
1493            self.add_vacant_node(&mut free_node);
1494            self.free_node = free_node;
1495        }
1496        self.occupy_vacant_node(node_ix, N::default());
1497    }
1498
1499    #[cfg(feature = "serde-1")]
1500    /// Fix up node and edge links after deserialization
1501    fn link_edges(&mut self) -> Result<(), NodeIndex<Ix>> {
1502        // set up free node list
1503        self.node_count = 0;
1504        self.edge_count = 0;
1505        let mut free_node = NodeIndex::end();
1506        for node_index in 0..self.g.node_count() {
1507            let node = &mut self.g.nodes[node_index];
1508            if node.weight.is_some() {
1509                self.node_count += 1;
1510            } else {
1511                // free node
1512                node.next = [free_node._into_edge(), EdgeIndex::end()];
1513                if free_node != NodeIndex::end() {
1514                    self.g.nodes[free_node.index()].next[1] = EdgeIndex::new(node_index);
1515                }
1516                free_node = NodeIndex::new(node_index);
1517            }
1518        }
1519        self.free_node = free_node;
1520
1521        let mut free_edge = EdgeIndex::end();
1522        for (edge_index, edge) in self.g.edges.iter_mut().enumerate() {
1523            if edge.weight.is_none() {
1524                // free edge
1525                edge.next = [free_edge, EdgeIndex::end()];
1526                free_edge = EdgeIndex::new(edge_index);
1527                continue;
1528            }
1529            let a = edge.source();
1530            let b = edge.target();
1531            let edge_idx = EdgeIndex::new(edge_index);
1532            match index_twice(&mut self.g.nodes, a.index(), b.index()) {
1533                Pair::None => return Err(if a > b { a } else { b }),
1534                Pair::One(an) => {
1535                    edge.next = an.next;
1536                    an.next[0] = edge_idx;
1537                    an.next[1] = edge_idx;
1538                }
1539                Pair::Both(an, bn) => {
1540                    // a and b are different indices
1541                    edge.next = [an.next[0], bn.next[1]];
1542                    an.next[0] = edge_idx;
1543                    bn.next[1] = edge_idx;
1544                }
1545            }
1546            self.edge_count += 1;
1547        }
1548        self.free_edge = free_edge;
1549        Ok(())
1550    }
1551
1552    #[cfg(not(debug_assertions))]
1553    fn check_free_lists(&self) {}
1554    #[cfg(debug_assertions)]
1555    // internal method to debug check the free lists (linked lists)
1556    // For the nodes, also check the backpointers of the doubly linked list.
1557    fn check_free_lists(&self) {
1558        let mut free_node = self.free_node;
1559        let mut prev_free_node = NodeIndex::end();
1560        let mut free_node_len = 0;
1561        while free_node != NodeIndex::end() {
1562            if let Some(n) = self.g.nodes.get(free_node.index()) {
1563                if n.weight.is_none() {
1564                    debug_assert_eq!(n.next[1]._into_node(), prev_free_node);
1565                    prev_free_node = free_node;
1566                    free_node = n.next[0]._into_node();
1567                    free_node_len += 1;
1568                    continue;
1569                }
1570                debug_assert!(
1571                    false,
1572                    "Corrupt free list: pointing to existing {:?}",
1573                    free_node.index()
1574                );
1575            }
1576            debug_assert!(false, "Corrupt free list: missing {:?}", free_node.index());
1577        }
1578        debug_assert_eq!(self.node_count(), self.raw_nodes().len() - free_node_len);
1579
1580        let mut free_edge_len = 0;
1581        let mut free_edge = self.free_edge;
1582        while free_edge != EdgeIndex::end() {
1583            if let Some(n) = self.g.edges.get(free_edge.index()) {
1584                if n.weight.is_none() {
1585                    free_edge = n.next[0];
1586                    free_edge_len += 1;
1587                    continue;
1588                }
1589                debug_assert!(
1590                    false,
1591                    "Corrupt free list: pointing to existing {:?}",
1592                    free_node.index()
1593                );
1594            }
1595            debug_assert!(false, "Corrupt free list: missing {:?}", free_edge.index());
1596        }
1597        debug_assert_eq!(self.edge_count(), self.raw_edges().len() - free_edge_len);
1598    }
1599}
1600
1601/// The resulting cloned graph has the same graph indices as `self`.
1602impl<N, E, Ty, Ix> Clone for StableGraph<N, E, Ty, Ix>
1603where
1604    N: Clone,
1605    E: Clone,
1606    Ix: Copy,
1607{
1608    fn clone(&self) -> Self {
1609        StableGraph {
1610            g: self.g.clone(),
1611            node_count: self.node_count,
1612            edge_count: self.edge_count,
1613            free_node: self.free_node,
1614            free_edge: self.free_edge,
1615        }
1616    }
1617
1618    fn clone_from(&mut self, rhs: &Self) {
1619        self.g.clone_from(&rhs.g);
1620        self.node_count = rhs.node_count;
1621        self.edge_count = rhs.edge_count;
1622        self.free_node = rhs.free_node;
1623        self.free_edge = rhs.free_edge;
1624    }
1625}
1626
1627/// Index the `StableGraph` by `NodeIndex` to access node weights.
1628///
1629/// **Panics** if the node doesn't exist.
1630impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1631where
1632    Ty: EdgeType,
1633    Ix: IndexType,
1634{
1635    type Output = N;
1636    fn index(&self, index: NodeIndex<Ix>) -> &N {
1637        self.node_weight(index).unwrap()
1638    }
1639}
1640
1641/// Index the `StableGraph` by `NodeIndex` to access node weights.
1642///
1643/// **Panics** if the node doesn't exist.
1644impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1645where
1646    Ty: EdgeType,
1647    Ix: IndexType,
1648{
1649    fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1650        self.node_weight_mut(index).unwrap()
1651    }
1652}
1653
1654/// Index the `StableGraph` by `EdgeIndex` to access edge weights.
1655///
1656/// **Panics** if the edge doesn't exist.
1657impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1658where
1659    Ty: EdgeType,
1660    Ix: IndexType,
1661{
1662    type Output = E;
1663    fn index(&self, index: EdgeIndex<Ix>) -> &E {
1664        self.edge_weight(index).unwrap()
1665    }
1666}
1667
1668/// Index the `StableGraph` by `EdgeIndex` to access edge weights.
1669///
1670/// **Panics** if the edge doesn't exist.
1671impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1672where
1673    Ty: EdgeType,
1674    Ix: IndexType,
1675{
1676    fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
1677        self.edge_weight_mut(index).unwrap()
1678    }
1679}
1680
1681/// Create a new empty `StableGraph`.
1682impl<N, E, Ty, Ix> Default for StableGraph<N, E, Ty, Ix>
1683where
1684    Ix: IndexType,
1685{
1686    fn default() -> Self {
1687        Self::with_capacity(0, 0)
1688    }
1689}
1690
1691/// Convert a `Graph` into a `StableGraph`
1692///
1693/// Computes in **O(|V| + |E|)** time where V is the set of nodes and E is the set of edges.
1694///
1695/// The resulting graph has the same node and edge indices as
1696/// the original graph.
1697impl<N, E, Ty, Ix> From<Graph<N, E, Ty, Ix>> for StableGraph<N, E, Ty, Ix>
1698where
1699    Ty: EdgeType,
1700    Ix: IndexType,
1701{
1702    fn from(g: Graph<N, E, Ty, Ix>) -> Self {
1703        let nodes = g.nodes.into_iter().map(|e| Node {
1704            weight: Some(e.weight),
1705            next: e.next,
1706        });
1707        let edges = g.edges.into_iter().map(|e| Edge {
1708            weight: Some(e.weight),
1709            node: e.node,
1710            next: e.next,
1711        });
1712        StableGraph {
1713            node_count: nodes.len(),
1714            edge_count: edges.len(),
1715            g: Graph {
1716                edges: edges.collect(),
1717                nodes: nodes.collect(),
1718                ty: g.ty,
1719            },
1720            free_node: NodeIndex::end(),
1721            free_edge: EdgeIndex::end(),
1722        }
1723    }
1724}
1725
1726/// Convert a `StableGraph` into a `Graph`
1727///
1728/// Computes in **O(|V| + |E|)** time where V is the set of nodes and E is the set of edges.
1729///
1730/// This translates the stable graph into a graph with node and edge indices in
1731/// a compact interval without holes (like `Graph`s always are).
1732///
1733/// Only if the stable graph had no vacancies after deletions (if node bound was
1734/// equal to node count, and the same for edges), would the resulting graph have
1735/// the same node and edge indices as the input.
1736impl<N, E, Ty, Ix> From<StableGraph<N, E, Ty, Ix>> for Graph<N, E, Ty, Ix>
1737where
1738    Ty: EdgeType,
1739    Ix: IndexType,
1740{
1741    fn from(graph: StableGraph<N, E, Ty, Ix>) -> Self {
1742        let mut result_g = Graph::with_capacity(graph.node_count(), graph.edge_count());
1743        // mapping from old node index to new node index
1744        let mut node_index_map = vec![NodeIndex::end(); graph.node_bound()];
1745
1746        for (i, node) in graph.g.nodes.into_iter().enumerate() {
1747            if let Some(nw) = node.weight {
1748                node_index_map[i] = result_g.add_node(nw);
1749            }
1750        }
1751        for edge in graph.g.edges {
1752            let source_index = edge.source().index();
1753            let target_index = edge.target().index();
1754            if let Some(ew) = edge.weight {
1755                let source = node_index_map[source_index];
1756                let target = node_index_map[target_index];
1757                debug_assert!(source != NodeIndex::end());
1758                debug_assert!(target != NodeIndex::end());
1759                result_g.add_edge(source, target, ew);
1760            }
1761        }
1762        result_g
1763    }
1764}
1765
1766/// Iterator over all nodes of a graph.
1767#[derive(Debug, Clone)]
1768pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
1769    iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1770}
1771
1772impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
1773where
1774    Ix: IndexType,
1775{
1776    type Item = (NodeIndex<Ix>, &'a N);
1777
1778    fn next(&mut self) -> Option<Self::Item> {
1779        self.iter
1780            .ex_find_map(|(i, node)| node.weight.as_ref().map(move |w| (node_index(i), w)))
1781    }
1782
1783    fn size_hint(&self) -> (usize, Option<usize>) {
1784        let (_, hi) = self.iter.size_hint();
1785        (0, hi)
1786    }
1787}
1788
1789impl<N, Ix> DoubleEndedIterator for NodeReferences<'_, N, Ix>
1790where
1791    Ix: IndexType,
1792{
1793    fn next_back(&mut self) -> Option<Self::Item> {
1794        self.iter
1795            .ex_rfind_map(|(i, node)| node.weight.as_ref().map(move |w| (node_index(i), w)))
1796    }
1797}
1798
1799/// Reference to a `StableGraph` edge.
1800#[derive(Debug)]
1801pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
1802    index: EdgeIndex<Ix>,
1803    node: [NodeIndex<Ix>; 2],
1804    weight: &'a E,
1805}
1806
1807impl<E, Ix: IndexType> Clone for EdgeReference<'_, E, Ix> {
1808    fn clone(&self) -> Self {
1809        *self
1810    }
1811}
1812
1813impl<E, Ix: IndexType> Copy for EdgeReference<'_, E, Ix> {}
1814
1815impl<E, Ix: IndexType> PartialEq for EdgeReference<'_, E, Ix>
1816where
1817    E: PartialEq,
1818{
1819    fn eq(&self, rhs: &Self) -> bool {
1820        self.index == rhs.index && self.weight == rhs.weight
1821    }
1822}
1823
1824impl<'a, Ix, E> EdgeReference<'a, E, Ix>
1825where
1826    Ix: IndexType,
1827{
1828    /// Access the edge’s weight.
1829    ///
1830    /// **NOTE** that this method offers a longer lifetime
1831    /// than the trait (unfortunately they don't match yet).
1832    pub fn weight(&self) -> &'a E {
1833        self.weight
1834    }
1835}
1836
1837/// Iterator over the edges of from or to a node
1838#[derive(Debug, Clone)]
1839pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1840where
1841    Ty: EdgeType,
1842    Ix: IndexType,
1843{
1844    /// starting node to skip over
1845    skip_start: NodeIndex<Ix>,
1846    edges: &'a [Edge<Option<E>, Ix>],
1847
1848    /// Next edge to visit.
1849    next: [EdgeIndex<Ix>; 2],
1850
1851    /// For directed graphs: the direction to iterate in
1852    /// For undirected graphs: the direction of edges
1853    direction: Direction,
1854    ty: PhantomData<Ty>,
1855}
1856
1857impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1858where
1859    Ty: EdgeType,
1860    Ix: IndexType,
1861{
1862    type Item = EdgeReference<'a, E, Ix>;
1863
1864    fn next(&mut self) -> Option<Self::Item> {
1865        //      type        direction    |    iterate over    reverse
1866        //                               |
1867        //    Directed      Outgoing     |      outgoing        no
1868        //    Directed      Incoming     |      incoming        no
1869        //   Undirected     Outgoing     |        both       incoming
1870        //   Undirected     Incoming     |        both       outgoing
1871
1872        // For iterate_over, "both" is represented as None.
1873        // For reverse, "no" is represented as None.
1874        let (iterate_over, reverse) = if Ty::is_directed() {
1875            (Some(self.direction), None)
1876        } else {
1877            (None, Some(self.direction.opposite()))
1878        };
1879
1880        if iterate_over.unwrap_or(Outgoing) == Outgoing {
1881            let i = self.next[0].index();
1882            if let Some(Edge {
1883                node,
1884                weight: Some(weight),
1885                next,
1886            }) = self.edges.get(i)
1887            {
1888                self.next[0] = next[0];
1889                return Some(EdgeReference {
1890                    index: edge_index(i),
1891                    node: if reverse == Some(Outgoing) {
1892                        swap_pair(*node)
1893                    } else {
1894                        *node
1895                    },
1896                    weight,
1897                });
1898            }
1899        }
1900
1901        if iterate_over.unwrap_or(Incoming) == Incoming {
1902            while let Some(Edge { node, weight, next }) = self.edges.get(self.next[1].index()) {
1903                debug_assert!(weight.is_some());
1904                let edge_index = self.next[1];
1905                self.next[1] = next[1];
1906                // In any of the "both" situations, self-loops would be iterated over twice.
1907                // Skip them here.
1908                if iterate_over.is_none() && node[0] == self.skip_start {
1909                    continue;
1910                }
1911
1912                return Some(EdgeReference {
1913                    index: edge_index,
1914                    node: if reverse == Some(Incoming) {
1915                        swap_pair(*node)
1916                    } else {
1917                        *node
1918                    },
1919                    weight: weight.as_ref().unwrap(),
1920                });
1921            }
1922        }
1923
1924        None
1925    }
1926}
1927
1928/// Iterator over the multiple directed edges connecting a source node to a target node
1929#[derive(Debug, Clone)]
1930pub struct EdgesConnecting<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1931where
1932    Ty: EdgeType,
1933    Ix: IndexType,
1934{
1935    target_node: NodeIndex<Ix>,
1936    edges: Edges<'a, E, Ty, Ix>,
1937    ty: PhantomData<Ty>,
1938}
1939
1940impl<'a, E, Ty, Ix> Iterator for EdgesConnecting<'a, E, Ty, Ix>
1941where
1942    Ty: EdgeType,
1943    Ix: IndexType,
1944{
1945    type Item = EdgeReference<'a, E, Ix>;
1946
1947    fn next(&mut self) -> Option<EdgeReference<'a, E, Ix>> {
1948        let target_node = self.target_node;
1949        self.edges
1950            .by_ref()
1951            .find(|&edge| edge.node[1] == target_node)
1952    }
1953    fn size_hint(&self) -> (usize, Option<usize>) {
1954        let (_, upper) = self.edges.size_hint();
1955        (0, upper)
1956    }
1957}
1958
1959fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1960    x.swap(0, 1);
1961    x
1962}
1963
1964/// Iterator over all edges of a graph.
1965#[derive(Debug, Clone)]
1966pub struct EdgeReferences<'a, E: 'a, Ix: 'a = DefaultIx> {
1967    iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1968}
1969
1970impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
1971where
1972    Ix: IndexType,
1973{
1974    type Item = EdgeReference<'a, E, Ix>;
1975
1976    fn next(&mut self) -> Option<Self::Item> {
1977        self.iter.ex_find_map(|(i, edge)| {
1978            edge.weight.as_ref().map(move |weight| EdgeReference {
1979                index: edge_index(i),
1980                node: edge.node,
1981                weight,
1982            })
1983        })
1984    }
1985}
1986
1987impl<E, Ix> DoubleEndedIterator for EdgeReferences<'_, E, Ix>
1988where
1989    Ix: IndexType,
1990{
1991    fn next_back(&mut self) -> Option<Self::Item> {
1992        self.iter.ex_rfind_map(|(i, edge)| {
1993            edge.weight.as_ref().map(move |weight| EdgeReference {
1994                index: edge_index(i),
1995                node: edge.node,
1996                weight,
1997            })
1998        })
1999    }
2000}
2001
2002/// An iterator over either the nodes without edges to them or from them.
2003#[derive(Debug, Clone)]
2004pub struct Externals<'a, N: 'a, Ty, Ix: IndexType = DefaultIx> {
2005    iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
2006    dir: Direction,
2007    ty: PhantomData<Ty>,
2008}
2009
2010impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix>
2011where
2012    Ty: EdgeType,
2013    Ix: IndexType,
2014{
2015    type Item = NodeIndex<Ix>;
2016    fn next(&mut self) -> Option<NodeIndex<Ix>> {
2017        let k = self.dir.index();
2018        loop {
2019            match self.iter.next() {
2020                None => return None,
2021                Some((index, node)) => {
2022                    if node.weight.is_some()
2023                        && node.next[k] == EdgeIndex::end()
2024                        && (Ty::is_directed() || node.next[1 - k] == EdgeIndex::end())
2025                    {
2026                        return Some(NodeIndex::new(index));
2027                    } else {
2028                        continue;
2029                    }
2030                }
2031            }
2032        }
2033    }
2034    fn size_hint(&self) -> (usize, Option<usize>) {
2035        let (_, upper) = self.iter.size_hint();
2036        (0, upper)
2037    }
2038}
2039
2040/// Iterator over the neighbors of a node.
2041///
2042/// Iterator element type is `NodeIndex`.
2043#[derive(Debug, Clone)]
2044pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx> {
2045    /// starting node to skip over
2046    skip_start: NodeIndex<Ix>,
2047    edges: &'a [Edge<Option<E>, Ix>],
2048    next: [EdgeIndex<Ix>; 2],
2049}
2050
2051impl<E, Ix> Neighbors<'_, E, Ix>
2052where
2053    Ix: IndexType,
2054{
2055    /// Return a “walker” object that can be used to step through the
2056    /// neighbors and edges from the origin node.
2057    ///
2058    /// Note: The walker does not borrow from the graph, this is to allow mixing
2059    /// edge walking with mutating the graph's weights.
2060    pub fn detach(&self) -> WalkNeighbors<Ix> {
2061        WalkNeighbors {
2062            inner: super::WalkNeighbors {
2063                skip_start: self.skip_start,
2064                next: self.next,
2065            },
2066        }
2067    }
2068}
2069
2070impl<E, Ix> Iterator for Neighbors<'_, E, Ix>
2071where
2072    Ix: IndexType,
2073{
2074    type Item = NodeIndex<Ix>;
2075
2076    fn next(&mut self) -> Option<NodeIndex<Ix>> {
2077        // First any outgoing edges
2078        match self.edges.get(self.next[0].index()) {
2079            None => {}
2080            Some(edge) => {
2081                debug_assert!(edge.weight.is_some());
2082                self.next[0] = edge.next[0];
2083                return Some(edge.node[1]);
2084            }
2085        }
2086        // Then incoming edges
2087        // For an "undirected" iterator (traverse both incoming
2088        // and outgoing edge lists), make sure we don't double
2089        // count selfloops by skipping them in the incoming list.
2090        while let Some(edge) = self.edges.get(self.next[1].index()) {
2091            debug_assert!(edge.weight.is_some());
2092            self.next[1] = edge.next[1];
2093            if edge.node[0] != self.skip_start {
2094                return Some(edge.node[0]);
2095            }
2096        }
2097        None
2098    }
2099}
2100
2101/// A “walker” object that can be used to step through the edge list of a node.
2102///
2103/// See [*.detach()*](struct.Neighbors.html#method.detach) for more information.
2104///
2105/// The walker does not borrow from the graph, so it lets you step through
2106/// neighbors or incident edges while also mutating graph weights, as
2107/// in the following example:
2108///
2109/// ```
2110/// use petgraph::visit::Dfs;
2111/// use petgraph::Incoming;
2112/// use petgraph::stable_graph::StableGraph;
2113///
2114/// let mut gr = StableGraph::new();
2115/// let a = gr.add_node(0.);
2116/// let b = gr.add_node(0.);
2117/// let c = gr.add_node(0.);
2118/// gr.add_edge(a, b, 3.);
2119/// gr.add_edge(b, c, 2.);
2120/// gr.add_edge(c, b, 1.);
2121///
2122/// // step through the graph and sum incoming edges into the node weight
2123/// let mut dfs = Dfs::new(&gr, a);
2124/// while let Some(node) = dfs.next(&gr) {
2125///     // use a detached neighbors walker
2126///     let mut edges = gr.neighbors_directed(node, Incoming).detach();
2127///     while let Some(edge) = edges.next_edge(&gr) {
2128///         gr[node] += gr[edge];
2129///     }
2130/// }
2131///
2132/// // check the result
2133/// assert_eq!(gr[a], 0.);
2134/// assert_eq!(gr[b], 4.);
2135/// assert_eq!(gr[c], 2.);
2136/// ```
2137pub struct WalkNeighbors<Ix> {
2138    inner: super::WalkNeighbors<Ix>,
2139}
2140
2141impl<Ix: IndexType> Clone for WalkNeighbors<Ix> {
2142    clone_fields!(WalkNeighbors, inner);
2143}
2144
2145impl<Ix: IndexType> WalkNeighbors<Ix> {
2146    /// Step to the next edge and its endpoint node in the walk for graph `g`.
2147    ///
2148    /// The next node indices are always the others than the starting point
2149    /// where the `WalkNeighbors` value was created.
2150    /// For an `Outgoing` walk, the target nodes,
2151    /// for an `Incoming` walk, the source nodes of the edge.
2152    pub fn next<N, E, Ty: EdgeType>(
2153        &mut self,
2154        g: &StableGraph<N, E, Ty, Ix>,
2155    ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
2156        self.inner.next(&g.g)
2157    }
2158
2159    pub fn next_node<N, E, Ty: EdgeType>(
2160        &mut self,
2161        g: &StableGraph<N, E, Ty, Ix>,
2162    ) -> Option<NodeIndex<Ix>> {
2163        self.next(g).map(|t| t.1)
2164    }
2165
2166    pub fn next_edge<N, E, Ty: EdgeType>(
2167        &mut self,
2168        g: &StableGraph<N, E, Ty, Ix>,
2169    ) -> Option<EdgeIndex<Ix>> {
2170        self.next(g).map(|t| t.0)
2171    }
2172}
2173
2174/// Iterator over the node indices of a graph.
2175#[derive(Debug, Clone)]
2176pub struct NodeIndices<'a, N: 'a, Ix: 'a = DefaultIx> {
2177    iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
2178}
2179
2180impl<N, Ix: IndexType> Iterator for NodeIndices<'_, N, Ix> {
2181    type Item = NodeIndex<Ix>;
2182
2183    fn next(&mut self) -> Option<Self::Item> {
2184        self.iter.ex_find_map(|(i, node)| {
2185            if node.weight.is_some() {
2186                Some(node_index(i))
2187            } else {
2188                None
2189            }
2190        })
2191    }
2192    fn size_hint(&self) -> (usize, Option<usize>) {
2193        let (_, upper) = self.iter.size_hint();
2194        (0, upper)
2195    }
2196}
2197
2198impl<N, Ix: IndexType> DoubleEndedIterator for NodeIndices<'_, N, Ix> {
2199    fn next_back(&mut self) -> Option<Self::Item> {
2200        self.iter.ex_rfind_map(|(i, node)| {
2201            if node.weight.is_some() {
2202                Some(node_index(i))
2203            } else {
2204                None
2205            }
2206        })
2207    }
2208}
2209
2210/// Iterator over the edge indices of a graph.
2211///
2212/// Note: `EdgeIndices` borrows a graph.
2213#[derive(Debug, Clone)]
2214pub struct EdgeIndices<'a, E: 'a, Ix: 'a = DefaultIx> {
2215    iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
2216}
2217
2218impl<E, Ix: IndexType> Iterator for EdgeIndices<'_, E, Ix> {
2219    type Item = EdgeIndex<Ix>;
2220
2221    fn next(&mut self) -> Option<Self::Item> {
2222        self.iter.ex_find_map(|(i, node)| {
2223            if node.weight.is_some() {
2224                Some(edge_index(i))
2225            } else {
2226                None
2227            }
2228        })
2229    }
2230    fn size_hint(&self) -> (usize, Option<usize>) {
2231        let (_, upper) = self.iter.size_hint();
2232        (0, upper)
2233    }
2234}
2235
2236impl<E, Ix: IndexType> DoubleEndedIterator for EdgeIndices<'_, E, Ix> {
2237    fn next_back(&mut self) -> Option<Self::Item> {
2238        self.iter.ex_rfind_map(|(i, node)| {
2239            if node.weight.is_some() {
2240                Some(edge_index(i))
2241            } else {
2242                None
2243            }
2244        })
2245    }
2246}
2247
2248impl<N, E, Ty, Ix> visit::GraphBase for StableGraph<N, E, Ty, Ix>
2249where
2250    Ix: IndexType,
2251{
2252    type NodeId = NodeIndex<Ix>;
2253    type EdgeId = EdgeIndex<Ix>;
2254}
2255
2256impl<N, E, Ty, Ix> visit::Visitable for StableGraph<N, E, Ty, Ix>
2257where
2258    Ty: EdgeType,
2259    Ix: IndexType,
2260{
2261    type Map = FixedBitSet;
2262    fn visit_map(&self) -> FixedBitSet {
2263        FixedBitSet::with_capacity(self.node_bound())
2264    }
2265    fn reset_map(&self, map: &mut Self::Map) {
2266        map.clear();
2267        map.grow(self.node_bound());
2268    }
2269}
2270
2271impl<N, E, Ty, Ix> visit::Data for StableGraph<N, E, Ty, Ix>
2272where
2273    Ty: EdgeType,
2274    Ix: IndexType,
2275{
2276    type NodeWeight = N;
2277    type EdgeWeight = E;
2278}
2279
2280impl<N, E, Ty, Ix> visit::GraphProp for StableGraph<N, E, Ty, Ix>
2281where
2282    Ty: EdgeType,
2283    Ix: IndexType,
2284{
2285    type EdgeType = Ty;
2286}
2287
2288impl<'a, N, E: 'a, Ty, Ix> visit::IntoNodeIdentifiers for &'a StableGraph<N, E, Ty, Ix>
2289where
2290    Ty: EdgeType,
2291    Ix: IndexType,
2292{
2293    type NodeIdentifiers = NodeIndices<'a, N, Ix>;
2294    fn node_identifiers(self) -> Self::NodeIdentifiers {
2295        StableGraph::node_indices(self)
2296    }
2297}
2298
2299impl<N, E, Ty, Ix> visit::NodeCount for StableGraph<N, E, Ty, Ix>
2300where
2301    Ty: EdgeType,
2302    Ix: IndexType,
2303{
2304    fn node_count(&self) -> usize {
2305        self.node_count()
2306    }
2307}
2308
2309impl<'a, N, E, Ty, Ix> visit::IntoNodeReferences for &'a StableGraph<N, E, Ty, Ix>
2310where
2311    Ty: EdgeType,
2312    Ix: IndexType,
2313{
2314    type NodeRef = (NodeIndex<Ix>, &'a N);
2315    type NodeReferences = NodeReferences<'a, N, Ix>;
2316    fn node_references(self) -> Self::NodeReferences {
2317        NodeReferences {
2318            iter: self.raw_nodes().iter().enumerate(),
2319        }
2320    }
2321}
2322
2323impl<N, E, Ty, Ix> visit::NodeIndexable for StableGraph<N, E, Ty, Ix>
2324where
2325    Ty: EdgeType,
2326    Ix: IndexType,
2327{
2328    /// Return an upper bound of the node indices in the graph
2329    fn node_bound(&self) -> usize {
2330        self.node_indices().next_back().map_or(0, |i| i.index() + 1)
2331    }
2332    fn to_index(&self, ix: NodeIndex<Ix>) -> usize {
2333        ix.index()
2334    }
2335    fn from_index(&self, ix: usize) -> Self::NodeId {
2336        NodeIndex::new(ix)
2337    }
2338}
2339
2340impl<'a, N, E: 'a, Ty, Ix> visit::IntoNeighbors for &'a StableGraph<N, E, Ty, Ix>
2341where
2342    Ty: EdgeType,
2343    Ix: IndexType,
2344{
2345    type Neighbors = Neighbors<'a, E, Ix>;
2346    fn neighbors(self, n: Self::NodeId) -> Self::Neighbors {
2347        (*self).neighbors(n)
2348    }
2349}
2350
2351impl<'a, N, E: 'a, Ty, Ix> visit::IntoNeighborsDirected for &'a StableGraph<N, E, Ty, Ix>
2352where
2353    Ty: EdgeType,
2354    Ix: IndexType,
2355{
2356    type NeighborsDirected = Neighbors<'a, E, Ix>;
2357    fn neighbors_directed(self, n: NodeIndex<Ix>, d: Direction) -> Self::NeighborsDirected {
2358        StableGraph::neighbors_directed(self, n, d)
2359    }
2360}
2361
2362impl<'a, N, E, Ty, Ix> visit::IntoEdges for &'a StableGraph<N, E, Ty, Ix>
2363where
2364    Ty: EdgeType,
2365    Ix: IndexType,
2366{
2367    type Edges = Edges<'a, E, Ty, Ix>;
2368    fn edges(self, a: Self::NodeId) -> Self::Edges {
2369        self.edges(a)
2370    }
2371}
2372
2373impl<Ix, E> visit::EdgeRef for EdgeReference<'_, E, Ix>
2374where
2375    Ix: IndexType,
2376{
2377    type NodeId = NodeIndex<Ix>;
2378    type EdgeId = EdgeIndex<Ix>;
2379    type Weight = E;
2380
2381    fn source(&self) -> Self::NodeId {
2382        self.node[0]
2383    }
2384    fn target(&self) -> Self::NodeId {
2385        self.node[1]
2386    }
2387    fn weight(&self) -> &E {
2388        self.weight
2389    }
2390    fn id(&self) -> Self::EdgeId {
2391        self.index
2392    }
2393}
2394
2395impl<N, E, Ty, Ix> visit::EdgeIndexable for StableGraph<N, E, Ty, Ix>
2396where
2397    Ty: EdgeType,
2398    Ix: IndexType,
2399{
2400    fn edge_bound(&self) -> usize {
2401        self.edge_references()
2402            .next_back()
2403            .map_or(0, |edge| edge.id().index() + 1)
2404    }
2405
2406    fn to_index(&self, ix: EdgeIndex<Ix>) -> usize {
2407        ix.index()
2408    }
2409
2410    fn from_index(&self, ix: usize) -> Self::EdgeId {
2411        EdgeIndex::new(ix)
2412    }
2413}
2414
2415impl<'a, N, E, Ty, Ix> visit::IntoEdgesDirected for &'a StableGraph<N, E, Ty, Ix>
2416where
2417    Ty: EdgeType,
2418    Ix: IndexType,
2419{
2420    type EdgesDirected = Edges<'a, E, Ty, Ix>;
2421    fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
2422        self.edges_directed(a, dir)
2423    }
2424}
2425
2426impl<'a, N: 'a, E: 'a, Ty, Ix> visit::IntoEdgeReferences for &'a StableGraph<N, E, Ty, Ix>
2427where
2428    Ty: EdgeType,
2429    Ix: IndexType,
2430{
2431    type EdgeRef = EdgeReference<'a, E, Ix>;
2432    type EdgeReferences = EdgeReferences<'a, E, Ix>;
2433
2434    /// Create an iterator over all edges in the graph, in indexed order.
2435    ///
2436    /// Iterator element type is `EdgeReference<E, Ix>`.
2437    fn edge_references(self) -> Self::EdgeReferences {
2438        EdgeReferences {
2439            iter: self.g.edges.iter().enumerate(),
2440        }
2441    }
2442}
2443
2444impl<N, E, Ty, Ix> visit::EdgeCount for StableGraph<N, E, Ty, Ix>
2445where
2446    Ty: EdgeType,
2447    Ix: IndexType,
2448{
2449    #[inline]
2450    fn edge_count(&self) -> usize {
2451        self.edge_count()
2452    }
2453}
2454
2455#[test]
2456fn stable_graph() {
2457    use std::println;
2458
2459    let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
2460    let a = gr.add_node(0);
2461    let b = gr.add_node(1);
2462    let c = gr.add_node(2);
2463    let _ed = gr.add_edge(a, b, 1);
2464    println!("{gr:?}");
2465    gr.remove_node(b);
2466    println!("{gr:?}");
2467    let d = gr.add_node(3);
2468    println!("{gr:?}");
2469    gr.check_free_lists();
2470    gr.remove_node(a);
2471    gr.check_free_lists();
2472    gr.remove_node(c);
2473    gr.check_free_lists();
2474    println!("{gr:?}");
2475    gr.add_edge(d, d, 2);
2476    println!("{gr:?}");
2477
2478    let e = gr.add_node(4);
2479    gr.add_edge(d, e, 3);
2480    println!("{gr:?}");
2481    for neigh in gr.neighbors(d) {
2482        println!("edge {d:?} -> {neigh:?}");
2483    }
2484    gr.check_free_lists();
2485}
2486
2487#[test]
2488fn dfs() {
2489    use std::println;
2490
2491    use crate::visit::Dfs;
2492
2493    let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
2494    let a = gr.add_node("a");
2495    let b = gr.add_node("b");
2496    let c = gr.add_node("c");
2497    let d = gr.add_node("d");
2498    gr.add_edge(a, b, 1);
2499    gr.add_edge(a, c, 2);
2500    gr.add_edge(b, c, 3);
2501    gr.add_edge(b, d, 4);
2502    gr.add_edge(c, d, 5);
2503    gr.add_edge(d, b, 6);
2504    gr.add_edge(c, b, 7);
2505    println!("{gr:?}");
2506
2507    let mut dfs = Dfs::new(&gr, a);
2508    while let Some(next) = dfs.next(&gr) {
2509        println!("dfs visit => {:?}, weight={:?}", next, &gr[next]);
2510    }
2511}
2512
2513#[test]
2514fn test_retain_nodes() {
2515    let mut gr = StableGraph::<_, _>::with_capacity(6, 6);
2516    let a = gr.add_node("a");
2517    let f = gr.add_node("f");
2518    let b = gr.add_node("b");
2519    let c = gr.add_node("c");
2520    let d = gr.add_node("d");
2521    let e = gr.add_node("e");
2522    gr.add_edge(a, b, 1);
2523    gr.add_edge(a, c, 2);
2524    gr.add_edge(b, c, 3);
2525    gr.add_edge(b, d, 4);
2526    gr.add_edge(c, d, 5);
2527    gr.add_edge(d, b, 6);
2528    gr.add_edge(c, b, 7);
2529    gr.add_edge(d, e, 8);
2530    gr.remove_node(f);
2531
2532    assert_eq!(gr.node_count(), 5);
2533    assert_eq!(gr.edge_count(), 8);
2534    gr.retain_nodes(|frozen_gr, ix| frozen_gr[ix] >= "c");
2535    assert_eq!(gr.node_count(), 3);
2536    assert_eq!(gr.edge_count(), 2);
2537
2538    gr.check_free_lists();
2539}
2540
2541#[test]
2542fn extend_with_edges() {
2543    let mut gr = StableGraph::<_, _>::default();
2544    let a = gr.add_node("a");
2545    let b = gr.add_node("b");
2546    let c = gr.add_node("c");
2547    let _d = gr.add_node("d");
2548    gr.remove_node(a);
2549    gr.remove_node(b);
2550    gr.remove_node(c);
2551
2552    gr.extend_with_edges(vec![(0, 1, ())]);
2553    assert_eq!(gr.node_count(), 3);
2554    assert_eq!(gr.edge_count(), 1);
2555    gr.check_free_lists();
2556
2557    gr.extend_with_edges(vec![(5, 1, ())]);
2558    assert_eq!(gr.node_count(), 4);
2559    assert_eq!(gr.edge_count(), 2);
2560    gr.check_free_lists();
2561}
2562
2563#[test]
2564fn test_reverse() {
2565    let mut gr = StableGraph::<_, _>::default();
2566    let a = gr.add_node("a");
2567    let b = gr.add_node("b");
2568
2569    gr.add_edge(a, b, 0);
2570
2571    let mut reversed_gr = gr.clone();
2572    reversed_gr.reverse();
2573
2574    for i in gr.node_indices() {
2575        itertools::assert_equal(gr.edges_directed(i, Incoming), reversed_gr.edges(i));
2576    }
2577}
2578
2579#[test]
2580fn test_reverse_after_remove_nodes() {
2581    let mut gr = StableGraph::<_, _>::default();
2582    let a = gr.add_node("a");
2583    let b = gr.add_node("b");
2584    let c = gr.add_node("c");
2585
2586    gr.add_edge(a, a, 0);
2587
2588    gr.remove_node(b);
2589    gr.remove_node(c);
2590
2591    gr.check_free_lists();
2592
2593    gr.reverse();
2594
2595    gr.check_free_lists();
2596}
2597
2598#[test]
2599fn test_reverse_after_remove_edges() {
2600    let mut gr = StableGraph::<_, _>::default();
2601    let a = gr.add_node("a");
2602    let b = gr.add_node("b");
2603    let c = gr.add_node("c");
2604
2605    let e_ab = gr.add_edge(a, b, 0);
2606    let e_bc = gr.add_edge(b, c, 0);
2607
2608    gr.remove_edge(e_ab);
2609    gr.remove_edge(e_bc);
2610
2611    gr.check_free_lists();
2612
2613    gr.reverse();
2614
2615    gr.check_free_lists();
2616}