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