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