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