Skip to main content

petgraph/graph_impl/
mod.rs

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