petgraph/graph_impl/
mod.rs

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