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::{replace, 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, and allows fast node and edge insert
50/// 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 (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 = replace(&mut edge.weight, Some(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    pub fn edge_indices(&self) -> EdgeIndices<E, Ix> {
634        EdgeIndices {
635            iter: enumerate(self.raw_edges()),
636        }
637    }
638
639    /// Return an iterator over all the edges connecting `a` and `b`.
640    ///
641    /// - `Directed`: Outgoing edges from `a`.
642    /// - `Undirected`: All edges connected to `a`.
643    ///
644    /// Iterator element type is `EdgeReference<E, Ix>`.
645    pub fn edges_connecting(
646        &self,
647        a: NodeIndex<Ix>,
648        b: NodeIndex<Ix>,
649    ) -> EdgesConnecting<E, Ty, Ix> {
650        EdgesConnecting {
651            target_node: b,
652            edges: self.edges_directed(a, Direction::Outgoing),
653            ty: PhantomData,
654        }
655    }
656
657    /// Lookup if there is an edge from `a` to `b`.
658    ///
659    /// Computes in **O(e')** time, where **e'** is the number of edges
660    /// connected to `a` (and `b`, if the graph edges are undirected).
661    pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
662        self.find_edge(a, b).is_some()
663    }
664
665    /// Lookup an edge from `a` to `b`.
666    ///
667    /// Computes in **O(e')** time, where **e'** is the number of edges
668    /// connected to `a` (and `b`, if the graph edges are undirected).
669    pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>> {
670        if !self.is_directed() {
671            self.find_edge_undirected(a, b).map(|(ix, _)| ix)
672        } else {
673            match self.get_node(a) {
674                None => None,
675                Some(node) => self.g.find_edge_directed_from_node(node, b),
676            }
677        }
678    }
679
680    /// Lookup an edge between `a` and `b`, in either direction.
681    ///
682    /// If the graph is undirected, then this is equivalent to `.find_edge()`.
683    ///
684    /// Return the edge index and its directionality, with `Outgoing` meaning
685    /// from `a` to `b` and `Incoming` the reverse,
686    /// or `None` if the edge does not exist.
687    pub fn find_edge_undirected(
688        &self,
689        a: NodeIndex<Ix>,
690        b: NodeIndex<Ix>,
691    ) -> Option<(EdgeIndex<Ix>, Direction)> {
692        match self.get_node(a) {
693            None => None,
694            Some(node) => self.g.find_edge_undirected_from_node(node, b),
695        }
696    }
697
698    /// Return an iterator of all nodes with an edge starting from `a`.
699    ///
700    /// - `Directed`: Outgoing edges from `a`.
701    /// - `Undirected`: All edges connected to `a`.
702    ///
703    /// Produces an empty iterator if the node doesn't exist.<br>
704    /// Iterator element type is `NodeIndex<Ix>`.
705    ///
706    /// Use [`.neighbors(a).detach()`][1] to get a neighbor walker that does
707    /// not borrow from the graph.
708    ///
709    /// [1]: struct.Neighbors.html#method.detach
710    pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
711        self.neighbors_directed(a, Outgoing)
712    }
713
714    /// Return an iterator of all neighbors that have an edge between them and `a`,
715    /// in the specified direction.
716    /// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
717    ///
718    /// - `Directed`, `Outgoing`: All edges from `a`.
719    /// - `Directed`, `Incoming`: All edges to `a`.
720    /// - `Undirected`: All edges connected to `a`.
721    ///
722    /// Produces an empty iterator if the node doesn't exist.<br>
723    /// Iterator element type is `NodeIndex<Ix>`.
724    ///
725    /// Use [`.neighbors_directed(a, dir).detach()`][1] to get a neighbor walker that does
726    /// not borrow from the graph.
727    ///
728    /// [1]: struct.Neighbors.html#method.detach
729    pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix> {
730        let mut iter = self.neighbors_undirected(a);
731        if self.is_directed() {
732            let k = dir.index();
733            iter.next[1 - k] = EdgeIndex::end();
734            iter.skip_start = NodeIndex::end();
735        }
736        iter
737    }
738
739    /// Return an iterator of all neighbors that have an edge between them and `a`,
740    /// in either direction.
741    /// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
742    ///
743    /// - `Directed` and `Undirected`: All edges connected to `a`.
744    ///
745    /// Produces an empty iterator if the node doesn't exist.<br>
746    /// Iterator element type is `NodeIndex<Ix>`.
747    ///
748    /// Use [`.neighbors_undirected(a).detach()`][1] to get a neighbor walker that does
749    /// not borrow from the graph.
750    ///
751    /// [1]: struct.Neighbors.html#method.detach
752    pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
753        Neighbors {
754            skip_start: a,
755            edges: &self.g.edges,
756            next: match self.get_node(a) {
757                None => [EdgeIndex::end(), EdgeIndex::end()],
758                Some(n) => n.next,
759            },
760        }
761    }
762
763    /// Return an iterator of all edges of `a`.
764    ///
765    /// - `Directed`: Outgoing edges from `a`.
766    /// - `Undirected`: All edges connected to `a`.
767    ///
768    /// Produces an empty iterator if the node doesn't exist.<br>
769    /// Iterator element type is `EdgeReference<E, Ix>`.
770    pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
771        self.edges_directed(a, Outgoing)
772    }
773
774    /// Return an iterator of all edges of `a`, in the specified direction.
775    ///
776    /// - `Directed`, `Outgoing`: All edges from `a`.
777    /// - `Directed`, `Incoming`: All edges to `a`.
778    /// - `Undirected`, `Outgoing`: All edges connected to `a`, with `a` being the source of each
779    ///   edge.
780    /// - `Undirected`, `Incoming`: All edges connected to `a`, with `a` being the target of each
781    ///   edge.
782    ///
783    /// Produces an empty iterator if the node `a` doesn't exist.<br>
784    /// Iterator element type is `EdgeReference<E, Ix>`.
785    pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix> {
786        Edges {
787            skip_start: a,
788            edges: &self.g.edges,
789            direction: dir,
790            next: match self.get_node(a) {
791                None => [EdgeIndex::end(), EdgeIndex::end()],
792                Some(n) => n.next,
793            },
794            ty: PhantomData,
795        }
796    }
797
798    /// Return an iterator over either the nodes without edges to them
799    /// (`Incoming`) or from them (`Outgoing`).
800    ///
801    /// An *internal* node has both incoming and outgoing edges.
802    /// The nodes in `.externals(Incoming)` are the source nodes and
803    /// `.externals(Outgoing)` are the sinks of the graph.
804    ///
805    /// For a graph with undirected edges, both the sinks and the sources are
806    /// just the nodes without edges.
807    ///
808    /// The whole iteration computes in **O(|V|)** time.
809    pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix> {
810        Externals {
811            iter: self.raw_nodes().iter().enumerate(),
812            dir,
813            ty: PhantomData,
814        }
815    }
816
817    /// Index the `StableGraph` by two indices, any combination of
818    /// node or edge indices is fine.
819    ///
820    /// **Panics** if the indices are equal or if they are not found.
821    #[track_caller]
822    pub fn index_twice_mut<T, U>(
823        &mut self,
824        i: T,
825        j: U,
826    ) -> (
827        &mut <Self as Index<T>>::Output,
828        &mut <Self as Index<U>>::Output,
829    )
830    where
831        Self: IndexMut<T> + IndexMut<U>,
832        T: GraphIndex,
833        U: GraphIndex,
834    {
835        assert!(T::is_node_index() != U::is_node_index() || i.index() != j.index());
836
837        // Allow two mutable indexes here -- they are nonoverlapping
838        unsafe {
839            let self_mut = self as *mut _;
840            (
841                <Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
842                <Self as IndexMut<U>>::index_mut(&mut *self_mut, j),
843            )
844        }
845    }
846
847    /// Keep all nodes that return `true` from the `visit` closure,
848    /// remove the others.
849    ///
850    /// `visit` is provided a proxy reference to the graph, so that
851    /// the graph can be walked and associated data modified.
852    ///
853    /// The order nodes are visited is not specified.
854    ///
855    /// The node indices of the removed nodes are invalidated, but none other.
856    /// Edge indices are invalidated as they would be following the removal of
857    /// each edge with an endpoint in a removed node.
858    ///
859    /// Computes in **O(n + e')** time, where **n** is the number of node indices and
860    ///  **e'** is the number of affected edges, including *n* calls to `.remove_edge()`
861    /// where *n* is the number of edges with an endpoint in a removed node.
862    pub fn retain_nodes<F>(&mut self, mut visit: F)
863    where
864        F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,
865    {
866        for i in 0..self.node_bound() {
867            let ix = node_index(i);
868            if self.contains_node(ix) && !visit(Frozen(self), ix) {
869                self.remove_node(ix);
870            }
871        }
872        self.check_free_lists();
873    }
874
875    /// Keep all edges that return `true` from the `visit` closure,
876    /// remove the others.
877    ///
878    /// `visit` is provided a proxy reference to the graph, so that
879    /// the graph can be walked and associated data modified.
880    ///
881    /// The order edges are visited is not specified.
882    ///
883    /// The edge indices of the removed edes are invalidated, but none other.
884    ///
885    /// Computes in **O(e'')** time, **e'** is the number of affected edges,
886    /// including the calls to `.remove_edge()` for each removed edge.
887    pub fn retain_edges<F>(&mut self, mut visit: F)
888    where
889        F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,
890    {
891        for i in 0..self.edge_bound() {
892            let ix = edge_index(i);
893            if self.edge_weight(ix).is_some() && !visit(Frozen(self), ix) {
894                self.remove_edge(ix);
895            }
896        }
897        self.check_free_lists();
898    }
899
900    /// Create a new `StableGraph` from an iterable of edges.
901    ///
902    /// Node weights `N` are set to default values.
903    /// Edge weights `E` may either be specified in the list,
904    /// or they are filled with default values.
905    ///
906    /// Nodes are inserted automatically to match the edges.
907    ///
908    /// ```
909    /// use petgraph::stable_graph::StableGraph;
910    ///
911    /// let gr = StableGraph::<(), i32>::from_edges(&[
912    ///     (0, 1), (0, 2), (0, 3),
913    ///     (1, 2), (1, 3),
914    ///     (2, 3),
915    /// ]);
916    /// ```
917    pub fn from_edges<I>(iterable: I) -> Self
918    where
919        I: IntoIterator,
920        I::Item: IntoWeightedEdge<E>,
921        <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
922        N: Default,
923    {
924        let mut g = Self::with_capacity(0, 0);
925        g.extend_with_edges(iterable);
926        g
927    }
928
929    /// Create a new `StableGraph` by mapping node and
930    /// edge weights to new values.
931    ///
932    /// The resulting graph has the same structure and the same
933    /// graph indices as `self`.
934    pub fn map<'a, F, G, N2, E2>(
935        &'a self,
936        mut node_map: F,
937        mut edge_map: G,
938    ) -> StableGraph<N2, E2, Ty, Ix>
939    where
940        F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
941        G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
942    {
943        let g = self.g.map(
944            move |i, w| w.as_ref().map(|w| node_map(i, w)),
945            move |i, w| w.as_ref().map(|w| edge_map(i, w)),
946        );
947        StableGraph {
948            g,
949            node_count: self.node_count,
950            edge_count: self.edge_count,
951            free_node: self.free_node,
952            free_edge: self.free_edge,
953        }
954    }
955
956    /// Create a new `StableGraph` by mapping nodes and edges.
957    /// A node or edge may be mapped to `None` to exclude it from
958    /// the resulting graph.
959    ///
960    /// Nodes are mapped first with the `node_map` closure, then
961    /// `edge_map` is called for the edges that have not had any endpoint
962    /// removed.
963    ///
964    /// The resulting graph has the structure of a subgraph of the original graph.
965    /// Nodes and edges that are not removed maintain their old node or edge
966    /// indices.
967    pub fn filter_map<'a, F, G, N2, E2>(
968        &'a self,
969        mut node_map: F,
970        mut edge_map: G,
971    ) -> StableGraph<N2, E2, Ty, Ix>
972    where
973        F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
974        G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
975    {
976        let node_bound = self.node_bound();
977        let edge_bound = self.edge_bound();
978        let mut result_g = StableGraph::with_capacity(node_bound, edge_bound);
979        // use separate free lists so that
980        // add_node / add_edge below do not reuse the tombstones
981        let mut free_node = NodeIndex::end();
982        let mut free_edge = EdgeIndex::end();
983
984        // the stable graph keeps the node map itself
985
986        for (i, node) in enumerate(self.raw_nodes()) {
987            if i >= node_bound {
988                break;
989            }
990            if let Some(node_weight) = node.weight.as_ref() {
991                if let Some(new_weight) = node_map(NodeIndex::new(i), node_weight) {
992                    result_g.add_node(new_weight);
993                    continue;
994                }
995            }
996            result_g.add_vacant_node(&mut free_node);
997        }
998        for (i, edge) in enumerate(self.raw_edges()) {
999            if i >= edge_bound {
1000                break;
1001            }
1002            let source = edge.source();
1003            let target = edge.target();
1004            if let Some(edge_weight) = edge.weight.as_ref() {
1005                if result_g.contains_node(source) && result_g.contains_node(target) {
1006                    if let Some(new_weight) = edge_map(EdgeIndex::new(i), edge_weight) {
1007                        result_g.add_edge(source, target, new_weight);
1008                        continue;
1009                    }
1010                }
1011            }
1012            result_g.add_vacant_edge(&mut free_edge);
1013        }
1014        result_g.free_node = free_node;
1015        result_g.free_edge = free_edge;
1016        result_g.check_free_lists();
1017        result_g
1018    }
1019
1020    /// Extend the graph from an iterable of edges.
1021    ///
1022    /// Node weights `N` are set to default values.
1023    /// Edge weights `E` may either be specified in the list,
1024    /// or they are filled with default values.
1025    ///
1026    /// Nodes are inserted automatically to match the edges.
1027    pub fn extend_with_edges<I>(&mut self, iterable: I)
1028    where
1029        I: IntoIterator,
1030        I::Item: IntoWeightedEdge<E>,
1031        <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1032        N: Default,
1033    {
1034        let iter = iterable.into_iter();
1035
1036        for elt in iter {
1037            let (source, target, weight) = elt.into_weighted_edge();
1038            let (source, target) = (source.into(), target.into());
1039            self.ensure_node_exists(source);
1040            self.ensure_node_exists(target);
1041            self.add_edge(source, target, weight);
1042        }
1043    }
1044
1045    //
1046    // internal methods
1047    //
1048    fn raw_nodes(&self) -> &[Node<Option<N>, Ix>] {
1049        self.g.raw_nodes()
1050    }
1051
1052    fn raw_edges(&self) -> &[Edge<Option<E>, Ix>] {
1053        self.g.raw_edges()
1054    }
1055
1056    /// Create a new node using a vacant position,
1057    /// updating the free nodes doubly linked list.
1058    fn occupy_vacant_node(&mut self, node_idx: NodeIndex<Ix>, weight: N) {
1059        let node_slot = &mut self.g.nodes[node_idx.index()];
1060        let _old = replace(&mut node_slot.weight, Some(weight));
1061        debug_assert!(_old.is_none());
1062        let previous_node = node_slot.next[1];
1063        let next_node = node_slot.next[0];
1064        node_slot.next = [EdgeIndex::end(), EdgeIndex::end()];
1065        if previous_node != EdgeIndex::end() {
1066            self.g.nodes[previous_node.index()].next[0] = next_node;
1067        }
1068        if next_node != EdgeIndex::end() {
1069            self.g.nodes[next_node.index()].next[1] = previous_node;
1070        }
1071        if self.free_node == node_idx {
1072            self.free_node = next_node._into_node();
1073        }
1074        self.node_count += 1;
1075    }
1076
1077    /// Create the node if it does not exist,
1078    /// adding vacant nodes for padding if needed.
1079    fn ensure_node_exists(&mut self, node_ix: NodeIndex<Ix>)
1080    where
1081        N: Default,
1082    {
1083        if let Some(Some(_)) = self.g.node_weight(node_ix) {
1084            return;
1085        }
1086        while node_ix.index() >= self.g.node_count() {
1087            let mut free_node = self.free_node;
1088            self.add_vacant_node(&mut free_node);
1089            self.free_node = free_node;
1090        }
1091        self.occupy_vacant_node(node_ix, N::default());
1092    }
1093
1094    #[cfg(feature = "serde-1")]
1095    /// Fix up node and edge links after deserialization
1096    fn link_edges(&mut self) -> Result<(), NodeIndex<Ix>> {
1097        // set up free node list
1098        self.node_count = 0;
1099        self.edge_count = 0;
1100        let mut free_node = NodeIndex::end();
1101        for node_index in 0..self.g.node_count() {
1102            let node = &mut self.g.nodes[node_index];
1103            if node.weight.is_some() {
1104                self.node_count += 1;
1105            } else {
1106                // free node
1107                node.next = [free_node._into_edge(), EdgeIndex::end()];
1108                if free_node != NodeIndex::end() {
1109                    self.g.nodes[free_node.index()].next[1] = EdgeIndex::new(node_index);
1110                }
1111                free_node = NodeIndex::new(node_index);
1112            }
1113        }
1114        self.free_node = free_node;
1115
1116        let mut free_edge = EdgeIndex::end();
1117        for (edge_index, edge) in enumerate(&mut self.g.edges) {
1118            if edge.weight.is_none() {
1119                // free edge
1120                edge.next = [free_edge, EdgeIndex::end()];
1121                free_edge = EdgeIndex::new(edge_index);
1122                continue;
1123            }
1124            let a = edge.source();
1125            let b = edge.target();
1126            let edge_idx = EdgeIndex::new(edge_index);
1127            match index_twice(&mut self.g.nodes, a.index(), b.index()) {
1128                Pair::None => return Err(if a > b { a } else { b }),
1129                Pair::One(an) => {
1130                    edge.next = an.next;
1131                    an.next[0] = edge_idx;
1132                    an.next[1] = edge_idx;
1133                }
1134                Pair::Both(an, bn) => {
1135                    // a and b are different indices
1136                    edge.next = [an.next[0], bn.next[1]];
1137                    an.next[0] = edge_idx;
1138                    bn.next[1] = edge_idx;
1139                }
1140            }
1141            self.edge_count += 1;
1142        }
1143        self.free_edge = free_edge;
1144        Ok(())
1145    }
1146
1147    #[cfg(not(debug_assertions))]
1148    fn check_free_lists(&self) {}
1149    #[cfg(debug_assertions)]
1150    // internal method to debug check the free lists (linked lists)
1151    // For the nodes, also check the backpointers of the doubly linked list.
1152    fn check_free_lists(&self) {
1153        let mut free_node = self.free_node;
1154        let mut prev_free_node = NodeIndex::end();
1155        let mut free_node_len = 0;
1156        while free_node != NodeIndex::end() {
1157            if let Some(n) = self.g.nodes.get(free_node.index()) {
1158                if n.weight.is_none() {
1159                    debug_assert_eq!(n.next[1]._into_node(), prev_free_node);
1160                    prev_free_node = free_node;
1161                    free_node = n.next[0]._into_node();
1162                    free_node_len += 1;
1163                    continue;
1164                }
1165                debug_assert!(
1166                    false,
1167                    "Corrupt free list: pointing to existing {:?}",
1168                    free_node.index()
1169                );
1170            }
1171            debug_assert!(false, "Corrupt free list: missing {:?}", free_node.index());
1172        }
1173        debug_assert_eq!(self.node_count(), self.raw_nodes().len() - free_node_len);
1174
1175        let mut free_edge_len = 0;
1176        let mut free_edge = self.free_edge;
1177        while free_edge != EdgeIndex::end() {
1178            if let Some(n) = self.g.edges.get(free_edge.index()) {
1179                if n.weight.is_none() {
1180                    free_edge = n.next[0];
1181                    free_edge_len += 1;
1182                    continue;
1183                }
1184                debug_assert!(
1185                    false,
1186                    "Corrupt free list: pointing to existing {:?}",
1187                    free_node.index()
1188                );
1189            }
1190            debug_assert!(false, "Corrupt free list: missing {:?}", free_edge.index());
1191        }
1192        debug_assert_eq!(self.edge_count(), self.raw_edges().len() - free_edge_len);
1193    }
1194}
1195
1196/// The resulting cloned graph has the same graph indices as `self`.
1197impl<N, E, Ty, Ix: IndexType> Clone for StableGraph<N, E, Ty, Ix>
1198where
1199    N: Clone,
1200    E: Clone,
1201{
1202    fn clone(&self) -> Self {
1203        StableGraph {
1204            g: self.g.clone(),
1205            node_count: self.node_count,
1206            edge_count: self.edge_count,
1207            free_node: self.free_node,
1208            free_edge: self.free_edge,
1209        }
1210    }
1211
1212    fn clone_from(&mut self, rhs: &Self) {
1213        self.g.clone_from(&rhs.g);
1214        self.node_count = rhs.node_count;
1215        self.edge_count = rhs.edge_count;
1216        self.free_node = rhs.free_node;
1217        self.free_edge = rhs.free_edge;
1218    }
1219}
1220
1221/// Index the `StableGraph` by `NodeIndex` to access node weights.
1222///
1223/// **Panics** if the node doesn't exist.
1224impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1225where
1226    Ty: EdgeType,
1227    Ix: IndexType,
1228{
1229    type Output = N;
1230    fn index(&self, index: NodeIndex<Ix>) -> &N {
1231        self.node_weight(index).unwrap()
1232    }
1233}
1234
1235/// Index the `StableGraph` by `NodeIndex` to access node weights.
1236///
1237/// **Panics** if the node doesn't exist.
1238impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1239where
1240    Ty: EdgeType,
1241    Ix: IndexType,
1242{
1243    fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1244        self.node_weight_mut(index).unwrap()
1245    }
1246}
1247
1248/// Index the `StableGraph` by `EdgeIndex` to access edge weights.
1249///
1250/// **Panics** if the edge doesn't exist.
1251impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1252where
1253    Ty: EdgeType,
1254    Ix: IndexType,
1255{
1256    type Output = E;
1257    fn index(&self, index: EdgeIndex<Ix>) -> &E {
1258        self.edge_weight(index).unwrap()
1259    }
1260}
1261
1262/// Index the `StableGraph` by `EdgeIndex` to access edge weights.
1263///
1264/// **Panics** if the edge doesn't exist.
1265impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1266where
1267    Ty: EdgeType,
1268    Ix: IndexType,
1269{
1270    fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
1271        self.edge_weight_mut(index).unwrap()
1272    }
1273}
1274
1275/// Create a new empty `StableGraph`.
1276impl<N, E, Ty, Ix> Default for StableGraph<N, E, Ty, Ix>
1277where
1278    Ty: EdgeType,
1279    Ix: IndexType,
1280{
1281    fn default() -> Self {
1282        Self::with_capacity(0, 0)
1283    }
1284}
1285
1286/// Convert a `Graph` into a `StableGraph`
1287///
1288/// Computes in **O(|V| + |E|)** time.
1289///
1290/// The resulting graph has the same node and edge indices as
1291/// the original graph.
1292impl<N, E, Ty, Ix> From<Graph<N, E, Ty, Ix>> for StableGraph<N, E, Ty, Ix>
1293where
1294    Ty: EdgeType,
1295    Ix: IndexType,
1296{
1297    fn from(g: Graph<N, E, Ty, Ix>) -> Self {
1298        let nodes = g.nodes.into_iter().map(|e| Node {
1299            weight: Some(e.weight),
1300            next: e.next,
1301        });
1302        let edges = g.edges.into_iter().map(|e| Edge {
1303            weight: Some(e.weight),
1304            node: e.node,
1305            next: e.next,
1306        });
1307        StableGraph {
1308            node_count: nodes.len(),
1309            edge_count: edges.len(),
1310            g: Graph {
1311                edges: edges.collect(),
1312                nodes: nodes.collect(),
1313                ty: g.ty,
1314            },
1315            free_node: NodeIndex::end(),
1316            free_edge: EdgeIndex::end(),
1317        }
1318    }
1319}
1320
1321/// Convert a `StableGraph` into a `Graph`
1322///
1323/// Computes in **O(|V| + |E|)** time.
1324///
1325/// This translates the stable graph into a graph with node and edge indices in
1326/// a compact interval without holes (like `Graph`s always are).
1327///
1328/// Only if the stable graph had no vacancies after deletions (if node bound was
1329/// equal to node count, and the same for edges), would the resulting graph have
1330/// the same node and edge indices as the input.
1331impl<N, E, Ty, Ix> From<StableGraph<N, E, Ty, Ix>> for Graph<N, E, Ty, Ix>
1332where
1333    Ty: EdgeType,
1334    Ix: IndexType,
1335{
1336    fn from(graph: StableGraph<N, E, Ty, Ix>) -> Self {
1337        let mut result_g = Graph::with_capacity(graph.node_count(), graph.edge_count());
1338        // mapping from old node index to new node index
1339        let mut node_index_map = vec![NodeIndex::end(); graph.node_bound()];
1340
1341        for (i, node) in enumerate(graph.g.nodes) {
1342            if let Some(nw) = node.weight {
1343                node_index_map[i] = result_g.add_node(nw);
1344            }
1345        }
1346        for edge in graph.g.edges {
1347            let source_index = edge.source().index();
1348            let target_index = edge.target().index();
1349            if let Some(ew) = edge.weight {
1350                let source = node_index_map[source_index];
1351                let target = node_index_map[target_index];
1352                debug_assert!(source != NodeIndex::end());
1353                debug_assert!(target != NodeIndex::end());
1354                result_g.add_edge(source, target, ew);
1355            }
1356        }
1357        result_g
1358    }
1359}
1360
1361/// Iterator over all nodes of a graph.
1362#[derive(Debug, Clone)]
1363pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
1364    iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1365}
1366
1367impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
1368where
1369    Ix: IndexType,
1370{
1371    type Item = (NodeIndex<Ix>, &'a N);
1372
1373    fn next(&mut self) -> Option<Self::Item> {
1374        self.iter
1375            .ex_find_map(|(i, node)| node.weight.as_ref().map(move |w| (node_index(i), w)))
1376    }
1377
1378    fn size_hint(&self) -> (usize, Option<usize>) {
1379        let (_, hi) = self.iter.size_hint();
1380        (0, hi)
1381    }
1382}
1383
1384impl<N, Ix> DoubleEndedIterator for NodeReferences<'_, N, Ix>
1385where
1386    Ix: IndexType,
1387{
1388    fn next_back(&mut self) -> Option<Self::Item> {
1389        self.iter
1390            .ex_rfind_map(|(i, node)| node.weight.as_ref().map(move |w| (node_index(i), w)))
1391    }
1392}
1393
1394/// Reference to a `StableGraph` edge.
1395#[derive(Debug)]
1396pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
1397    index: EdgeIndex<Ix>,
1398    node: [NodeIndex<Ix>; 2],
1399    weight: &'a E,
1400}
1401
1402impl<E, Ix: IndexType> Clone for EdgeReference<'_, E, Ix> {
1403    fn clone(&self) -> Self {
1404        *self
1405    }
1406}
1407
1408impl<E, Ix: IndexType> Copy for EdgeReference<'_, E, Ix> {}
1409
1410impl<E, Ix: IndexType> PartialEq for EdgeReference<'_, E, Ix>
1411where
1412    E: PartialEq,
1413{
1414    fn eq(&self, rhs: &Self) -> bool {
1415        self.index == rhs.index && self.weight == rhs.weight
1416    }
1417}
1418
1419impl<'a, Ix, E> EdgeReference<'a, E, Ix>
1420where
1421    Ix: IndexType,
1422{
1423    /// Access the edge’s weight.
1424    ///
1425    /// **NOTE** that this method offers a longer lifetime
1426    /// than the trait (unfortunately they don't match yet).
1427    pub fn weight(&self) -> &'a E {
1428        self.weight
1429    }
1430}
1431
1432/// Iterator over the edges of from or to a node
1433#[derive(Debug, Clone)]
1434pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1435where
1436    Ty: EdgeType,
1437    Ix: IndexType,
1438{
1439    /// starting node to skip over
1440    skip_start: NodeIndex<Ix>,
1441    edges: &'a [Edge<Option<E>, Ix>],
1442
1443    /// Next edge to visit.
1444    next: [EdgeIndex<Ix>; 2],
1445
1446    /// For directed graphs: the direction to iterate in
1447    /// For undirected graphs: the direction of edges
1448    direction: Direction,
1449    ty: PhantomData<Ty>,
1450}
1451
1452impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1453where
1454    Ty: EdgeType,
1455    Ix: IndexType,
1456{
1457    type Item = EdgeReference<'a, E, Ix>;
1458
1459    fn next(&mut self) -> Option<Self::Item> {
1460        //      type        direction    |    iterate over    reverse
1461        //                               |
1462        //    Directed      Outgoing     |      outgoing        no
1463        //    Directed      Incoming     |      incoming        no
1464        //   Undirected     Outgoing     |        both       incoming
1465        //   Undirected     Incoming     |        both       outgoing
1466
1467        // For iterate_over, "both" is represented as None.
1468        // For reverse, "no" is represented as None.
1469        let (iterate_over, reverse) = if Ty::is_directed() {
1470            (Some(self.direction), None)
1471        } else {
1472            (None, Some(self.direction.opposite()))
1473        };
1474
1475        if iterate_over.unwrap_or(Outgoing) == Outgoing {
1476            let i = self.next[0].index();
1477            if let Some(Edge {
1478                node,
1479                weight: Some(weight),
1480                next,
1481            }) = self.edges.get(i)
1482            {
1483                self.next[0] = next[0];
1484                return Some(EdgeReference {
1485                    index: edge_index(i),
1486                    node: if reverse == Some(Outgoing) {
1487                        swap_pair(*node)
1488                    } else {
1489                        *node
1490                    },
1491                    weight,
1492                });
1493            }
1494        }
1495
1496        if iterate_over.unwrap_or(Incoming) == Incoming {
1497            while let Some(Edge { node, weight, next }) = self.edges.get(self.next[1].index()) {
1498                debug_assert!(weight.is_some());
1499                let edge_index = self.next[1];
1500                self.next[1] = next[1];
1501                // In any of the "both" situations, self-loops would be iterated over twice.
1502                // Skip them here.
1503                if iterate_over.is_none() && node[0] == self.skip_start {
1504                    continue;
1505                }
1506
1507                return Some(EdgeReference {
1508                    index: edge_index,
1509                    node: if reverse == Some(Incoming) {
1510                        swap_pair(*node)
1511                    } else {
1512                        *node
1513                    },
1514                    weight: weight.as_ref().unwrap(),
1515                });
1516            }
1517        }
1518
1519        None
1520    }
1521}
1522
1523/// Iterator over the multiple directed edges connecting a source node to a target node
1524#[derive(Debug, Clone)]
1525pub struct EdgesConnecting<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1526where
1527    Ty: EdgeType,
1528    Ix: IndexType,
1529{
1530    target_node: NodeIndex<Ix>,
1531    edges: Edges<'a, E, Ty, Ix>,
1532    ty: PhantomData<Ty>,
1533}
1534
1535impl<'a, E, Ty, Ix> Iterator for EdgesConnecting<'a, E, Ty, Ix>
1536where
1537    Ty: EdgeType,
1538    Ix: IndexType,
1539{
1540    type Item = EdgeReference<'a, E, Ix>;
1541
1542    fn next(&mut self) -> Option<EdgeReference<'a, E, Ix>> {
1543        let target_node = self.target_node;
1544        self.edges
1545            .by_ref()
1546            .find(|&edge| edge.node[1] == target_node)
1547    }
1548    fn size_hint(&self) -> (usize, Option<usize>) {
1549        let (_, upper) = self.edges.size_hint();
1550        (0, upper)
1551    }
1552}
1553
1554fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1555    x.swap(0, 1);
1556    x
1557}
1558
1559/// Iterator over all edges of a graph.
1560#[derive(Debug, Clone)]
1561pub struct EdgeReferences<'a, E: 'a, Ix: 'a = DefaultIx> {
1562    iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1563}
1564
1565impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
1566where
1567    Ix: IndexType,
1568{
1569    type Item = EdgeReference<'a, E, Ix>;
1570
1571    fn next(&mut self) -> Option<Self::Item> {
1572        self.iter.ex_find_map(|(i, edge)| {
1573            edge.weight.as_ref().map(move |weight| EdgeReference {
1574                index: edge_index(i),
1575                node: edge.node,
1576                weight,
1577            })
1578        })
1579    }
1580}
1581
1582impl<E, Ix> DoubleEndedIterator for EdgeReferences<'_, E, Ix>
1583where
1584    Ix: IndexType,
1585{
1586    fn next_back(&mut self) -> Option<Self::Item> {
1587        self.iter.ex_rfind_map(|(i, edge)| {
1588            edge.weight.as_ref().map(move |weight| EdgeReference {
1589                index: edge_index(i),
1590                node: edge.node,
1591                weight,
1592            })
1593        })
1594    }
1595}
1596
1597/// An iterator over either the nodes without edges to them or from them.
1598#[derive(Debug, Clone)]
1599pub struct Externals<'a, N: 'a, Ty, Ix: IndexType = DefaultIx> {
1600    iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1601    dir: Direction,
1602    ty: PhantomData<Ty>,
1603}
1604
1605impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix>
1606where
1607    Ty: EdgeType,
1608    Ix: IndexType,
1609{
1610    type Item = NodeIndex<Ix>;
1611    fn next(&mut self) -> Option<NodeIndex<Ix>> {
1612        let k = self.dir.index();
1613        loop {
1614            match self.iter.next() {
1615                None => return None,
1616                Some((index, node)) => {
1617                    if node.weight.is_some()
1618                        && node.next[k] == EdgeIndex::end()
1619                        && (Ty::is_directed() || node.next[1 - k] == EdgeIndex::end())
1620                    {
1621                        return Some(NodeIndex::new(index));
1622                    } else {
1623                        continue;
1624                    }
1625                }
1626            }
1627        }
1628    }
1629    fn size_hint(&self) -> (usize, Option<usize>) {
1630        let (_, upper) = self.iter.size_hint();
1631        (0, upper)
1632    }
1633}
1634
1635/// Iterator over the neighbors of a node.
1636///
1637/// Iterator element type is `NodeIndex`.
1638#[derive(Debug, Clone)]
1639pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx> {
1640    /// starting node to skip over
1641    skip_start: NodeIndex<Ix>,
1642    edges: &'a [Edge<Option<E>, Ix>],
1643    next: [EdgeIndex<Ix>; 2],
1644}
1645
1646impl<E, Ix> Neighbors<'_, E, Ix>
1647where
1648    Ix: IndexType,
1649{
1650    /// Return a “walker” object that can be used to step through the
1651    /// neighbors and edges from the origin node.
1652    ///
1653    /// Note: The walker does not borrow from the graph, this is to allow mixing
1654    /// edge walking with mutating the graph's weights.
1655    pub fn detach(&self) -> WalkNeighbors<Ix> {
1656        WalkNeighbors {
1657            inner: super::WalkNeighbors {
1658                skip_start: self.skip_start,
1659                next: self.next,
1660            },
1661        }
1662    }
1663}
1664
1665impl<E, Ix> Iterator for Neighbors<'_, E, Ix>
1666where
1667    Ix: IndexType,
1668{
1669    type Item = NodeIndex<Ix>;
1670
1671    fn next(&mut self) -> Option<NodeIndex<Ix>> {
1672        // First any outgoing edges
1673        match self.edges.get(self.next[0].index()) {
1674            None => {}
1675            Some(edge) => {
1676                debug_assert!(edge.weight.is_some());
1677                self.next[0] = edge.next[0];
1678                return Some(edge.node[1]);
1679            }
1680        }
1681        // Then incoming edges
1682        // For an "undirected" iterator (traverse both incoming
1683        // and outgoing edge lists), make sure we don't double
1684        // count selfloops by skipping them in the incoming list.
1685        while let Some(edge) = self.edges.get(self.next[1].index()) {
1686            debug_assert!(edge.weight.is_some());
1687            self.next[1] = edge.next[1];
1688            if edge.node[0] != self.skip_start {
1689                return Some(edge.node[0]);
1690            }
1691        }
1692        None
1693    }
1694}
1695
1696/// A “walker” object that can be used to step through the edge list of a node.
1697///
1698/// See [*.detach()*](struct.Neighbors.html#method.detach) for more information.
1699///
1700/// The walker does not borrow from the graph, so it lets you step through
1701/// neighbors or incident edges while also mutating graph weights, as
1702/// in the following example:
1703///
1704/// ```
1705/// use petgraph::visit::Dfs;
1706/// use petgraph::Incoming;
1707/// use petgraph::stable_graph::StableGraph;
1708///
1709/// let mut gr = StableGraph::new();
1710/// let a = gr.add_node(0.);
1711/// let b = gr.add_node(0.);
1712/// let c = gr.add_node(0.);
1713/// gr.add_edge(a, b, 3.);
1714/// gr.add_edge(b, c, 2.);
1715/// gr.add_edge(c, b, 1.);
1716///
1717/// // step through the graph and sum incoming edges into the node weight
1718/// let mut dfs = Dfs::new(&gr, a);
1719/// while let Some(node) = dfs.next(&gr) {
1720///     // use a detached neighbors walker
1721///     let mut edges = gr.neighbors_directed(node, Incoming).detach();
1722///     while let Some(edge) = edges.next_edge(&gr) {
1723///         gr[node] += gr[edge];
1724///     }
1725/// }
1726///
1727/// // check the result
1728/// assert_eq!(gr[a], 0.);
1729/// assert_eq!(gr[b], 4.);
1730/// assert_eq!(gr[c], 2.);
1731/// ```
1732pub struct WalkNeighbors<Ix> {
1733    inner: super::WalkNeighbors<Ix>,
1734}
1735
1736impl<Ix: IndexType> Clone for WalkNeighbors<Ix> {
1737    clone_fields!(WalkNeighbors, inner);
1738}
1739
1740impl<Ix: IndexType> WalkNeighbors<Ix> {
1741    /// Step to the next edge and its endpoint node in the walk for graph `g`.
1742    ///
1743    /// The next node indices are always the others than the starting point
1744    /// where the `WalkNeighbors` value was created.
1745    /// For an `Outgoing` walk, the target nodes,
1746    /// for an `Incoming` walk, the source nodes of the edge.
1747    pub fn next<N, E, Ty: EdgeType>(
1748        &mut self,
1749        g: &StableGraph<N, E, Ty, Ix>,
1750    ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
1751        self.inner.next(&g.g)
1752    }
1753
1754    pub fn next_node<N, E, Ty: EdgeType>(
1755        &mut self,
1756        g: &StableGraph<N, E, Ty, Ix>,
1757    ) -> Option<NodeIndex<Ix>> {
1758        self.next(g).map(|t| t.1)
1759    }
1760
1761    pub fn next_edge<N, E, Ty: EdgeType>(
1762        &mut self,
1763        g: &StableGraph<N, E, Ty, Ix>,
1764    ) -> Option<EdgeIndex<Ix>> {
1765        self.next(g).map(|t| t.0)
1766    }
1767}
1768
1769/// Iterator over the node indices of a graph.
1770#[derive(Debug, Clone)]
1771pub struct NodeIndices<'a, N: 'a, Ix: 'a = DefaultIx> {
1772    iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1773}
1774
1775impl<N, Ix: IndexType> Iterator for NodeIndices<'_, N, Ix> {
1776    type Item = NodeIndex<Ix>;
1777
1778    fn next(&mut self) -> Option<Self::Item> {
1779        self.iter.ex_find_map(|(i, node)| {
1780            if node.weight.is_some() {
1781                Some(node_index(i))
1782            } else {
1783                None
1784            }
1785        })
1786    }
1787    fn size_hint(&self) -> (usize, Option<usize>) {
1788        let (_, upper) = self.iter.size_hint();
1789        (0, upper)
1790    }
1791}
1792
1793impl<N, Ix: IndexType> DoubleEndedIterator for NodeIndices<'_, N, Ix> {
1794    fn next_back(&mut self) -> Option<Self::Item> {
1795        self.iter.ex_rfind_map(|(i, node)| {
1796            if node.weight.is_some() {
1797                Some(node_index(i))
1798            } else {
1799                None
1800            }
1801        })
1802    }
1803}
1804
1805/// Iterator over the edge indices of a graph.
1806#[derive(Debug, Clone)]
1807pub struct EdgeIndices<'a, E: 'a, Ix: 'a = DefaultIx> {
1808    iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1809}
1810
1811impl<E, Ix: IndexType> Iterator for EdgeIndices<'_, E, Ix> {
1812    type Item = EdgeIndex<Ix>;
1813
1814    fn next(&mut self) -> Option<Self::Item> {
1815        self.iter.ex_find_map(|(i, node)| {
1816            if node.weight.is_some() {
1817                Some(edge_index(i))
1818            } else {
1819                None
1820            }
1821        })
1822    }
1823    fn size_hint(&self) -> (usize, Option<usize>) {
1824        let (_, upper) = self.iter.size_hint();
1825        (0, upper)
1826    }
1827}
1828
1829impl<E, Ix: IndexType> DoubleEndedIterator for EdgeIndices<'_, E, Ix> {
1830    fn next_back(&mut self) -> Option<Self::Item> {
1831        self.iter.ex_rfind_map(|(i, node)| {
1832            if node.weight.is_some() {
1833                Some(edge_index(i))
1834            } else {
1835                None
1836            }
1837        })
1838    }
1839}
1840
1841impl<N, E, Ty, Ix> visit::GraphBase for StableGraph<N, E, Ty, Ix>
1842where
1843    Ix: IndexType,
1844{
1845    type NodeId = NodeIndex<Ix>;
1846    type EdgeId = EdgeIndex<Ix>;
1847}
1848
1849impl<N, E, Ty, Ix> visit::Visitable for StableGraph<N, E, Ty, Ix>
1850where
1851    Ty: EdgeType,
1852    Ix: IndexType,
1853{
1854    type Map = FixedBitSet;
1855    fn visit_map(&self) -> FixedBitSet {
1856        FixedBitSet::with_capacity(self.node_bound())
1857    }
1858    fn reset_map(&self, map: &mut Self::Map) {
1859        map.clear();
1860        map.grow(self.node_bound());
1861    }
1862}
1863
1864impl<N, E, Ty, Ix> visit::Data for StableGraph<N, E, Ty, Ix>
1865where
1866    Ty: EdgeType,
1867    Ix: IndexType,
1868{
1869    type NodeWeight = N;
1870    type EdgeWeight = E;
1871}
1872
1873impl<N, E, Ty, Ix> visit::GraphProp for StableGraph<N, E, Ty, Ix>
1874where
1875    Ty: EdgeType,
1876    Ix: IndexType,
1877{
1878    type EdgeType = Ty;
1879}
1880
1881impl<'a, N, E: 'a, Ty, Ix> visit::IntoNodeIdentifiers for &'a StableGraph<N, E, Ty, Ix>
1882where
1883    Ty: EdgeType,
1884    Ix: IndexType,
1885{
1886    type NodeIdentifiers = NodeIndices<'a, N, Ix>;
1887    fn node_identifiers(self) -> Self::NodeIdentifiers {
1888        StableGraph::node_indices(self)
1889    }
1890}
1891
1892impl<N, E, Ty, Ix> visit::NodeCount for StableGraph<N, E, Ty, Ix>
1893where
1894    Ty: EdgeType,
1895    Ix: IndexType,
1896{
1897    fn node_count(&self) -> usize {
1898        self.node_count()
1899    }
1900}
1901
1902impl<'a, N, E, Ty, Ix> visit::IntoNodeReferences for &'a StableGraph<N, E, Ty, Ix>
1903where
1904    Ty: EdgeType,
1905    Ix: IndexType,
1906{
1907    type NodeRef = (NodeIndex<Ix>, &'a N);
1908    type NodeReferences = NodeReferences<'a, N, Ix>;
1909    fn node_references(self) -> Self::NodeReferences {
1910        NodeReferences {
1911            iter: enumerate(self.raw_nodes()),
1912        }
1913    }
1914}
1915
1916impl<N, E, Ty, Ix> visit::NodeIndexable for StableGraph<N, E, Ty, Ix>
1917where
1918    Ty: EdgeType,
1919    Ix: IndexType,
1920{
1921    /// Return an upper bound of the node indices in the graph
1922    fn node_bound(&self) -> usize {
1923        self.node_indices().next_back().map_or(0, |i| i.index() + 1)
1924    }
1925    fn to_index(&self, ix: NodeIndex<Ix>) -> usize {
1926        ix.index()
1927    }
1928    fn from_index(&self, ix: usize) -> Self::NodeId {
1929        NodeIndex::new(ix)
1930    }
1931}
1932
1933impl<'a, N, E: 'a, Ty, Ix> visit::IntoNeighbors for &'a StableGraph<N, E, Ty, Ix>
1934where
1935    Ty: EdgeType,
1936    Ix: IndexType,
1937{
1938    type Neighbors = Neighbors<'a, E, Ix>;
1939    fn neighbors(self, n: Self::NodeId) -> Self::Neighbors {
1940        (*self).neighbors(n)
1941    }
1942}
1943
1944impl<'a, N, E: 'a, Ty, Ix> visit::IntoNeighborsDirected for &'a StableGraph<N, E, Ty, Ix>
1945where
1946    Ty: EdgeType,
1947    Ix: IndexType,
1948{
1949    type NeighborsDirected = Neighbors<'a, E, Ix>;
1950    fn neighbors_directed(self, n: NodeIndex<Ix>, d: Direction) -> Self::NeighborsDirected {
1951        StableGraph::neighbors_directed(self, n, d)
1952    }
1953}
1954
1955impl<'a, N, E, Ty, Ix> visit::IntoEdges for &'a StableGraph<N, E, Ty, Ix>
1956where
1957    Ty: EdgeType,
1958    Ix: IndexType,
1959{
1960    type Edges = Edges<'a, E, Ty, Ix>;
1961    fn edges(self, a: Self::NodeId) -> Self::Edges {
1962        self.edges(a)
1963    }
1964}
1965
1966impl<Ix, E> visit::EdgeRef for EdgeReference<'_, E, Ix>
1967where
1968    Ix: IndexType,
1969{
1970    type NodeId = NodeIndex<Ix>;
1971    type EdgeId = EdgeIndex<Ix>;
1972    type Weight = E;
1973
1974    fn source(&self) -> Self::NodeId {
1975        self.node[0]
1976    }
1977    fn target(&self) -> Self::NodeId {
1978        self.node[1]
1979    }
1980    fn weight(&self) -> &E {
1981        self.weight
1982    }
1983    fn id(&self) -> Self::EdgeId {
1984        self.index
1985    }
1986}
1987
1988impl<N, E, Ty, Ix> visit::EdgeIndexable for StableGraph<N, E, Ty, Ix>
1989where
1990    Ty: EdgeType,
1991    Ix: IndexType,
1992{
1993    fn edge_bound(&self) -> usize {
1994        self.edge_references()
1995            .next_back()
1996            .map_or(0, |edge| edge.id().index() + 1)
1997    }
1998
1999    fn to_index(&self, ix: EdgeIndex<Ix>) -> usize {
2000        ix.index()
2001    }
2002
2003    fn from_index(&self, ix: usize) -> Self::EdgeId {
2004        EdgeIndex::new(ix)
2005    }
2006}
2007
2008impl<'a, N, E, Ty, Ix> visit::IntoEdgesDirected for &'a StableGraph<N, E, Ty, Ix>
2009where
2010    Ty: EdgeType,
2011    Ix: IndexType,
2012{
2013    type EdgesDirected = Edges<'a, E, Ty, Ix>;
2014    fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
2015        self.edges_directed(a, dir)
2016    }
2017}
2018
2019impl<'a, N: 'a, E: 'a, Ty, Ix> visit::IntoEdgeReferences for &'a StableGraph<N, E, Ty, Ix>
2020where
2021    Ty: EdgeType,
2022    Ix: IndexType,
2023{
2024    type EdgeRef = EdgeReference<'a, E, Ix>;
2025    type EdgeReferences = EdgeReferences<'a, E, Ix>;
2026
2027    /// Create an iterator over all edges in the graph, in indexed order.
2028    ///
2029    /// Iterator element type is `EdgeReference<E, Ix>`.
2030    fn edge_references(self) -> Self::EdgeReferences {
2031        EdgeReferences {
2032            iter: self.g.edges.iter().enumerate(),
2033        }
2034    }
2035}
2036
2037impl<N, E, Ty, Ix> visit::EdgeCount for StableGraph<N, E, Ty, Ix>
2038where
2039    Ty: EdgeType,
2040    Ix: IndexType,
2041{
2042    #[inline]
2043    fn edge_count(&self) -> usize {
2044        self.edge_count()
2045    }
2046}
2047
2048#[test]
2049fn stable_graph() {
2050    use std::println;
2051
2052    let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
2053    let a = gr.add_node(0);
2054    let b = gr.add_node(1);
2055    let c = gr.add_node(2);
2056    let _ed = gr.add_edge(a, b, 1);
2057    println!("{:?}", gr);
2058    gr.remove_node(b);
2059    println!("{:?}", gr);
2060    let d = gr.add_node(3);
2061    println!("{:?}", gr);
2062    gr.check_free_lists();
2063    gr.remove_node(a);
2064    gr.check_free_lists();
2065    gr.remove_node(c);
2066    gr.check_free_lists();
2067    println!("{:?}", gr);
2068    gr.add_edge(d, d, 2);
2069    println!("{:?}", gr);
2070
2071    let e = gr.add_node(4);
2072    gr.add_edge(d, e, 3);
2073    println!("{:?}", gr);
2074    for neigh in gr.neighbors(d) {
2075        println!("edge {:?} -> {:?}", d, neigh);
2076    }
2077    gr.check_free_lists();
2078}
2079
2080#[test]
2081fn dfs() {
2082    use std::println;
2083
2084    use crate::visit::Dfs;
2085
2086    let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
2087    let a = gr.add_node("a");
2088    let b = gr.add_node("b");
2089    let c = gr.add_node("c");
2090    let d = gr.add_node("d");
2091    gr.add_edge(a, b, 1);
2092    gr.add_edge(a, c, 2);
2093    gr.add_edge(b, c, 3);
2094    gr.add_edge(b, d, 4);
2095    gr.add_edge(c, d, 5);
2096    gr.add_edge(d, b, 6);
2097    gr.add_edge(c, b, 7);
2098    println!("{:?}", gr);
2099
2100    let mut dfs = Dfs::new(&gr, a);
2101    while let Some(next) = dfs.next(&gr) {
2102        println!("dfs visit => {:?}, weight={:?}", next, &gr[next]);
2103    }
2104}
2105
2106#[test]
2107fn test_retain_nodes() {
2108    let mut gr = StableGraph::<_, _>::with_capacity(6, 6);
2109    let a = gr.add_node("a");
2110    let f = gr.add_node("f");
2111    let b = gr.add_node("b");
2112    let c = gr.add_node("c");
2113    let d = gr.add_node("d");
2114    let e = gr.add_node("e");
2115    gr.add_edge(a, b, 1);
2116    gr.add_edge(a, c, 2);
2117    gr.add_edge(b, c, 3);
2118    gr.add_edge(b, d, 4);
2119    gr.add_edge(c, d, 5);
2120    gr.add_edge(d, b, 6);
2121    gr.add_edge(c, b, 7);
2122    gr.add_edge(d, e, 8);
2123    gr.remove_node(f);
2124
2125    assert_eq!(gr.node_count(), 5);
2126    assert_eq!(gr.edge_count(), 8);
2127    gr.retain_nodes(|frozen_gr, ix| frozen_gr[ix] >= "c");
2128    assert_eq!(gr.node_count(), 3);
2129    assert_eq!(gr.edge_count(), 2);
2130
2131    gr.check_free_lists();
2132}
2133
2134#[test]
2135fn extend_with_edges() {
2136    let mut gr = StableGraph::<_, _>::default();
2137    let a = gr.add_node("a");
2138    let b = gr.add_node("b");
2139    let c = gr.add_node("c");
2140    let _d = gr.add_node("d");
2141    gr.remove_node(a);
2142    gr.remove_node(b);
2143    gr.remove_node(c);
2144
2145    gr.extend_with_edges(vec![(0, 1, ())]);
2146    assert_eq!(gr.node_count(), 3);
2147    assert_eq!(gr.edge_count(), 1);
2148    gr.check_free_lists();
2149
2150    gr.extend_with_edges(vec![(5, 1, ())]);
2151    assert_eq!(gr.node_count(), 4);
2152    assert_eq!(gr.edge_count(), 2);
2153    gr.check_free_lists();
2154}
2155
2156#[test]
2157fn test_reverse() {
2158    let mut gr = StableGraph::<_, _>::default();
2159    let a = gr.add_node("a");
2160    let b = gr.add_node("b");
2161
2162    gr.add_edge(a, b, 0);
2163
2164    let mut reversed_gr = gr.clone();
2165    reversed_gr.reverse();
2166
2167    for i in gr.node_indices() {
2168        itertools::assert_equal(gr.edges_directed(i, Incoming), reversed_gr.edges(i));
2169    }
2170}