1use std::cmp;
2use std::fmt;
3use std::hash::Hash;
4use std::iter;
5use std::marker::PhantomData;
6use std::mem::size_of;
7use std::ops::{Index, IndexMut, Range};
8use std::slice;
9
10use fixedbitset::FixedBitSet;
11
12use crate::{Directed, Direction, EdgeType, Incoming, IntoWeightedEdge, Outgoing, Undirected};
13
14use crate::iter_format::{DebugMap, IterFormatExt, NoPretty};
15
16use crate::util::enumerate;
17use crate::visit;
18
19#[cfg(feature = "serde-1")]
20mod serialization;
21
22pub type DefaultIx = u32;
29
30pub unsafe trait IndexType: Copy + Default + Hash + Ord + fmt::Debug + 'static {
37 fn new(x: usize) -> Self;
38 fn index(&self) -> usize;
39 fn max() -> Self;
40}
41
42unsafe impl IndexType for usize {
43 #[inline(always)]
44 fn new(x: usize) -> Self {
45 x
46 }
47 #[inline(always)]
48 fn index(&self) -> Self {
49 *self
50 }
51 #[inline(always)]
52 fn max() -> Self {
53 ::std::usize::MAX
54 }
55}
56
57unsafe impl IndexType for u32 {
58 #[inline(always)]
59 fn new(x: usize) -> Self {
60 x as u32
61 }
62 #[inline(always)]
63 fn index(&self) -> usize {
64 *self as usize
65 }
66 #[inline(always)]
67 fn max() -> Self {
68 ::std::u32::MAX
69 }
70}
71
72unsafe impl IndexType for u16 {
73 #[inline(always)]
74 fn new(x: usize) -> Self {
75 x as u16
76 }
77 #[inline(always)]
78 fn index(&self) -> usize {
79 *self as usize
80 }
81 #[inline(always)]
82 fn max() -> Self {
83 ::std::u16::MAX
84 }
85}
86
87unsafe impl IndexType for u8 {
88 #[inline(always)]
89 fn new(x: usize) -> Self {
90 x as u8
91 }
92 #[inline(always)]
93 fn index(&self) -> usize {
94 *self as usize
95 }
96 #[inline(always)]
97 fn max() -> Self {
98 ::std::u8::MAX
99 }
100}
101
102#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
104pub struct NodeIndex<Ix = DefaultIx>(Ix);
105
106impl<Ix: IndexType> NodeIndex<Ix> {
107 #[inline]
108 pub fn new(x: usize) -> Self {
109 NodeIndex(IndexType::new(x))
110 }
111
112 #[inline]
113 pub fn index(self) -> usize {
114 self.0.index()
115 }
116
117 #[inline]
118 pub fn end() -> Self {
119 NodeIndex(IndexType::max())
120 }
121
122 fn _into_edge(self) -> EdgeIndex<Ix> {
123 EdgeIndex(self.0)
124 }
125}
126
127unsafe impl<Ix: IndexType> IndexType for NodeIndex<Ix> {
128 fn index(&self) -> usize {
129 self.0.index()
130 }
131 fn new(x: usize) -> Self {
132 NodeIndex::new(x)
133 }
134 fn max() -> Self {
135 NodeIndex(<Ix as IndexType>::max())
136 }
137}
138
139impl<Ix: IndexType> From<Ix> for NodeIndex<Ix> {
140 fn from(ix: Ix) -> Self {
141 NodeIndex(ix)
142 }
143}
144
145impl<Ix: fmt::Debug> fmt::Debug for NodeIndex<Ix> {
146 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
147 write!(f, "NodeIndex({:?})", self.0)
148 }
149}
150
151pub fn node_index<Ix: IndexType>(index: usize) -> NodeIndex<Ix> {
153 NodeIndex::new(index)
154}
155
156pub fn edge_index<Ix: IndexType>(index: usize) -> EdgeIndex<Ix> {
158 EdgeIndex::new(index)
159}
160
161#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
163pub struct EdgeIndex<Ix = DefaultIx>(Ix);
164
165impl<Ix: IndexType> EdgeIndex<Ix> {
166 #[inline]
167 pub fn new(x: usize) -> Self {
168 EdgeIndex(IndexType::new(x))
169 }
170
171 #[inline]
172 pub fn index(self) -> usize {
173 self.0.index()
174 }
175
176 #[inline]
179 pub fn end() -> Self {
180 EdgeIndex(IndexType::max())
181 }
182
183 fn _into_node(self) -> NodeIndex<Ix> {
184 NodeIndex(self.0)
185 }
186}
187
188impl<Ix: IndexType> From<Ix> for EdgeIndex<Ix> {
189 fn from(ix: Ix) -> Self {
190 EdgeIndex(ix)
191 }
192}
193
194impl<Ix: fmt::Debug> fmt::Debug for EdgeIndex<Ix> {
195 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
196 write!(f, "EdgeIndex({:?})", self.0)
197 }
198}
199const DIRECTIONS: [Direction; 2] = [Outgoing, Incoming];
216
217#[derive(Debug)]
219pub struct Node<N, Ix = DefaultIx> {
220 pub weight: N,
222 next: [EdgeIndex<Ix>; 2],
224}
225
226impl<E, Ix> Clone for Node<E, Ix>
227where
228 E: Clone,
229 Ix: Copy,
230{
231 clone_fields!(Node, weight, next,);
232}
233
234impl<N, Ix: IndexType> Node<N, Ix> {
235 pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix> {
237 self.next[dir.index()]
238 }
239}
240
241#[derive(Debug)]
243pub struct Edge<E, Ix = DefaultIx> {
244 pub weight: E,
246 next: [EdgeIndex<Ix>; 2],
248 node: [NodeIndex<Ix>; 2],
250}
251
252impl<E, Ix> Clone for Edge<E, Ix>
253where
254 E: Clone,
255 Ix: Copy,
256{
257 clone_fields!(Edge, weight, next, node,);
258}
259
260impl<E, Ix: IndexType> Edge<E, Ix> {
261 pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix> {
263 self.next[dir.index()]
264 }
265
266 pub fn source(&self) -> NodeIndex<Ix> {
268 self.node[0]
269 }
270
271 pub fn target(&self) -> NodeIndex<Ix> {
273 self.node[1]
274 }
275}
276
277pub 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
353pub type DiGraph<N, E, Ix = DefaultIx> = Graph<N, E, Directed, Ix>;
358
359pub type UnGraph<N, E, Ix = DefaultIx> = Graph<N, E, Undirected, Ix>;
364
365impl<N, E, Ty, Ix: IndexType> Clone for Graph<N, E, Ty, Ix>
367where
368 N: Clone,
369 E: Clone,
370{
371 fn clone(&self) -> Self {
372 Graph {
373 nodes: self.nodes.clone(),
374 edges: self.edges.clone(),
375 ty: self.ty,
376 }
377 }
378
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
386impl<N, E, Ty, Ix> fmt::Debug for Graph<N, E, Ty, Ix>
387where
388 N: fmt::Debug,
389 E: fmt::Debug,
390 Ty: EdgeType,
391 Ix: IndexType,
392{
393 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 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
430enum Pair<T> {
431 Both(T, T),
432 One(T),
433 None,
434}
435
436use std::cmp::max;
437
438fn 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 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
455impl<N, E> Graph<N, E, Directed> {
456 pub fn new() -> Self {
461 Graph {
462 nodes: Vec::new(),
463 edges: Vec::new(),
464 ty: PhantomData,
465 }
466 }
467}
468
469impl<N, E> Graph<N, E, Undirected> {
470 pub fn new_undirected() -> Self {
475 Graph {
476 nodes: Vec::new(),
477 edges: Vec::new(),
478 ty: PhantomData,
479 }
480 }
481}
482
483impl<N, E, Ty, Ix> Graph<N, E, Ty, Ix>
484where
485 Ty: EdgeType,
486 Ix: IndexType,
487{
488 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 pub fn node_count(&self) -> usize {
501 self.nodes.len()
502 }
503
504 pub fn edge_count(&self) -> usize {
508 self.edges.len()
509 }
510
511 #[inline]
513 pub fn is_directed(&self) -> bool {
514 Ty::is_directed()
515 }
516
517 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 assert!(<Ix as IndexType>::max().index() == !0 || NodeIndex::end() != node_idx);
533 self.nodes.push(node);
534 node_idx
535 }
536
537 pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
542 self.nodes.get(a.index()).map(|n| &n.weight)
543 }
544
545 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 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 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 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 pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
616 self.edges.get(e.index()).map(|ed| &ed.weight)
617 }
618
619 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 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 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 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 let node = self.nodes.swap_remove(a.index());
669
670 let swap_edges = match self.nodes.get(a.index()) {
673 None => return Some(node.weight),
674 Some(ed) => ed.next,
675 };
676
677 let old_index = NodeIndex::new(self.nodes.len());
679 let new_index = a;
680
681 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 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 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; }
725 }
726 }
727 }
728 }
729
730 pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
738 let (edge_node, edge_next) = match self.edges.get(e.index()) {
742 None => return None,
743 Some(x) => (x.node, x.next),
744 };
745 self.change_edge_links(edge_node, e, edge_next);
748 self.remove_edge_adjust_indices(e)
749 }
750
751 fn remove_edge_adjust_indices(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
752 let edge = self.edges.swap_remove(e.index());
756 let swap = match self.edges.get(e.index()) {
757 None => return Some(edge.weight),
759 Some(ed) => ed.node,
760 };
761 let swapped_e = EdgeIndex::new(self.edges.len());
762
763 self.change_edge_links(swap, swapped_e, [e, e]);
766 Some(edge.weight)
767 }
768
769 pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
782 self.neighbors_directed(a, Outgoing)
783 }
784
785 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 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 pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
847 self.edges_directed(a, Outgoing)
848 }
849
850 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 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 pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
897 self.find_edge(a, b).is_some()
898 }
899
900 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
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 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
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 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 pub fn node_indices(&self) -> NodeIndices<Ix> {
998 NodeIndices {
999 r: 0..self.node_count(),
1000 ty: PhantomData,
1001 }
1002 }
1003
1004 pub fn node_weights_mut(&mut self) -> NodeWeightsMut<N, Ix> {
1009 NodeWeightsMut {
1010 nodes: self.nodes.iter_mut(),
1011 }
1012 }
1013
1014 pub fn node_weights(&self) -> NodeWeights<N, Ix> {
1019 NodeWeights {
1020 nodes: self.nodes.iter(),
1021 }
1022 }
1023
1024 pub fn edge_indices(&self) -> EdgeIndices<Ix> {
1026 EdgeIndices {
1027 r: 0..self.edge_count(),
1028 ty: PhantomData,
1029 }
1030 }
1031
1032 pub fn edge_references(&self) -> EdgeReferences<E, Ix> {
1036 EdgeReferences {
1037 iter: self.edges.iter().enumerate(),
1038 }
1039 }
1040
1041 pub fn edge_weights(&self) -> EdgeWeights<E, Ix> {
1046 EdgeWeights {
1047 edges: self.edges.iter(),
1048 }
1049 }
1050 pub fn edge_weights_mut(&mut self) -> EdgeWeightsMut<E, Ix> {
1055 EdgeWeightsMut {
1056 edges: self.edges.iter_mut(),
1057 }
1058 }
1059
1060 pub fn raw_nodes(&self) -> &[Node<N, Ix>] {
1065 &self.nodes
1066 }
1067
1068 pub fn raw_edges(&self) -> &[Edge<E, Ix>] {
1070 &self.edges
1071 }
1072
1073 #[allow(clippy::type_complexity)]
1074 pub fn into_nodes_edges(self) -> (Vec<Node<N, Ix>>, Vec<Edge<E, Ix>>) {
1076 (self.nodes, self.edges)
1077 }
1078
1079 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 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 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 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 pub fn reverse(&mut self) {
1169 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 pub fn clear(&mut self) {
1183 self.nodes.clear();
1184 self.edges.clear();
1185 }
1186
1187 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 pub fn capacity(&self) -> (usize, usize) {
1197 (self.nodes.capacity(), self.edges.capacity())
1198 }
1199
1200 pub fn reserve_nodes(&mut self, additional: usize) {
1205 self.nodes.reserve(additional);
1206 }
1207
1208 pub fn reserve_edges(&mut self, additional: usize) {
1213 self.edges.reserve(additional);
1214 }
1215
1216 pub fn reserve_exact_nodes(&mut self, additional: usize) {
1224 self.nodes.reserve_exact(additional);
1225 }
1226
1227 pub fn reserve_exact_edges(&mut self, additional: usize) {
1235 self.edges.reserve_exact(additional);
1236 }
1237
1238 pub fn shrink_to_fit_nodes(&mut self) {
1240 self.nodes.shrink_to_fit();
1241 }
1242
1243 pub fn shrink_to_fit_edges(&mut self) {
1245 self.edges.shrink_to_fit();
1246 }
1247
1248 pub fn shrink_to_fit(&mut self) {
1250 self.nodes.shrink_to_fit();
1251 self.edges.shrink_to_fit();
1252 }
1253
1254 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 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 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 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 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 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 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 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 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 #[cfg(feature = "serde-1")]
1440 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 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#[derive(Debug, Clone)]
1467pub 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
1473impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix>
1474where
1475 Ty: EdgeType,
1476 Ix: IndexType,
1477{
1478 type Item = 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 }
1496 fn size_hint(&self) -> (usize, Option<usize>) {
1497 let (_, upper) = self.iter.size_hint();
1498 (0, upper)
1499 }
1500}
1501
1502#[derive(Debug)]
1513pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx> {
1514 skip_start: NodeIndex<Ix>,
1516 edges: &'a [Edge<E, Ix>],
1517 next: [EdgeIndex<Ix>; 2],
1518}
1519
1520impl<E, Ix> Iterator for Neighbors<'_, E, Ix>
1521where
1522 Ix: IndexType,
1523{
1524 type Item = NodeIndex<Ix>;
1525
1526 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1527 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 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
1549impl<E, Ix> Clone for Neighbors<'_, E, Ix>
1550where
1551 Ix: IndexType,
1552{
1553 clone_fields!(Neighbors, skip_start, edges, next,);
1554}
1555
1556impl<E, Ix> Neighbors<'_, E, Ix>
1557where
1558 Ix: IndexType,
1559{
1560 pub fn detach(&self) -> WalkNeighbors<Ix> {
1566 WalkNeighbors {
1567 skip_start: self.skip_start,
1568 next: self.next,
1569 }
1570 }
1571}
1572
1573struct EdgesWalkerMut<'a, E: 'a, Ix: IndexType = DefaultIx> {
1574 edges: &'a mut [Edge<E, Ix>],
1575 next: EdgeIndex<Ix>,
1576 dir: Direction,
1577}
1578
1579fn edges_walker_mut<E, Ix>(
1580 edges: &mut [Edge<E, Ix>],
1581 next: EdgeIndex<Ix>,
1582 dir: Direction,
1583) -> EdgesWalkerMut<E, Ix>
1584where
1585 Ix: IndexType,
1586{
1587 EdgesWalkerMut { edges, next, dir }
1588}
1589
1590impl<E, Ix> EdgesWalkerMut<'_, E, Ix>
1591where
1592 Ix: IndexType,
1593{
1594 fn next_edge(&mut self) -> Option<&mut Edge<E, Ix>> {
1595 self.next().map(|t| t.1)
1596 }
1597
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
1611impl<'a, N, E, Ty, Ix> visit::IntoEdges for &'a Graph<N, E, Ty, Ix>
1612where
1613 Ty: EdgeType,
1614 Ix: IndexType,
1615{
1616 type Edges = Edges<'a, E, Ty, Ix>;
1617 fn edges(self, a: Self::NodeId) -> Self::Edges {
1618 self.edges(a)
1619 }
1620}
1621
1622impl<'a, N, E, Ty, Ix> visit::IntoEdgesDirected for &'a Graph<N, E, Ty, Ix>
1623where
1624 Ty: EdgeType,
1625 Ix: IndexType,
1626{
1627 type EdgesDirected = Edges<'a, E, Ty, Ix>;
1628 fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
1629 self.edges_directed(a, dir)
1630 }
1631}
1632
1633#[derive(Debug)]
1635pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1636where
1637 Ty: EdgeType,
1638 Ix: IndexType,
1639{
1640 skip_start: NodeIndex<Ix>,
1642 edges: &'a [Edge<E, Ix>],
1643
1644 next: [EdgeIndex<Ix>; 2],
1646
1647 direction: Direction,
1650 ty: PhantomData<Ty>,
1651}
1652
1653impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1654where
1655 Ty: EdgeType,
1656 Ix: IndexType,
1657{
1658 type Item = EdgeReference<'a, E, Ix>;
1659
1660 fn next(&mut self) -> Option<Self::Item> {
1661 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 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#[derive(Debug, Clone)]
1720pub struct EdgesConnecting<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1721where
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
1730impl<'a, E, Ty, Ix> Iterator for EdgesConnecting<'a, E, Ty, Ix>
1731where
1732 Ty: EdgeType,
1733 Ix: IndexType,
1734{
1735 type Item = EdgeReference<'a, E, Ix>;
1736
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 }
1743 fn size_hint(&self) -> (usize, Option<usize>) {
1744 let (_, upper) = self.edges.size_hint();
1745 (0, upper)
1746 }
1747}
1748
1749fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1750 x.swap(0, 1);
1751 x
1752}
1753
1754impl<E, Ty, Ix> Clone for Edges<'_, E, Ty, Ix>
1755where
1756 Ix: IndexType,
1757 Ty: EdgeType,
1758{
1759 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
1770pub struct NodeWeights<'a, N: 'a, Ix: IndexType = DefaultIx> {
1772 nodes: ::std::slice::Iter<'a, Node<N, Ix>>,
1773}
1774impl<'a, N, Ix> Iterator for NodeWeights<'a, N, Ix>
1775where
1776 Ix: IndexType,
1777{
1778 type Item = &'a N;
1779
1780 fn next(&mut self) -> Option<&'a N> {
1781 self.nodes.next().map(|node| &node.weight)
1782 }
1783
1784 fn size_hint(&self) -> (usize, Option<usize>) {
1785 self.nodes.size_hint()
1786 }
1787}
1788#[derive(Debug)]
1790pub struct NodeWeightsMut<'a, N: 'a, Ix: IndexType = DefaultIx> {
1791 nodes: ::std::slice::IterMut<'a, Node<N, Ix>>, }
1793
1794impl<'a, N, Ix> Iterator for NodeWeightsMut<'a, N, Ix>
1795where
1796 Ix: IndexType,
1797{
1798 type Item = &'a mut N;
1799
1800 fn next(&mut self) -> Option<&'a mut N> {
1801 self.nodes.next().map(|node| &mut node.weight)
1802 }
1803
1804 fn size_hint(&self) -> (usize, Option<usize>) {
1805 self.nodes.size_hint()
1806 }
1807}
1808
1809pub struct EdgeWeights<'a, E: 'a, Ix: IndexType = DefaultIx> {
1811 edges: ::std::slice::Iter<'a, Edge<E, Ix>>,
1812}
1813
1814impl<'a, E, Ix> Iterator for EdgeWeights<'a, E, Ix>
1815where
1816 Ix: IndexType,
1817{
1818 type Item = &'a E;
1819
1820 fn next(&mut self) -> Option<&'a E> {
1821 self.edges.next().map(|edge| &edge.weight)
1822 }
1823
1824 fn size_hint(&self) -> (usize, Option<usize>) {
1825 self.edges.size_hint()
1826 }
1827}
1828
1829#[derive(Debug)]
1831pub struct EdgeWeightsMut<'a, E: 'a, Ix: IndexType = DefaultIx> {
1832 edges: ::std::slice::IterMut<'a, Edge<E, Ix>>, }
1834
1835impl<'a, E, Ix> Iterator for EdgeWeightsMut<'a, E, Ix>
1836where
1837 Ix: IndexType,
1838{
1839 type Item = &'a mut E;
1840
1841 fn next(&mut self) -> Option<&'a mut E> {
1842 self.edges.next().map(|edge| &mut edge.weight)
1843 }
1844
1845 fn size_hint(&self) -> (usize, Option<usize>) {
1846 self.edges.size_hint()
1847 }
1848}
1849
1850impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for Graph<N, E, Ty, Ix>
1854where
1855 Ty: EdgeType,
1856 Ix: IndexType,
1857{
1858 type Output = N;
1859 fn index(&self, index: NodeIndex<Ix>) -> &N {
1860 &self.nodes[index.index()].weight
1861 }
1862}
1863
1864impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for Graph<N, E, Ty, Ix>
1868where
1869 Ty: EdgeType,
1870 Ix: IndexType,
1871{
1872 fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1873 &mut self.nodes[index.index()].weight
1874 }
1875}
1876
1877impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix>
1881where
1882 Ty: EdgeType,
1883 Ix: IndexType,
1884{
1885 type Output = E;
1886 fn index(&self, index: EdgeIndex<Ix>) -> &E {
1887 &self.edges[index.index()].weight
1888 }
1889}
1890
1891impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix>
1895where
1896 Ty: EdgeType,
1897 Ix: IndexType,
1898{
1899 fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
1900 &mut self.edges[index.index()].weight
1901 }
1902}
1903
1904impl<N, E, Ty, Ix> Default for Graph<N, E, Ty, Ix>
1906where
1907 Ty: EdgeType,
1908 Ix: IndexType,
1909{
1910 fn default() -> Self {
1911 Self::with_capacity(0, 0)
1912 }
1913}
1914
1915pub trait GraphIndex: Copy {
1917 #[doc(hidden)]
1918 fn index(&self) -> usize;
1919 #[doc(hidden)]
1920 fn is_node_index() -> bool;
1921}
1922
1923impl<Ix: IndexType> GraphIndex for NodeIndex<Ix> {
1924 #[inline]
1925 #[doc(hidden)]
1926 fn index(&self) -> usize {
1927 NodeIndex::index(*self)
1928 }
1929 #[inline]
1930 #[doc(hidden)]
1931 fn is_node_index() -> bool {
1932 true
1933 }
1934}
1935
1936impl<Ix: IndexType> GraphIndex for EdgeIndex<Ix> {
1937 #[inline]
1938 #[doc(hidden)]
1939 fn index(&self) -> usize {
1940 EdgeIndex::index(*self)
1941 }
1942 #[inline]
1943 #[doc(hidden)]
1944 fn is_node_index() -> bool {
1945 false
1946 }
1947}
1948
1949pub struct WalkNeighbors<Ix> {
1985 skip_start: NodeIndex<Ix>,
1986 next: [EdgeIndex<Ix>; 2],
1987}
1988
1989impl<Ix> Clone for WalkNeighbors<Ix>
1990where
1991 Ix: IndexType,
1992{
1993 fn clone(&self) -> Self {
1994 WalkNeighbors {
1995 skip_start: self.skip_start,
1996 next: self.next,
1997 }
1998 }
1999}
2000
2001impl<Ix: IndexType> WalkNeighbors<Ix> {
2002 pub fn next<N, E, Ty: EdgeType>(
2009 &mut self,
2010 g: &Graph<N, E, Ty, Ix>,
2011 ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
2012 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 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
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
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#[derive(Clone, Debug)]
2052pub struct NodeIndices<Ix = DefaultIx> {
2053 r: Range<usize>,
2054 ty: PhantomData<fn() -> Ix>,
2055}
2056
2057impl<Ix: IndexType> Iterator for NodeIndices<Ix> {
2058 type Item = NodeIndex<Ix>;
2059
2060 fn next(&mut self) -> Option<Self::Item> {
2061 self.r.next().map(node_index)
2062 }
2063
2064 fn size_hint(&self) -> (usize, Option<usize>) {
2065 self.r.size_hint()
2066 }
2067}
2068
2069impl<Ix: IndexType> DoubleEndedIterator for NodeIndices<Ix> {
2070 fn next_back(&mut self) -> Option<Self::Item> {
2071 self.r.next_back().map(node_index)
2072 }
2073}
2074
2075impl<Ix: IndexType> ExactSizeIterator for NodeIndices<Ix> {}
2076
2077#[derive(Clone, Debug)]
2079pub struct EdgeIndices<Ix = DefaultIx> {
2080 r: Range<usize>,
2081 ty: PhantomData<fn() -> Ix>,
2082}
2083
2084impl<Ix: IndexType> Iterator for EdgeIndices<Ix> {
2085 type Item = EdgeIndex<Ix>;
2086
2087 fn next(&mut self) -> Option<Self::Item> {
2088 self.r.next().map(edge_index)
2089 }
2090
2091 fn size_hint(&self) -> (usize, Option<usize>) {
2092 self.r.size_hint()
2093 }
2094}
2095
2096impl<Ix: IndexType> DoubleEndedIterator for EdgeIndices<Ix> {
2097 fn next_back(&mut self) -> Option<Self::Item> {
2098 self.r.next_back().map(edge_index)
2099 }
2100}
2101
2102impl<Ix: IndexType> ExactSizeIterator for EdgeIndices<Ix> {}
2103
2104#[derive(Debug)]
2106pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
2107 index: EdgeIndex<Ix>,
2108 node: [NodeIndex<Ix>; 2],
2109 weight: &'a E,
2110}
2111
2112impl<E, Ix: IndexType> Clone for EdgeReference<'_, E, Ix> {
2113 fn clone(&self) -> Self {
2114 *self
2115 }
2116}
2117
2118impl<E, Ix: IndexType> Copy for EdgeReference<'_, E, Ix> {}
2119
2120impl<E, Ix: IndexType> PartialEq for EdgeReference<'_, E, Ix>
2121where
2122 E: PartialEq,
2123{
2124 fn eq(&self, rhs: &Self) -> bool {
2125 self.index == rhs.index && self.weight == rhs.weight
2126 }
2127}
2128
2129impl<N, E, Ty, Ix> visit::GraphBase for Graph<N, E, Ty, Ix>
2130where
2131 Ix: IndexType,
2132{
2133 type NodeId = NodeIndex<Ix>;
2134 type EdgeId = EdgeIndex<Ix>;
2135}
2136
2137impl<N, E, Ty, Ix> visit::Visitable for Graph<N, E, Ty, Ix>
2138where
2139 Ty: EdgeType,
2140 Ix: IndexType,
2141{
2142 type Map = FixedBitSet;
2143 fn visit_map(&self) -> FixedBitSet {
2144 FixedBitSet::with_capacity(self.node_count())
2145 }
2146
2147 fn reset_map(&self, map: &mut Self::Map) {
2148 map.clear();
2149 map.grow(self.node_count());
2150 }
2151}
2152
2153impl<N, E, Ty, Ix> visit::GraphProp for Graph<N, E, Ty, Ix>
2154where
2155 Ty: EdgeType,
2156 Ix: IndexType,
2157{
2158 type EdgeType = Ty;
2159}
2160
2161impl<'a, N, E: 'a, Ty, Ix> visit::IntoNodeIdentifiers for &'a Graph<N, E, Ty, Ix>
2162where
2163 Ty: EdgeType,
2164 Ix: IndexType,
2165{
2166 type NodeIdentifiers = NodeIndices<Ix>;
2167 fn node_identifiers(self) -> NodeIndices<Ix> {
2168 Graph::node_indices(self)
2169 }
2170}
2171
2172impl<N, E, Ty, Ix> visit::NodeCount for Graph<N, E, Ty, Ix>
2173where
2174 Ty: EdgeType,
2175 Ix: IndexType,
2176{
2177 fn node_count(&self) -> usize {
2178 self.node_count()
2179 }
2180}
2181
2182impl<N, E, Ty, Ix> visit::NodeIndexable for Graph<N, E, Ty, Ix>
2183where
2184 Ty: EdgeType,
2185 Ix: IndexType,
2186{
2187 #[inline]
2188 fn node_bound(&self) -> usize {
2189 self.node_count()
2190 }
2191 #[inline]
2192 fn to_index(&self, ix: NodeIndex<Ix>) -> usize {
2193 ix.index()
2194 }
2195 #[inline]
2196 fn from_index(&self, ix: usize) -> Self::NodeId {
2197 NodeIndex::new(ix)
2198 }
2199}
2200
2201impl<N, E, Ty, Ix> visit::NodeCompactIndexable for Graph<N, E, Ty, Ix>
2202where
2203 Ty: EdgeType,
2204 Ix: IndexType,
2205{
2206}
2207
2208impl<'a, N, E: 'a, Ty, Ix> visit::IntoNeighbors for &'a Graph<N, E, Ty, Ix>
2209where
2210 Ty: EdgeType,
2211 Ix: IndexType,
2212{
2213 type Neighbors = Neighbors<'a, E, Ix>;
2214 fn neighbors(self, n: NodeIndex<Ix>) -> Neighbors<'a, E, Ix> {
2215 Graph::neighbors(self, n)
2216 }
2217}
2218
2219impl<'a, N, E: 'a, Ty, Ix> visit::IntoNeighborsDirected for &'a Graph<N, E, Ty, Ix>
2220where
2221 Ty: EdgeType,
2222 Ix: IndexType,
2223{
2224 type NeighborsDirected = 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
2230impl<'a, N: 'a, E: 'a, Ty, Ix> visit::IntoEdgeReferences for &'a Graph<N, E, Ty, Ix>
2231where
2232 Ty: EdgeType,
2233 Ix: IndexType,
2234{
2235 type EdgeRef = EdgeReference<'a, E, Ix>;
2236 type EdgeReferences = EdgeReferences<'a, E, Ix>;
2237 fn edge_references(self) -> Self::EdgeReferences {
2238 (*self).edge_references()
2239 }
2240}
2241
2242impl<N, E, Ty, Ix> visit::EdgeCount for Graph<N, E, Ty, Ix>
2243where
2244 Ty: EdgeType,
2245 Ix: IndexType,
2246{
2247 #[inline]
2248 fn edge_count(&self) -> usize {
2249 self.edge_count()
2250 }
2251}
2252
2253impl<'a, N, E, Ty, Ix> visit::IntoNodeReferences for &'a Graph<N, E, Ty, Ix>
2254where
2255 Ty: EdgeType,
2256 Ix: IndexType,
2257{
2258 type NodeRef = (NodeIndex<Ix>, &'a N);
2259 type NodeReferences = NodeReferences<'a, N, Ix>;
2260 fn node_references(self) -> Self::NodeReferences {
2261 NodeReferences {
2262 iter: self.nodes.iter().enumerate(),
2263 }
2264 }
2265}
2266
2267#[derive(Debug, Clone)]
2269pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
2270 iter: iter::Enumerate<slice::Iter<'a, Node<N, Ix>>>,
2271}
2272
2273impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
2274where
2275 Ix: IndexType,
2276{
2277 type Item = (NodeIndex<Ix>, &'a N);
2278
2279 fn next(&mut self) -> Option<Self::Item> {
2280 self.iter
2281 .next()
2282 .map(|(i, node)| (node_index(i), &node.weight))
2283 }
2284
2285 fn size_hint(&self) -> (usize, Option<usize>) {
2286 self.iter.size_hint()
2287 }
2288}
2289
2290impl<N, Ix> DoubleEndedIterator for NodeReferences<'_, N, Ix>
2291where
2292 Ix: IndexType,
2293{
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
2301impl<N, Ix> ExactSizeIterator for NodeReferences<'_, N, Ix> where Ix: IndexType {}
2302
2303impl<'a, Ix, E> EdgeReference<'a, E, Ix>
2304where
2305 Ix: IndexType,
2306{
2307 pub fn weight(&self) -> &'a E {
2312 self.weight
2313 }
2314}
2315
2316impl<Ix, E> visit::EdgeRef for EdgeReference<'_, E, Ix>
2317where
2318 Ix: IndexType,
2319{
2320 type NodeId = NodeIndex<Ix>;
2321 type EdgeId = EdgeIndex<Ix>;
2322 type Weight = E;
2323
2324 fn source(&self) -> Self::NodeId {
2325 self.node[0]
2326 }
2327 fn target(&self) -> Self::NodeId {
2328 self.node[1]
2329 }
2330 fn weight(&self) -> &E {
2331 self.weight
2332 }
2333 fn id(&self) -> Self::EdgeId {
2334 self.index
2335 }
2336}
2337
2338#[derive(Debug, Clone)]
2340pub struct EdgeReferences<'a, E: 'a, Ix: IndexType = DefaultIx> {
2341 iter: iter::Enumerate<slice::Iter<'a, Edge<E, Ix>>>,
2342}
2343
2344impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
2345where
2346 Ix: IndexType,
2347{
2348 type Item = EdgeReference<'a, E, Ix>;
2349
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
2358 fn size_hint(&self) -> (usize, Option<usize>) {
2359 self.iter.size_hint()
2360 }
2361}
2362
2363impl<E, Ix> DoubleEndedIterator for EdgeReferences<'_, E, Ix>
2364where
2365 Ix: IndexType,
2366{
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
2376impl<E, Ix> ExactSizeIterator for EdgeReferences<'_, E, Ix> where Ix: IndexType {}
2377
2378impl<N, E, Ty, Ix> visit::EdgeIndexable for Graph<N, E, Ty, Ix>
2379where
2380 Ty: EdgeType,
2381 Ix: IndexType,
2382{
2383 fn edge_bound(&self) -> usize {
2384 self.edge_count()
2385 }
2386
2387 fn to_index(&self, ix: EdgeIndex<Ix>) -> usize {
2388 ix.index()
2389 }
2390
2391 fn from_index(&self, ix: usize) -> Self::EdgeId {
2392 EdgeIndex::new(ix)
2393 }
2394}
2395
2396mod frozen;
2397#[cfg(feature = "stable_graph")]
2398pub mod stable_graph;
2399
2400pub struct Frozen<'a, G: 'a>(&'a mut G);