petgraph/graph_impl/
mod.rs

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