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