1use alloc::{vec, vec::Vec};
2use core::{
3 cmp, fmt,
4 hash::Hash,
5 iter,
6 marker::PhantomData,
7 mem::size_of,
8 ops::{Index, IndexMut, Range},
9 slice,
10};
11
12use fixedbitset::FixedBitSet;
13
14use crate::{Directed, Direction, EdgeType, Incoming, IntoWeightedEdge, Outgoing, Undirected};
15
16use crate::iter_format::{DebugMap, IterFormatExt, NoPretty};
17
18use crate::util::enumerate;
19use crate::visit;
20
21#[cfg(feature = "serde-1")]
22mod serialization;
23
24pub type DefaultIx = u32;
31
32pub unsafe trait IndexType: Copy + Default + Hash + Ord + fmt::Debug + 'static {
39 fn new(x: usize) -> Self;
40 fn index(&self) -> usize;
41 fn max() -> Self;
42}
43
44unsafe impl IndexType for usize {
45 #[inline(always)]
46 fn new(x: usize) -> Self {
47 x
48 }
49 #[inline(always)]
50 fn index(&self) -> Self {
51 *self
52 }
53 #[inline(always)]
54 fn max() -> Self {
55 usize::MAX
56 }
57}
58
59unsafe impl IndexType for u32 {
60 #[inline(always)]
61 fn new(x: usize) -> Self {
62 x as u32
63 }
64 #[inline(always)]
65 fn index(&self) -> usize {
66 *self as usize
67 }
68 #[inline(always)]
69 fn max() -> Self {
70 u32::MAX
71 }
72}
73
74unsafe impl IndexType for u16 {
75 #[inline(always)]
76 fn new(x: usize) -> Self {
77 x as u16
78 }
79 #[inline(always)]
80 fn index(&self) -> usize {
81 *self as usize
82 }
83 #[inline(always)]
84 fn max() -> Self {
85 u16::MAX
86 }
87}
88
89unsafe impl IndexType for u8 {
90 #[inline(always)]
91 fn new(x: usize) -> Self {
92 x as u8
93 }
94 #[inline(always)]
95 fn index(&self) -> usize {
96 *self as usize
97 }
98 #[inline(always)]
99 fn max() -> Self {
100 u8::MAX
101 }
102}
103
104#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
106pub struct NodeIndex<Ix = DefaultIx>(Ix);
107
108impl<Ix: IndexType> NodeIndex<Ix> {
109 #[inline]
110 pub fn new(x: usize) -> Self {
111 NodeIndex(IndexType::new(x))
112 }
113
114 #[inline]
115 pub fn index(self) -> usize {
116 self.0.index()
117 }
118
119 #[inline]
120 pub fn end() -> Self {
121 NodeIndex(IndexType::max())
122 }
123
124 fn _into_edge(self) -> EdgeIndex<Ix> {
125 EdgeIndex(self.0)
126 }
127}
128
129unsafe impl<Ix: IndexType> IndexType for NodeIndex<Ix> {
130 fn index(&self) -> usize {
131 self.0.index()
132 }
133 fn new(x: usize) -> Self {
134 NodeIndex::new(x)
135 }
136 fn max() -> Self {
137 NodeIndex(<Ix as IndexType>::max())
138 }
139}
140
141impl<Ix: IndexType> From<Ix> for NodeIndex<Ix> {
142 fn from(ix: Ix) -> Self {
143 NodeIndex(ix)
144 }
145}
146
147impl<Ix: fmt::Debug> fmt::Debug for NodeIndex<Ix> {
148 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
149 write!(f, "NodeIndex({:?})", self.0)
150 }
151}
152
153pub fn node_index<Ix: IndexType>(index: usize) -> NodeIndex<Ix> {
155 NodeIndex::new(index)
156}
157
158pub fn edge_index<Ix: IndexType>(index: usize) -> EdgeIndex<Ix> {
160 EdgeIndex::new(index)
161}
162
163#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
165pub struct EdgeIndex<Ix = DefaultIx>(Ix);
166
167impl<Ix: IndexType> EdgeIndex<Ix> {
168 #[inline]
169 pub fn new(x: usize) -> Self {
170 EdgeIndex(IndexType::new(x))
171 }
172
173 #[inline]
174 pub fn index(self) -> usize {
175 self.0.index()
176 }
177
178 #[inline]
181 pub fn end() -> Self {
182 EdgeIndex(IndexType::max())
183 }
184
185 fn _into_node(self) -> NodeIndex<Ix> {
186 NodeIndex(self.0)
187 }
188}
189
190impl<Ix: IndexType> From<Ix> for EdgeIndex<Ix> {
191 fn from(ix: Ix) -> Self {
192 EdgeIndex(ix)
193 }
194}
195
196impl<Ix: fmt::Debug> fmt::Debug for EdgeIndex<Ix> {
197 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
198 write!(f, "EdgeIndex({:?})", self.0)
199 }
200}
201const DIRECTIONS: [Direction; 2] = [Outgoing, Incoming];
218
219#[derive(Debug)]
221pub struct Node<N, Ix = DefaultIx> {
222 pub weight: N,
224 next: [EdgeIndex<Ix>; 2],
226}
227
228impl<E, Ix> Clone for Node<E, Ix>
229where
230 E: Clone,
231 Ix: Copy,
232{
233 clone_fields!(Node, weight, next,);
234}
235
236impl<N, Ix: IndexType> Node<N, Ix> {
237 pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix> {
239 self.next[dir.index()]
240 }
241}
242
243#[derive(Debug)]
245pub struct Edge<E, Ix = DefaultIx> {
246 pub weight: E,
248 next: [EdgeIndex<Ix>; 2],
250 node: [NodeIndex<Ix>; 2],
252}
253
254impl<E, Ix> Clone for Edge<E, Ix>
255where
256 E: Clone,
257 Ix: Copy,
258{
259 clone_fields!(Edge, weight, next, node,);
260}
261
262impl<E, Ix: IndexType> Edge<E, Ix> {
263 pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix> {
265 self.next[dir.index()]
266 }
267
268 pub fn source(&self) -> NodeIndex<Ix> {
270 self.node[0]
271 }
272
273 pub fn target(&self) -> NodeIndex<Ix> {
275 self.node[1]
276 }
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub enum GraphError {
282 NodeIxLimit,
284
285 EdgeIxLimit,
287
288 NodeMissed(usize),
290
291 NodeOutBounds,
293}
294
295#[cfg(feature = "std")]
296impl std::error::Error for GraphError {}
297
298#[cfg(not(feature = "std"))]
299impl core::error::Error for GraphError {}
300
301impl fmt::Display for GraphError {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 match self {
304 GraphError::NodeIxLimit => write!(
305 f,
306 "The Graph is at the maximum number of nodes for its index"
307 ),
308 GraphError::EdgeIxLimit => write!(
309 f,
310 "The Graph is at the maximum number of edges for its index."
311 ),
312 GraphError::NodeMissed(i) => {
313 write!(f, "The node with index {i} is missing from the graph.")
314 }
315 GraphError::NodeOutBounds => write!(f, "Node indices out of bounds."),
316 }
317 }
318}
319
320pub struct Graph<N, E, Ty = Directed, Ix = DefaultIx> {
391 nodes: Vec<Node<N, Ix>>,
392 edges: Vec<Edge<E, Ix>>,
393 ty: PhantomData<Ty>,
394}
395
396pub type DiGraph<N, E, Ix = DefaultIx> = Graph<N, E, Directed, Ix>;
401
402pub type UnGraph<N, E, Ix = DefaultIx> = Graph<N, E, Undirected, Ix>;
407
408impl<N, E, Ty, Ix: IndexType> Clone for Graph<N, E, Ty, Ix>
410where
411 N: Clone,
412 E: Clone,
413{
414 fn clone(&self) -> Self {
415 Graph {
416 nodes: self.nodes.clone(),
417 edges: self.edges.clone(),
418 ty: self.ty,
419 }
420 }
421
422 fn clone_from(&mut self, rhs: &Self) {
423 self.nodes.clone_from(&rhs.nodes);
424 self.edges.clone_from(&rhs.edges);
425 self.ty = rhs.ty;
426 }
427}
428
429impl<N, E, Ty, Ix> fmt::Debug for Graph<N, E, Ty, Ix>
430where
431 N: fmt::Debug,
432 E: fmt::Debug,
433 Ty: EdgeType,
434 Ix: IndexType,
435{
436 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
437 let etype = if self.is_directed() {
438 "Directed"
439 } else {
440 "Undirected"
441 };
442 let mut fmt_struct = f.debug_struct("Graph");
443 fmt_struct.field("Ty", &etype);
444 fmt_struct.field("node_count", &self.node_count());
445 fmt_struct.field("edge_count", &self.edge_count());
446 if self.edge_count() > 0 {
447 fmt_struct.field(
448 "edges",
449 &self
450 .edges
451 .iter()
452 .map(|e| NoPretty((e.source().index(), e.target().index())))
453 .format(", "),
454 );
455 }
456 if size_of::<N>() != 0 {
458 fmt_struct.field(
459 "node weights",
460 &DebugMap(|| self.nodes.iter().map(|n| &n.weight).enumerate()),
461 );
462 }
463 if size_of::<E>() != 0 {
464 fmt_struct.field(
465 "edge weights",
466 &DebugMap(|| self.edges.iter().map(|n| &n.weight).enumerate()),
467 );
468 }
469 fmt_struct.finish()
470 }
471}
472
473enum Pair<T> {
474 Both(T, T),
475 One(T),
476 None,
477}
478
479use core::cmp::max;
480
481fn index_twice<T>(slc: &mut [T], a: usize, b: usize) -> Pair<&mut T> {
483 if max(a, b) >= slc.len() {
484 Pair::None
485 } else if a == b {
486 Pair::One(&mut slc[max(a, b)])
487 } else {
488 unsafe {
490 let ptr = slc.as_mut_ptr();
491 let ar = &mut *ptr.add(a);
492 let br = &mut *ptr.add(b);
493 Pair::Both(ar, br)
494 }
495 }
496}
497
498impl<N, E> Graph<N, E, Directed> {
499 pub fn new() -> Self {
504 Graph {
505 nodes: Vec::new(),
506 edges: Vec::new(),
507 ty: PhantomData,
508 }
509 }
510}
511
512impl<N, E> Graph<N, E, Undirected> {
513 pub fn new_undirected() -> Self {
518 Graph {
519 nodes: Vec::new(),
520 edges: Vec::new(),
521 ty: PhantomData,
522 }
523 }
524}
525
526impl<N, E, Ty, Ix> Graph<N, E, Ty, Ix>
527where
528 Ty: EdgeType,
529 Ix: IndexType,
530{
531 pub fn with_capacity(nodes: usize, edges: usize) -> Self {
533 Graph {
534 nodes: Vec::with_capacity(nodes),
535 edges: Vec::with_capacity(edges),
536 ty: PhantomData,
537 }
538 }
539
540 pub fn node_count(&self) -> usize {
544 self.nodes.len()
545 }
546
547 pub fn edge_count(&self) -> usize {
551 self.edges.len()
552 }
553
554 #[inline]
556 pub fn is_directed(&self) -> bool {
557 Ty::is_directed()
558 }
559
560 #[track_caller]
569 pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
570 self.try_add_node(weight).unwrap()
571 }
572
573 pub fn try_add_node(&mut self, weight: N) -> Result<NodeIndex<Ix>, GraphError> {
581 let node = Node {
582 weight,
583 next: [EdgeIndex::end(), EdgeIndex::end()],
584 };
585 let node_idx = NodeIndex::new(self.nodes.len());
586 if <Ix as IndexType>::max().index() == !0 || NodeIndex::end() != node_idx {
588 self.nodes.push(node);
589 Ok(node_idx)
590 } else {
591 Err(GraphError::NodeIxLimit)
592 }
593 }
594
595 pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
600 self.nodes.get(a.index()).map(|n| &n.weight)
601 }
602
603 pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
608 self.nodes.get_mut(a.index()).map(|n| &mut n.weight)
609 }
610
611 #[track_caller]
625 pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
626 let res = self.try_add_edge(a, b, weight);
627 if res == Err(GraphError::NodeOutBounds) {
628 panic!("Graph::add_edge: node indices out of bounds");
629 }
630 res.unwrap()
631 }
632
633 pub fn try_add_edge(
648 &mut self,
649 a: NodeIndex<Ix>,
650 b: NodeIndex<Ix>,
651 weight: E,
652 ) -> Result<EdgeIndex<Ix>, GraphError> {
653 let edge_idx = EdgeIndex::new(self.edges.len());
654 if !(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx) {
655 return Err(GraphError::EdgeIxLimit);
656 }
657
658 let mut edge = Edge {
659 weight,
660 node: [a, b],
661 next: [EdgeIndex::end(); 2],
662 };
663 match index_twice(&mut self.nodes, a.index(), b.index()) {
664 Pair::None => return Err(GraphError::NodeOutBounds),
665 Pair::One(an) => {
666 edge.next = an.next;
667 an.next[0] = edge_idx;
668 an.next[1] = edge_idx;
669 }
670 Pair::Both(an, bn) => {
671 edge.next = [an.next[0], bn.next[1]];
673 an.next[0] = edge_idx;
674 bn.next[1] = edge_idx;
675 }
676 }
677 self.edges.push(edge);
678 Ok(edge_idx)
679 }
680
681 #[track_caller]
692 pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
693 self.try_update_edge(a, b, weight).unwrap()
694 }
695
696 pub fn try_update_edge(
709 &mut self,
710 a: NodeIndex<Ix>,
711 b: NodeIndex<Ix>,
712 weight: E,
713 ) -> Result<EdgeIndex<Ix>, GraphError> {
714 if let Some(ix) = self.find_edge(a, b) {
715 if let Some(ed) = self.edge_weight_mut(ix) {
716 *ed = weight;
717 return Ok(ix);
718 }
719 }
720 self.try_add_edge(a, b, weight)
721 }
722
723 pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
728 self.edges.get(e.index()).map(|ed| &ed.weight)
729 }
730
731 pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
736 self.edges.get_mut(e.index()).map(|ed| &mut ed.weight)
737 }
738
739 pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)> {
743 self.edges
744 .get(e.index())
745 .map(|ed| (ed.source(), ed.target()))
746 }
747
748 pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N> {
761 self.nodes.get(a.index())?;
762 for d in &DIRECTIONS {
763 let k = d.index();
764
765 loop {
767 let next = self.nodes[a.index()].next[k];
768 if next == EdgeIndex::end() {
769 break;
770 }
771 let ret = self.remove_edge(next);
772 debug_assert!(ret.is_some());
773 let _ = ret;
774 }
775 }
776
777 let node = self.nodes.swap_remove(a.index());
781
782 let swap_edges = match self.nodes.get(a.index()) {
785 None => return Some(node.weight),
786 Some(ed) => ed.next,
787 };
788
789 let old_index = NodeIndex::new(self.nodes.len());
791 let new_index = a;
792
793 for &d in &DIRECTIONS {
795 let k = d.index();
796 let mut edges = edges_walker_mut(&mut self.edges, swap_edges[k], d);
797 while let Some(curedge) = edges.next_edge() {
798 debug_assert!(curedge.node[k] == old_index);
799 curedge.node[k] = new_index;
800 }
801 }
802 Some(node.weight)
803 }
804
805 fn change_edge_links(
808 &mut self,
809 edge_node: [NodeIndex<Ix>; 2],
810 e: EdgeIndex<Ix>,
811 edge_next: [EdgeIndex<Ix>; 2],
812 ) {
813 for &d in &DIRECTIONS {
814 let k = d.index();
815 let node = match self.nodes.get_mut(edge_node[k].index()) {
816 Some(r) => r,
817 None => {
818 debug_assert!(
819 false,
820 "Edge's endpoint dir={:?} index={:?} not found",
821 d, edge_node[k]
822 );
823 return;
824 }
825 };
826 let fst = node.next[k];
827 if fst == e {
828 node.next[k] = edge_next[k];
830 } else {
831 let mut edges = edges_walker_mut(&mut self.edges, fst, d);
832 while let Some(curedge) = edges.next_edge() {
833 if curedge.next[k] == e {
834 curedge.next[k] = edge_next[k];
835 break; }
837 }
838 }
839 }
840 }
841
842 pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
850 let (edge_node, edge_next) = match self.edges.get(e.index()) {
854 None => return None,
855 Some(x) => (x.node, x.next),
856 };
857 self.change_edge_links(edge_node, e, edge_next);
860 self.remove_edge_adjust_indices(e)
861 }
862
863 fn remove_edge_adjust_indices(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
864 let edge = self.edges.swap_remove(e.index());
868 let swap = match self.edges.get(e.index()) {
869 None => return Some(edge.weight),
871 Some(ed) => ed.node,
872 };
873 let swapped_e = EdgeIndex::new(self.edges.len());
874
875 self.change_edge_links(swap, swapped_e, [e, e]);
878 Some(edge.weight)
879 }
880
881 pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
894 self.neighbors_directed(a, Outgoing)
895 }
896
897 pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix> {
917 let mut iter = self.neighbors_undirected(a);
918 if self.is_directed() {
919 let k = dir.index();
920 iter.next[1 - k] = EdgeIndex::end();
921 iter.skip_start = NodeIndex::end();
922 }
923 iter
924 }
925
926 pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
941 Neighbors {
942 skip_start: a,
943 edges: &self.edges,
944 next: match self.nodes.get(a.index()) {
945 None => [EdgeIndex::end(), EdgeIndex::end()],
946 Some(n) => n.next,
947 },
948 }
949 }
950
951 pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
959 self.edges_directed(a, Outgoing)
960 }
961
962 pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix> {
974 Edges {
975 skip_start: a,
976 edges: &self.edges,
977 direction: dir,
978 next: match self.nodes.get(a.index()) {
979 None => [EdgeIndex::end(), EdgeIndex::end()],
980 Some(n) => n.next,
981 },
982 ty: PhantomData,
983 }
984 }
985
986 pub fn edges_connecting(
993 &self,
994 a: NodeIndex<Ix>,
995 b: NodeIndex<Ix>,
996 ) -> EdgesConnecting<E, Ty, Ix> {
997 EdgesConnecting {
998 target_node: b,
999 edges: self.edges_directed(a, Direction::Outgoing),
1000 ty: PhantomData,
1001 }
1002 }
1003
1004 pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
1009 self.find_edge(a, b).is_some()
1010 }
1011
1012 pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>> {
1017 if !self.is_directed() {
1018 self.find_edge_undirected(a, b).map(|(ix, _)| ix)
1019 } else {
1020 match self.nodes.get(a.index()) {
1021 None => None,
1022 Some(node) => self.find_edge_directed_from_node(node, b),
1023 }
1024 }
1025 }
1026
1027 fn find_edge_directed_from_node(
1028 &self,
1029 node: &Node<N, Ix>,
1030 b: NodeIndex<Ix>,
1031 ) -> Option<EdgeIndex<Ix>> {
1032 let mut edix = node.next[0];
1033 while let Some(edge) = self.edges.get(edix.index()) {
1034 if edge.node[1] == b {
1035 return Some(edix);
1036 }
1037 edix = edge.next[0];
1038 }
1039 None
1040 }
1041
1042 pub fn find_edge_undirected(
1050 &self,
1051 a: NodeIndex<Ix>,
1052 b: NodeIndex<Ix>,
1053 ) -> Option<(EdgeIndex<Ix>, Direction)> {
1054 match self.nodes.get(a.index()) {
1055 None => None,
1056 Some(node) => self.find_edge_undirected_from_node(node, b),
1057 }
1058 }
1059
1060 fn find_edge_undirected_from_node(
1061 &self,
1062 node: &Node<N, Ix>,
1063 b: NodeIndex<Ix>,
1064 ) -> Option<(EdgeIndex<Ix>, Direction)> {
1065 for &d in &DIRECTIONS {
1066 let k = d.index();
1067 let mut edix = node.next[k];
1068 while let Some(edge) = self.edges.get(edix.index()) {
1069 if edge.node[1 - k] == b {
1070 return Some((edix, d));
1071 }
1072 edix = edge.next[k];
1073 }
1074 }
1075 None
1076 }
1077
1078 pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix> {
1090 Externals {
1091 iter: self.nodes.iter().enumerate(),
1092 dir,
1093 ty: PhantomData,
1094 }
1095 }
1096
1097 pub fn node_indices(&self) -> NodeIndices<Ix> {
1110 NodeIndices {
1111 r: 0..self.node_count(),
1112 ty: PhantomData,
1113 }
1114 }
1115
1116 pub fn node_weights_mut(&mut self) -> NodeWeightsMut<N, Ix> {
1121 NodeWeightsMut {
1122 nodes: self.nodes.iter_mut(),
1123 }
1124 }
1125
1126 pub fn node_weights(&self) -> NodeWeights<N, Ix> {
1131 NodeWeights {
1132 nodes: self.nodes.iter(),
1133 }
1134 }
1135
1136 pub fn edge_indices(&self) -> EdgeIndices<Ix> {
1138 EdgeIndices {
1139 r: 0..self.edge_count(),
1140 ty: PhantomData,
1141 }
1142 }
1143
1144 pub fn edge_references(&self) -> EdgeReferences<E, Ix> {
1148 EdgeReferences {
1149 iter: self.edges.iter().enumerate(),
1150 }
1151 }
1152
1153 pub fn edge_weights(&self) -> EdgeWeights<E, Ix> {
1158 EdgeWeights {
1159 edges: self.edges.iter(),
1160 }
1161 }
1162 pub fn edge_weights_mut(&mut self) -> EdgeWeightsMut<E, Ix> {
1167 EdgeWeightsMut {
1168 edges: self.edges.iter_mut(),
1169 }
1170 }
1171
1172 pub fn raw_nodes(&self) -> &[Node<N, Ix>] {
1177 &self.nodes
1178 }
1179
1180 pub fn raw_edges(&self) -> &[Edge<E, Ix>] {
1182 &self.edges
1183 }
1184
1185 #[allow(clippy::type_complexity)]
1186 pub fn into_nodes_edges(self) -> (Vec<Node<N, Ix>>, Vec<Edge<E, Ix>>) {
1188 (self.nodes, self.edges)
1189 }
1190
1191 pub fn first_edge(&self, a: NodeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>> {
1193 match self.nodes.get(a.index()) {
1194 None => None,
1195 Some(node) => {
1196 let edix = node.next[dir.index()];
1197 if edix == EdgeIndex::end() {
1198 None
1199 } else {
1200 Some(edix)
1201 }
1202 }
1203 }
1204 }
1205
1206 pub fn next_edge(&self, e: EdgeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>> {
1208 match self.edges.get(e.index()) {
1209 None => None,
1210 Some(node) => {
1211 let edix = node.next[dir.index()];
1212 if edix == EdgeIndex::end() {
1213 None
1214 } else {
1215 Some(edix)
1216 }
1217 }
1218 }
1219 }
1220
1221 #[track_caller]
1255 pub fn index_twice_mut<T, U>(
1256 &mut self,
1257 i: T,
1258 j: U,
1259 ) -> (
1260 &mut <Self as Index<T>>::Output,
1261 &mut <Self as Index<U>>::Output,
1262 )
1263 where
1264 Self: IndexMut<T> + IndexMut<U>,
1265 T: GraphIndex,
1266 U: GraphIndex,
1267 {
1268 assert!(T::is_node_index() != U::is_node_index() || i.index() != j.index());
1269
1270 unsafe {
1272 let self_mut = self as *mut _;
1273 (
1274 <Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
1275 <Self as IndexMut<U>>::index_mut(&mut *self_mut, j),
1276 )
1277 }
1278 }
1279
1280 pub fn reverse(&mut self) {
1282 for edge in &mut self.edges {
1286 edge.node.swap(0, 1);
1287 edge.next.swap(0, 1);
1288 }
1289 for node in &mut self.nodes {
1290 node.next.swap(0, 1);
1291 }
1292 }
1293
1294 pub fn clear(&mut self) {
1296 self.nodes.clear();
1297 self.edges.clear();
1298 }
1299
1300 pub fn clear_edges(&mut self) {
1302 self.edges.clear();
1303 for node in &mut self.nodes {
1304 node.next = [EdgeIndex::end(), EdgeIndex::end()];
1305 }
1306 }
1307
1308 pub fn capacity(&self) -> (usize, usize) {
1310 (self.nodes.capacity(), self.edges.capacity())
1311 }
1312
1313 #[track_caller]
1318 pub fn reserve_nodes(&mut self, additional: usize) {
1319 self.nodes.reserve(additional);
1320 }
1321
1322 #[track_caller]
1327 pub fn reserve_edges(&mut self, additional: usize) {
1328 self.edges.reserve(additional);
1329 }
1330
1331 #[track_caller]
1339 pub fn reserve_exact_nodes(&mut self, additional: usize) {
1340 self.nodes.reserve_exact(additional);
1341 }
1342
1343 #[track_caller]
1351 pub fn reserve_exact_edges(&mut self, additional: usize) {
1352 self.edges.reserve_exact(additional);
1353 }
1354
1355 pub fn shrink_to_fit_nodes(&mut self) {
1357 self.nodes.shrink_to_fit();
1358 }
1359
1360 pub fn shrink_to_fit_edges(&mut self) {
1362 self.edges.shrink_to_fit();
1363 }
1364
1365 pub fn shrink_to_fit(&mut self) {
1367 self.nodes.shrink_to_fit();
1368 self.edges.shrink_to_fit();
1369 }
1370
1371 pub fn retain_nodes<F>(&mut self, mut visit: F)
1379 where
1380 F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,
1381 {
1382 for index in self.node_indices().rev() {
1383 if !visit(Frozen(self), index) {
1384 let ret = self.remove_node(index);
1385 debug_assert!(ret.is_some());
1386 let _ = ret;
1387 }
1388 }
1389 }
1390
1391 pub fn retain_edges<F>(&mut self, mut visit: F)
1399 where
1400 F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,
1401 {
1402 for index in self.edge_indices().rev() {
1403 if !visit(Frozen(self), index) {
1404 let ret = self.remove_edge(index);
1405 debug_assert!(ret.is_some());
1406 let _ = ret;
1407 }
1408 }
1409 }
1410
1411 pub fn from_edges<I>(iterable: I) -> Self
1429 where
1430 I: IntoIterator,
1431 I::Item: IntoWeightedEdge<E>,
1432 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1433 N: Default,
1434 {
1435 let mut g = Self::with_capacity(0, 0);
1436 g.extend_with_edges(iterable);
1437 g
1438 }
1439
1440 pub fn extend_with_edges<I>(&mut self, iterable: I)
1448 where
1449 I: IntoIterator,
1450 I::Item: IntoWeightedEdge<E>,
1451 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1452 N: Default,
1453 {
1454 let iter = iterable.into_iter();
1455 let (low, _) = iter.size_hint();
1456 self.edges.reserve(low);
1457
1458 for elt in iter {
1459 let (source, target, weight) = elt.into_weighted_edge();
1460 let (source, target) = (source.into(), target.into());
1461 let nx = cmp::max(source, target);
1462 while nx.index() >= self.node_count() {
1463 self.add_node(N::default());
1464 }
1465 self.add_edge(source, target, weight);
1466 }
1467 }
1468
1469 pub fn map<'a, F, G, N2, E2>(
1475 &'a self,
1476 mut node_map: F,
1477 mut edge_map: G,
1478 ) -> Graph<N2, E2, Ty, Ix>
1479 where
1480 F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
1481 G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
1482 {
1483 let mut g = Graph::with_capacity(self.node_count(), self.edge_count());
1484 g.nodes.extend(enumerate(&self.nodes).map(|(i, node)| Node {
1485 weight: node_map(NodeIndex::new(i), &node.weight),
1486 next: node.next,
1487 }));
1488 g.edges.extend(enumerate(&self.edges).map(|(i, edge)| Edge {
1489 weight: edge_map(EdgeIndex::new(i), &edge.weight),
1490 next: edge.next,
1491 node: edge.node,
1492 }));
1493 g
1494 }
1495
1496 pub fn filter_map<'a, F, G, N2, E2>(
1509 &'a self,
1510 mut node_map: F,
1511 mut edge_map: G,
1512 ) -> Graph<N2, E2, Ty, Ix>
1513 where
1514 F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
1515 G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
1516 {
1517 let mut g = Graph::with_capacity(0, 0);
1518 let mut node_index_map = vec![NodeIndex::end(); self.node_count()];
1520 for (i, node) in enumerate(&self.nodes) {
1521 if let Some(nw) = node_map(NodeIndex::new(i), &node.weight) {
1522 node_index_map[i] = g.add_node(nw);
1523 }
1524 }
1525 for (i, edge) in enumerate(&self.edges) {
1526 let source = node_index_map[edge.source().index()];
1528 let target = node_index_map[edge.target().index()];
1529 if source != NodeIndex::end() && target != NodeIndex::end() {
1530 if let Some(ew) = edge_map(EdgeIndex::new(i), &edge.weight) {
1531 g.add_edge(source, target, ew);
1532 }
1533 }
1534 }
1535 g
1536 }
1537
1538 pub fn into_edge_type<NewTy>(self) -> Graph<N, E, NewTy, Ix>
1543 where
1544 NewTy: EdgeType,
1545 {
1546 Graph {
1547 nodes: self.nodes,
1548 edges: self.edges,
1549 ty: PhantomData,
1550 }
1551 }
1552
1553 #[cfg(feature = "serde-1")]
1557 fn link_edges(&mut self) -> Result<(), NodeIndex<Ix>> {
1559 for (edge_index, edge) in enumerate(&mut self.edges) {
1560 let a = edge.source();
1561 let b = edge.target();
1562 let edge_idx = EdgeIndex::new(edge_index);
1563 match index_twice(&mut self.nodes, a.index(), b.index()) {
1564 Pair::None => return Err(if a > b { a } else { b }),
1565 Pair::One(an) => {
1566 edge.next = an.next;
1567 an.next[0] = edge_idx;
1568 an.next[1] = edge_idx;
1569 }
1570 Pair::Both(an, bn) => {
1571 edge.next = [an.next[0], bn.next[1]];
1573 an.next[0] = edge_idx;
1574 bn.next[1] = edge_idx;
1575 }
1576 }
1577 }
1578 Ok(())
1579 }
1580}
1581
1582#[derive(Debug, Clone)]
1584pub struct Externals<'a, N: 'a, Ty, Ix: IndexType = DefaultIx> {
1585 iter: iter::Enumerate<slice::Iter<'a, Node<N, Ix>>>,
1586 dir: Direction,
1587 ty: PhantomData<Ty>,
1588}
1589
1590impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix>
1591where
1592 Ty: EdgeType,
1593 Ix: IndexType,
1594{
1595 type Item = NodeIndex<Ix>;
1596 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1597 let k = self.dir.index();
1598 loop {
1599 match self.iter.next() {
1600 None => return None,
1601 Some((index, node)) => {
1602 if node.next[k] == EdgeIndex::end()
1603 && (Ty::is_directed() || node.next[1 - k] == EdgeIndex::end())
1604 {
1605 return Some(NodeIndex::new(index));
1606 } else {
1607 continue;
1608 }
1609 }
1610 }
1611 }
1612 }
1613 fn size_hint(&self) -> (usize, Option<usize>) {
1614 let (_, upper) = self.iter.size_hint();
1615 (0, upper)
1616 }
1617}
1618
1619#[derive(Debug)]
1630pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx> {
1631 skip_start: NodeIndex<Ix>,
1633 edges: &'a [Edge<E, Ix>],
1634 next: [EdgeIndex<Ix>; 2],
1635}
1636
1637impl<E, Ix> Iterator for Neighbors<'_, E, Ix>
1638where
1639 Ix: IndexType,
1640{
1641 type Item = NodeIndex<Ix>;
1642
1643 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1644 match self.edges.get(self.next[0].index()) {
1646 None => {}
1647 Some(edge) => {
1648 self.next[0] = edge.next[0];
1649 return Some(edge.node[1]);
1650 }
1651 }
1652 while let Some(edge) = self.edges.get(self.next[1].index()) {
1657 self.next[1] = edge.next[1];
1658 if edge.node[0] != self.skip_start {
1659 return Some(edge.node[0]);
1660 }
1661 }
1662 None
1663 }
1664}
1665
1666impl<E, Ix> Clone for Neighbors<'_, E, Ix>
1667where
1668 Ix: IndexType,
1669{
1670 clone_fields!(Neighbors, skip_start, edges, next,);
1671}
1672
1673impl<E, Ix> Neighbors<'_, E, Ix>
1674where
1675 Ix: IndexType,
1676{
1677 pub fn detach(&self) -> WalkNeighbors<Ix> {
1683 WalkNeighbors {
1684 skip_start: self.skip_start,
1685 next: self.next,
1686 }
1687 }
1688}
1689
1690struct EdgesWalkerMut<'a, E: 'a, Ix: IndexType = DefaultIx> {
1691 edges: &'a mut [Edge<E, Ix>],
1692 next: EdgeIndex<Ix>,
1693 dir: Direction,
1694}
1695
1696fn edges_walker_mut<E, Ix>(
1697 edges: &mut [Edge<E, Ix>],
1698 next: EdgeIndex<Ix>,
1699 dir: Direction,
1700) -> EdgesWalkerMut<E, Ix>
1701where
1702 Ix: IndexType,
1703{
1704 EdgesWalkerMut { edges, next, dir }
1705}
1706
1707impl<E, Ix> EdgesWalkerMut<'_, E, Ix>
1708where
1709 Ix: IndexType,
1710{
1711 fn next_edge(&mut self) -> Option<&mut Edge<E, Ix>> {
1712 self.next().map(|t| t.1)
1713 }
1714
1715 fn next(&mut self) -> Option<(EdgeIndex<Ix>, &mut Edge<E, Ix>)> {
1716 let this_index = self.next;
1717 let k = self.dir.index();
1718 match self.edges.get_mut(self.next.index()) {
1719 None => None,
1720 Some(edge) => {
1721 self.next = edge.next[k];
1722 Some((this_index, edge))
1723 }
1724 }
1725 }
1726}
1727
1728impl<'a, N, E, Ty, Ix> visit::IntoEdges for &'a Graph<N, E, Ty, Ix>
1729where
1730 Ty: EdgeType,
1731 Ix: IndexType,
1732{
1733 type Edges = Edges<'a, E, Ty, Ix>;
1734 fn edges(self, a: Self::NodeId) -> Self::Edges {
1735 self.edges(a)
1736 }
1737}
1738
1739impl<'a, N, E, Ty, Ix> visit::IntoEdgesDirected for &'a Graph<N, E, Ty, Ix>
1740where
1741 Ty: EdgeType,
1742 Ix: IndexType,
1743{
1744 type EdgesDirected = Edges<'a, E, Ty, Ix>;
1745 fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
1746 self.edges_directed(a, dir)
1747 }
1748}
1749
1750#[derive(Debug)]
1752pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1753where
1754 Ty: EdgeType,
1755 Ix: IndexType,
1756{
1757 skip_start: NodeIndex<Ix>,
1759 edges: &'a [Edge<E, Ix>],
1760
1761 next: [EdgeIndex<Ix>; 2],
1763
1764 direction: Direction,
1767 ty: PhantomData<Ty>,
1768}
1769
1770impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1771where
1772 Ty: EdgeType,
1773 Ix: IndexType,
1774{
1775 type Item = EdgeReference<'a, E, Ix>;
1776
1777 fn next(&mut self) -> Option<Self::Item> {
1778 let (iterate_over, reverse) = if Ty::is_directed() {
1788 (Some(self.direction), None)
1789 } else {
1790 (None, Some(self.direction.opposite()))
1791 };
1792
1793 if iterate_over.unwrap_or(Outgoing) == Outgoing {
1794 let i = self.next[0].index();
1795 if let Some(Edge { node, weight, next }) = self.edges.get(i) {
1796 self.next[0] = next[0];
1797 return Some(EdgeReference {
1798 index: edge_index(i),
1799 node: if reverse == Some(Outgoing) {
1800 swap_pair(*node)
1801 } else {
1802 *node
1803 },
1804 weight,
1805 });
1806 }
1807 }
1808
1809 if iterate_over.unwrap_or(Incoming) == Incoming {
1810 while let Some(Edge { node, weight, next }) = self.edges.get(self.next[1].index()) {
1811 let edge_index = self.next[1];
1812 self.next[1] = next[1];
1813 if iterate_over.is_none() && node[0] == self.skip_start {
1816 continue;
1817 }
1818
1819 return Some(EdgeReference {
1820 index: edge_index,
1821 node: if reverse == Some(Incoming) {
1822 swap_pair(*node)
1823 } else {
1824 *node
1825 },
1826 weight,
1827 });
1828 }
1829 }
1830
1831 None
1832 }
1833}
1834
1835#[derive(Debug, Clone)]
1837pub struct EdgesConnecting<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1838where
1839 Ty: EdgeType,
1840 Ix: IndexType,
1841{
1842 target_node: NodeIndex<Ix>,
1843 edges: Edges<'a, E, Ty, Ix>,
1844 ty: PhantomData<Ty>,
1845}
1846
1847impl<'a, E, Ty, Ix> Iterator for EdgesConnecting<'a, E, Ty, Ix>
1848where
1849 Ty: EdgeType,
1850 Ix: IndexType,
1851{
1852 type Item = EdgeReference<'a, E, Ix>;
1853
1854 fn next(&mut self) -> Option<EdgeReference<'a, E, Ix>> {
1855 let target_node = self.target_node;
1856 self.edges
1857 .by_ref()
1858 .find(|&edge| edge.node[1] == target_node)
1859 }
1860 fn size_hint(&self) -> (usize, Option<usize>) {
1861 let (_, upper) = self.edges.size_hint();
1862 (0, upper)
1863 }
1864}
1865
1866fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1867 x.swap(0, 1);
1868 x
1869}
1870
1871impl<E, Ty, Ix> Clone for Edges<'_, E, Ty, Ix>
1872where
1873 Ix: IndexType,
1874 Ty: EdgeType,
1875{
1876 fn clone(&self) -> Self {
1877 Edges {
1878 skip_start: self.skip_start,
1879 edges: self.edges,
1880 next: self.next,
1881 direction: self.direction,
1882 ty: self.ty,
1883 }
1884 }
1885}
1886
1887pub struct NodeWeights<'a, N: 'a, Ix: IndexType = DefaultIx> {
1889 nodes: ::core::slice::Iter<'a, Node<N, Ix>>,
1890}
1891impl<'a, N, Ix> Iterator for NodeWeights<'a, N, Ix>
1892where
1893 Ix: IndexType,
1894{
1895 type Item = &'a N;
1896
1897 fn next(&mut self) -> Option<&'a N> {
1898 self.nodes.next().map(|node| &node.weight)
1899 }
1900
1901 fn size_hint(&self) -> (usize, Option<usize>) {
1902 self.nodes.size_hint()
1903 }
1904}
1905#[derive(Debug)]
1907pub struct NodeWeightsMut<'a, N: 'a, Ix: IndexType = DefaultIx> {
1908 nodes: ::core::slice::IterMut<'a, Node<N, Ix>>, }
1910
1911impl<'a, N, Ix> Iterator for NodeWeightsMut<'a, N, Ix>
1912where
1913 Ix: IndexType,
1914{
1915 type Item = &'a mut N;
1916
1917 fn next(&mut self) -> Option<&'a mut N> {
1918 self.nodes.next().map(|node| &mut node.weight)
1919 }
1920
1921 fn size_hint(&self) -> (usize, Option<usize>) {
1922 self.nodes.size_hint()
1923 }
1924}
1925
1926pub struct EdgeWeights<'a, E: 'a, Ix: IndexType = DefaultIx> {
1928 edges: ::core::slice::Iter<'a, Edge<E, Ix>>,
1929}
1930
1931impl<'a, E, Ix> Iterator for EdgeWeights<'a, E, Ix>
1932where
1933 Ix: IndexType,
1934{
1935 type Item = &'a E;
1936
1937 fn next(&mut self) -> Option<&'a E> {
1938 self.edges.next().map(|edge| &edge.weight)
1939 }
1940
1941 fn size_hint(&self) -> (usize, Option<usize>) {
1942 self.edges.size_hint()
1943 }
1944}
1945
1946#[derive(Debug)]
1948pub struct EdgeWeightsMut<'a, E: 'a, Ix: IndexType = DefaultIx> {
1949 edges: ::core::slice::IterMut<'a, Edge<E, Ix>>, }
1951
1952impl<'a, E, Ix> Iterator for EdgeWeightsMut<'a, E, Ix>
1953where
1954 Ix: IndexType,
1955{
1956 type Item = &'a mut E;
1957
1958 fn next(&mut self) -> Option<&'a mut E> {
1959 self.edges.next().map(|edge| &mut edge.weight)
1960 }
1961
1962 fn size_hint(&self) -> (usize, Option<usize>) {
1963 self.edges.size_hint()
1964 }
1965}
1966
1967impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for Graph<N, E, Ty, Ix>
1971where
1972 Ty: EdgeType,
1973 Ix: IndexType,
1974{
1975 type Output = N;
1976 fn index(&self, index: NodeIndex<Ix>) -> &N {
1977 &self.nodes[index.index()].weight
1978 }
1979}
1980
1981impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for Graph<N, E, Ty, Ix>
1985where
1986 Ty: EdgeType,
1987 Ix: IndexType,
1988{
1989 fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1990 &mut self.nodes[index.index()].weight
1991 }
1992}
1993
1994impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix>
1998where
1999 Ty: EdgeType,
2000 Ix: IndexType,
2001{
2002 type Output = E;
2003 fn index(&self, index: EdgeIndex<Ix>) -> &E {
2004 &self.edges[index.index()].weight
2005 }
2006}
2007
2008impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix>
2012where
2013 Ty: EdgeType,
2014 Ix: IndexType,
2015{
2016 fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
2017 &mut self.edges[index.index()].weight
2018 }
2019}
2020
2021impl<N, E, Ty, Ix> Default for Graph<N, E, Ty, Ix>
2023where
2024 Ty: EdgeType,
2025 Ix: IndexType,
2026{
2027 fn default() -> Self {
2028 Self::with_capacity(0, 0)
2029 }
2030}
2031
2032pub trait GraphIndex: Copy {
2034 #[doc(hidden)]
2035 fn index(&self) -> usize;
2036 #[doc(hidden)]
2037 fn is_node_index() -> bool;
2038}
2039
2040impl<Ix: IndexType> GraphIndex for NodeIndex<Ix> {
2041 #[inline]
2042 #[doc(hidden)]
2043 fn index(&self) -> usize {
2044 NodeIndex::index(*self)
2045 }
2046 #[inline]
2047 #[doc(hidden)]
2048 fn is_node_index() -> bool {
2049 true
2050 }
2051}
2052
2053impl<Ix: IndexType> GraphIndex for EdgeIndex<Ix> {
2054 #[inline]
2055 #[doc(hidden)]
2056 fn index(&self) -> usize {
2057 EdgeIndex::index(*self)
2058 }
2059 #[inline]
2060 #[doc(hidden)]
2061 fn is_node_index() -> bool {
2062 false
2063 }
2064}
2065
2066pub struct WalkNeighbors<Ix> {
2102 skip_start: NodeIndex<Ix>,
2103 next: [EdgeIndex<Ix>; 2],
2104}
2105
2106impl<Ix> Clone for WalkNeighbors<Ix>
2107where
2108 Ix: IndexType,
2109{
2110 fn clone(&self) -> Self {
2111 WalkNeighbors {
2112 skip_start: self.skip_start,
2113 next: self.next,
2114 }
2115 }
2116}
2117
2118impl<Ix: IndexType> WalkNeighbors<Ix> {
2119 pub fn next<N, E, Ty: EdgeType>(
2126 &mut self,
2127 g: &Graph<N, E, Ty, Ix>,
2128 ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
2129 match g.edges.get(self.next[0].index()) {
2131 None => {}
2132 Some(edge) => {
2133 let ed = self.next[0];
2134 self.next[0] = edge.next[0];
2135 return Some((ed, edge.node[1]));
2136 }
2137 }
2138 while let Some(edge) = g.edges.get(self.next[1].index()) {
2143 let ed = self.next[1];
2144 self.next[1] = edge.next[1];
2145 if edge.node[0] != self.skip_start {
2146 return Some((ed, edge.node[0]));
2147 }
2148 }
2149 None
2150 }
2151
2152 pub fn next_node<N, E, Ty: EdgeType>(
2153 &mut self,
2154 g: &Graph<N, E, Ty, Ix>,
2155 ) -> Option<NodeIndex<Ix>> {
2156 self.next(g).map(|t| t.1)
2157 }
2158
2159 pub fn next_edge<N, E, Ty: EdgeType>(
2160 &mut self,
2161 g: &Graph<N, E, Ty, Ix>,
2162 ) -> Option<EdgeIndex<Ix>> {
2163 self.next(g).map(|t| t.0)
2164 }
2165}
2166
2167#[derive(Clone, Debug)]
2169pub struct NodeIndices<Ix = DefaultIx> {
2170 r: Range<usize>,
2171 ty: PhantomData<fn() -> Ix>,
2172}
2173
2174impl<Ix: IndexType> Iterator for NodeIndices<Ix> {
2175 type Item = NodeIndex<Ix>;
2176
2177 fn next(&mut self) -> Option<Self::Item> {
2178 self.r.next().map(node_index)
2179 }
2180
2181 fn size_hint(&self) -> (usize, Option<usize>) {
2182 self.r.size_hint()
2183 }
2184}
2185
2186impl<Ix: IndexType> DoubleEndedIterator for NodeIndices<Ix> {
2187 fn next_back(&mut self) -> Option<Self::Item> {
2188 self.r.next_back().map(node_index)
2189 }
2190}
2191
2192impl<Ix: IndexType> ExactSizeIterator for NodeIndices<Ix> {}
2193
2194#[derive(Clone, Debug)]
2196pub struct EdgeIndices<Ix = DefaultIx> {
2197 r: Range<usize>,
2198 ty: PhantomData<fn() -> Ix>,
2199}
2200
2201impl<Ix: IndexType> Iterator for EdgeIndices<Ix> {
2202 type Item = EdgeIndex<Ix>;
2203
2204 fn next(&mut self) -> Option<Self::Item> {
2205 self.r.next().map(edge_index)
2206 }
2207
2208 fn size_hint(&self) -> (usize, Option<usize>) {
2209 self.r.size_hint()
2210 }
2211}
2212
2213impl<Ix: IndexType> DoubleEndedIterator for EdgeIndices<Ix> {
2214 fn next_back(&mut self) -> Option<Self::Item> {
2215 self.r.next_back().map(edge_index)
2216 }
2217}
2218
2219impl<Ix: IndexType> ExactSizeIterator for EdgeIndices<Ix> {}
2220
2221#[derive(Debug)]
2223pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
2224 index: EdgeIndex<Ix>,
2225 node: [NodeIndex<Ix>; 2],
2226 weight: &'a E,
2227}
2228
2229impl<E, Ix: IndexType> Clone for EdgeReference<'_, E, Ix> {
2230 fn clone(&self) -> Self {
2231 *self
2232 }
2233}
2234
2235impl<E, Ix: IndexType> Copy for EdgeReference<'_, E, Ix> {}
2236
2237impl<E, Ix: IndexType> PartialEq for EdgeReference<'_, E, Ix>
2238where
2239 E: PartialEq,
2240{
2241 fn eq(&self, rhs: &Self) -> bool {
2242 self.index == rhs.index && self.weight == rhs.weight
2243 }
2244}
2245
2246impl<N, E, Ty, Ix> visit::GraphBase for Graph<N, E, Ty, Ix>
2247where
2248 Ix: IndexType,
2249{
2250 type NodeId = NodeIndex<Ix>;
2251 type EdgeId = EdgeIndex<Ix>;
2252}
2253
2254impl<N, E, Ty, Ix> visit::Visitable for Graph<N, E, Ty, Ix>
2255where
2256 Ty: EdgeType,
2257 Ix: IndexType,
2258{
2259 type Map = FixedBitSet;
2260 fn visit_map(&self) -> FixedBitSet {
2261 FixedBitSet::with_capacity(self.node_count())
2262 }
2263
2264 fn reset_map(&self, map: &mut Self::Map) {
2265 map.clear();
2266 map.grow(self.node_count());
2267 }
2268}
2269
2270impl<N, E, Ty, Ix> visit::GraphProp for Graph<N, E, Ty, Ix>
2271where
2272 Ty: EdgeType,
2273 Ix: IndexType,
2274{
2275 type EdgeType = Ty;
2276}
2277
2278impl<'a, N, E: 'a, Ty, Ix> visit::IntoNodeIdentifiers for &'a Graph<N, E, Ty, Ix>
2279where
2280 Ty: EdgeType,
2281 Ix: IndexType,
2282{
2283 type NodeIdentifiers = NodeIndices<Ix>;
2284 fn node_identifiers(self) -> NodeIndices<Ix> {
2285 Graph::node_indices(self)
2286 }
2287}
2288
2289impl<N, E, Ty, Ix> visit::NodeCount for Graph<N, E, Ty, Ix>
2290where
2291 Ty: EdgeType,
2292 Ix: IndexType,
2293{
2294 fn node_count(&self) -> usize {
2295 self.node_count()
2296 }
2297}
2298
2299impl<N, E, Ty, Ix> visit::NodeIndexable for Graph<N, E, Ty, Ix>
2300where
2301 Ty: EdgeType,
2302 Ix: IndexType,
2303{
2304 #[inline]
2305 fn node_bound(&self) -> usize {
2306 self.node_count()
2307 }
2308 #[inline]
2309 fn to_index(&self, ix: NodeIndex<Ix>) -> usize {
2310 ix.index()
2311 }
2312 #[inline]
2313 fn from_index(&self, ix: usize) -> Self::NodeId {
2314 NodeIndex::new(ix)
2315 }
2316}
2317
2318impl<N, E, Ty, Ix> visit::NodeCompactIndexable for Graph<N, E, Ty, Ix>
2319where
2320 Ty: EdgeType,
2321 Ix: IndexType,
2322{
2323}
2324
2325impl<'a, N, E: 'a, Ty, Ix> visit::IntoNeighbors for &'a Graph<N, E, Ty, Ix>
2326where
2327 Ty: EdgeType,
2328 Ix: IndexType,
2329{
2330 type Neighbors = Neighbors<'a, E, Ix>;
2331 fn neighbors(self, n: NodeIndex<Ix>) -> Neighbors<'a, E, Ix> {
2332 Graph::neighbors(self, n)
2333 }
2334}
2335
2336impl<'a, N, E: 'a, Ty, Ix> visit::IntoNeighborsDirected for &'a Graph<N, E, Ty, Ix>
2337where
2338 Ty: EdgeType,
2339 Ix: IndexType,
2340{
2341 type NeighborsDirected = Neighbors<'a, E, Ix>;
2342 fn neighbors_directed(self, n: NodeIndex<Ix>, d: Direction) -> Neighbors<'a, E, Ix> {
2343 Graph::neighbors_directed(self, n, d)
2344 }
2345}
2346
2347impl<'a, N: 'a, E: 'a, Ty, Ix> visit::IntoEdgeReferences for &'a Graph<N, E, Ty, Ix>
2348where
2349 Ty: EdgeType,
2350 Ix: IndexType,
2351{
2352 type EdgeRef = EdgeReference<'a, E, Ix>;
2353 type EdgeReferences = EdgeReferences<'a, E, Ix>;
2354 fn edge_references(self) -> Self::EdgeReferences {
2355 (*self).edge_references()
2356 }
2357}
2358
2359impl<N, E, Ty, Ix> visit::EdgeCount for Graph<N, E, Ty, Ix>
2360where
2361 Ty: EdgeType,
2362 Ix: IndexType,
2363{
2364 #[inline]
2365 fn edge_count(&self) -> usize {
2366 self.edge_count()
2367 }
2368}
2369
2370impl<'a, N, E, Ty, Ix> visit::IntoNodeReferences for &'a Graph<N, E, Ty, Ix>
2371where
2372 Ty: EdgeType,
2373 Ix: IndexType,
2374{
2375 type NodeRef = (NodeIndex<Ix>, &'a N);
2376 type NodeReferences = NodeReferences<'a, N, Ix>;
2377 fn node_references(self) -> Self::NodeReferences {
2378 NodeReferences {
2379 iter: self.nodes.iter().enumerate(),
2380 }
2381 }
2382}
2383
2384#[derive(Debug, Clone)]
2386pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
2387 iter: iter::Enumerate<slice::Iter<'a, Node<N, Ix>>>,
2388}
2389
2390impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
2391where
2392 Ix: IndexType,
2393{
2394 type Item = (NodeIndex<Ix>, &'a N);
2395
2396 fn next(&mut self) -> Option<Self::Item> {
2397 self.iter
2398 .next()
2399 .map(|(i, node)| (node_index(i), &node.weight))
2400 }
2401
2402 fn size_hint(&self) -> (usize, Option<usize>) {
2403 self.iter.size_hint()
2404 }
2405}
2406
2407impl<N, Ix> DoubleEndedIterator for NodeReferences<'_, N, Ix>
2408where
2409 Ix: IndexType,
2410{
2411 fn next_back(&mut self) -> Option<Self::Item> {
2412 self.iter
2413 .next_back()
2414 .map(|(i, node)| (node_index(i), &node.weight))
2415 }
2416}
2417
2418impl<N, Ix> ExactSizeIterator for NodeReferences<'_, N, Ix> where Ix: IndexType {}
2419
2420impl<'a, Ix, E> EdgeReference<'a, E, Ix>
2421where
2422 Ix: IndexType,
2423{
2424 pub fn weight(&self) -> &'a E {
2429 self.weight
2430 }
2431}
2432
2433impl<Ix, E> visit::EdgeRef for EdgeReference<'_, E, Ix>
2434where
2435 Ix: IndexType,
2436{
2437 type NodeId = NodeIndex<Ix>;
2438 type EdgeId = EdgeIndex<Ix>;
2439 type Weight = E;
2440
2441 fn source(&self) -> Self::NodeId {
2442 self.node[0]
2443 }
2444 fn target(&self) -> Self::NodeId {
2445 self.node[1]
2446 }
2447 fn weight(&self) -> &E {
2448 self.weight
2449 }
2450 fn id(&self) -> Self::EdgeId {
2451 self.index
2452 }
2453}
2454
2455#[derive(Debug, Clone)]
2457pub struct EdgeReferences<'a, E: 'a, Ix: IndexType = DefaultIx> {
2458 iter: iter::Enumerate<slice::Iter<'a, Edge<E, Ix>>>,
2459}
2460
2461impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
2462where
2463 Ix: IndexType,
2464{
2465 type Item = EdgeReference<'a, E, Ix>;
2466
2467 fn next(&mut self) -> Option<Self::Item> {
2468 self.iter.next().map(|(i, edge)| EdgeReference {
2469 index: edge_index(i),
2470 node: edge.node,
2471 weight: &edge.weight,
2472 })
2473 }
2474
2475 fn size_hint(&self) -> (usize, Option<usize>) {
2476 self.iter.size_hint()
2477 }
2478}
2479
2480impl<E, Ix> DoubleEndedIterator for EdgeReferences<'_, E, Ix>
2481where
2482 Ix: IndexType,
2483{
2484 fn next_back(&mut self) -> Option<Self::Item> {
2485 self.iter.next_back().map(|(i, edge)| EdgeReference {
2486 index: edge_index(i),
2487 node: edge.node,
2488 weight: &edge.weight,
2489 })
2490 }
2491}
2492
2493impl<E, Ix> ExactSizeIterator for EdgeReferences<'_, E, Ix> where Ix: IndexType {}
2494
2495impl<N, E, Ty, Ix> visit::EdgeIndexable for Graph<N, E, Ty, Ix>
2496where
2497 Ty: EdgeType,
2498 Ix: IndexType,
2499{
2500 fn edge_bound(&self) -> usize {
2501 self.edge_count()
2502 }
2503
2504 fn to_index(&self, ix: EdgeIndex<Ix>) -> usize {
2505 ix.index()
2506 }
2507
2508 fn from_index(&self, ix: usize) -> Self::EdgeId {
2509 EdgeIndex::new(ix)
2510 }
2511}
2512
2513mod frozen;
2514#[cfg(feature = "stable_graph")]
2515pub mod stable_graph;
2516
2517pub struct Frozen<'a, G: 'a>(&'a mut G);