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> {
392 nodes: Vec<Node<N, Ix>>,
393 edges: Vec<Edge<E, Ix>>,
394 ty: PhantomData<Ty>,
395}
396
397pub type DiGraph<N, E, Ix = DefaultIx> = Graph<N, E, Directed, Ix>;
402
403pub type UnGraph<N, E, Ix = DefaultIx> = Graph<N, E, Undirected, Ix>;
408
409impl<N, E, Ty, Ix: IndexType> Clone for Graph<N, E, Ty, Ix>
411where
412 N: Clone,
413 E: Clone,
414{
415 fn clone(&self) -> Self {
416 Graph {
417 nodes: self.nodes.clone(),
418 edges: self.edges.clone(),
419 ty: self.ty,
420 }
421 }
422
423 fn clone_from(&mut self, rhs: &Self) {
424 self.nodes.clone_from(&rhs.nodes);
425 self.edges.clone_from(&rhs.edges);
426 self.ty = rhs.ty;
427 }
428}
429
430impl<N, E, Ty, Ix> fmt::Debug for Graph<N, E, Ty, Ix>
431where
432 N: fmt::Debug,
433 E: fmt::Debug,
434 Ty: EdgeType,
435 Ix: IndexType,
436{
437 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
438 let etype = if self.is_directed() {
439 "Directed"
440 } else {
441 "Undirected"
442 };
443 let mut fmt_struct = f.debug_struct("Graph");
444 fmt_struct.field("Ty", &etype);
445 fmt_struct.field("node_count", &self.node_count());
446 fmt_struct.field("edge_count", &self.edge_count());
447 if self.edge_count() > 0 {
448 fmt_struct.field(
449 "edges",
450 &self
451 .edges
452 .iter()
453 .map(|e| NoPretty((e.source().index(), e.target().index())))
454 .format(", "),
455 );
456 }
457 if size_of::<N>() != 0 {
459 fmt_struct.field(
460 "node weights",
461 &DebugMap(|| self.nodes.iter().map(|n| &n.weight).enumerate()),
462 );
463 }
464 if size_of::<E>() != 0 {
465 fmt_struct.field(
466 "edge weights",
467 &DebugMap(|| self.edges.iter().map(|n| &n.weight).enumerate()),
468 );
469 }
470 fmt_struct.finish()
471 }
472}
473
474enum Pair<T> {
475 Both(T, T),
476 One(T),
477 None,
478}
479
480use core::cmp::max;
481
482fn index_twice<T>(slc: &mut [T], a: usize, b: usize) -> Pair<&mut T> {
484 if max(a, b) >= slc.len() {
485 Pair::None
486 } else if a == b {
487 Pair::One(&mut slc[max(a, b)])
488 } else {
489 unsafe {
491 let ptr = slc.as_mut_ptr();
492 let ar = &mut *ptr.add(a);
493 let br = &mut *ptr.add(b);
494 Pair::Both(ar, br)
495 }
496 }
497}
498
499impl<N, E> Graph<N, E, Directed> {
500 pub fn new() -> Self {
505 Graph {
506 nodes: Vec::new(),
507 edges: Vec::new(),
508 ty: PhantomData,
509 }
510 }
511}
512
513impl<N, E> Graph<N, E, Undirected> {
514 pub fn new_undirected() -> Self {
519 Graph {
520 nodes: Vec::new(),
521 edges: Vec::new(),
522 ty: PhantomData,
523 }
524 }
525}
526
527impl<N, E, Ty, Ix> Graph<N, E, Ty, Ix>
528where
529 Ty: EdgeType,
530 Ix: IndexType,
531{
532 pub fn with_capacity(nodes: usize, edges: usize) -> Self {
534 Graph {
535 nodes: Vec::with_capacity(nodes),
536 edges: Vec::with_capacity(edges),
537 ty: PhantomData,
538 }
539 }
540
541 pub fn node_count(&self) -> usize {
545 self.nodes.len()
546 }
547
548 pub fn edge_count(&self) -> usize {
552 self.edges.len()
553 }
554
555 #[inline]
557 pub fn is_directed(&self) -> bool {
558 Ty::is_directed()
559 }
560
561 #[track_caller]
570 pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
571 self.try_add_node(weight).unwrap()
572 }
573
574 pub fn try_add_node(&mut self, weight: N) -> Result<NodeIndex<Ix>, GraphError> {
582 let node = Node {
583 weight,
584 next: [EdgeIndex::end(), EdgeIndex::end()],
585 };
586 let node_idx = NodeIndex::new(self.nodes.len());
587 if <Ix as IndexType>::max().index() == !0 || NodeIndex::end() != node_idx {
589 self.nodes.push(node);
590 Ok(node_idx)
591 } else {
592 Err(GraphError::NodeIxLimit)
593 }
594 }
595
596 pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
601 self.nodes.get(a.index()).map(|n| &n.weight)
602 }
603
604 pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
609 self.nodes.get_mut(a.index()).map(|n| &mut n.weight)
610 }
611
612 #[track_caller]
626 pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
627 let res = self.try_add_edge(a, b, weight);
628 if res == Err(GraphError::NodeOutBounds) {
629 panic!("Graph::add_edge: node indices out of bounds");
630 }
631 res.unwrap()
632 }
633
634 pub fn try_add_edge(
649 &mut self,
650 a: NodeIndex<Ix>,
651 b: NodeIndex<Ix>,
652 weight: E,
653 ) -> Result<EdgeIndex<Ix>, GraphError> {
654 let edge_idx = EdgeIndex::new(self.edges.len());
655 if !(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx) {
656 return Err(GraphError::EdgeIxLimit);
657 }
658
659 let mut edge = Edge {
660 weight,
661 node: [a, b],
662 next: [EdgeIndex::end(); 2],
663 };
664 match index_twice(&mut self.nodes, a.index(), b.index()) {
665 Pair::None => return Err(GraphError::NodeOutBounds),
666 Pair::One(an) => {
667 edge.next = an.next;
668 an.next[0] = edge_idx;
669 an.next[1] = edge_idx;
670 }
671 Pair::Both(an, bn) => {
672 edge.next = [an.next[0], bn.next[1]];
674 an.next[0] = edge_idx;
675 bn.next[1] = edge_idx;
676 }
677 }
678 self.edges.push(edge);
679 Ok(edge_idx)
680 }
681
682 #[track_caller]
693 pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
694 self.try_update_edge(a, b, weight).unwrap()
695 }
696
697 pub fn try_update_edge(
710 &mut self,
711 a: NodeIndex<Ix>,
712 b: NodeIndex<Ix>,
713 weight: E,
714 ) -> Result<EdgeIndex<Ix>, GraphError> {
715 if let Some(ix) = self.find_edge(a, b) {
716 if let Some(ed) = self.edge_weight_mut(ix) {
717 *ed = weight;
718 return Ok(ix);
719 }
720 }
721 self.try_add_edge(a, b, weight)
722 }
723
724 pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
729 self.edges.get(e.index()).map(|ed| &ed.weight)
730 }
731
732 pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
737 self.edges.get_mut(e.index()).map(|ed| &mut ed.weight)
738 }
739
740 pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)> {
744 self.edges
745 .get(e.index())
746 .map(|ed| (ed.source(), ed.target()))
747 }
748
749 pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N> {
762 self.nodes.get(a.index())?;
763 for d in &DIRECTIONS {
764 let k = d.index();
765
766 loop {
768 let next = self.nodes[a.index()].next[k];
769 if next == EdgeIndex::end() {
770 break;
771 }
772 let ret = self.remove_edge(next);
773 debug_assert!(ret.is_some());
774 let _ = ret;
775 }
776 }
777
778 let node = self.nodes.swap_remove(a.index());
782
783 let swap_edges = match self.nodes.get(a.index()) {
786 None => return Some(node.weight),
787 Some(ed) => ed.next,
788 };
789
790 let old_index = NodeIndex::new(self.nodes.len());
792 let new_index = a;
793
794 for &d in &DIRECTIONS {
796 let k = d.index();
797 let mut edges = edges_walker_mut(&mut self.edges, swap_edges[k], d);
798 while let Some(curedge) = edges.next_edge() {
799 debug_assert!(curedge.node[k] == old_index);
800 curedge.node[k] = new_index;
801 }
802 }
803 Some(node.weight)
804 }
805
806 fn change_edge_links(
809 &mut self,
810 edge_node: [NodeIndex<Ix>; 2],
811 e: EdgeIndex<Ix>,
812 edge_next: [EdgeIndex<Ix>; 2],
813 ) {
814 for &d in &DIRECTIONS {
815 let k = d.index();
816 let node = match self.nodes.get_mut(edge_node[k].index()) {
817 Some(r) => r,
818 None => {
819 debug_assert!(
820 false,
821 "Edge's endpoint dir={:?} index={:?} not found",
822 d, edge_node[k]
823 );
824 return;
825 }
826 };
827 let fst = node.next[k];
828 if fst == e {
829 node.next[k] = edge_next[k];
831 } else {
832 let mut edges = edges_walker_mut(&mut self.edges, fst, d);
833 while let Some(curedge) = edges.next_edge() {
834 if curedge.next[k] == e {
835 curedge.next[k] = edge_next[k];
836 break; }
838 }
839 }
840 }
841 }
842
843 pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
851 let (edge_node, edge_next) = match self.edges.get(e.index()) {
855 None => return None,
856 Some(x) => (x.node, x.next),
857 };
858 self.change_edge_links(edge_node, e, edge_next);
861 self.remove_edge_adjust_indices(e)
862 }
863
864 fn remove_edge_adjust_indices(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
865 let edge = self.edges.swap_remove(e.index());
869 let swap = match self.edges.get(e.index()) {
870 None => return Some(edge.weight),
872 Some(ed) => ed.node,
873 };
874 let swapped_e = EdgeIndex::new(self.edges.len());
875
876 self.change_edge_links(swap, swapped_e, [e, e]);
879 Some(edge.weight)
880 }
881
882 pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
895 self.neighbors_directed(a, Outgoing)
896 }
897
898 pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix> {
918 let mut iter = self.neighbors_undirected(a);
919 if self.is_directed() {
920 let k = dir.index();
921 iter.next[1 - k] = EdgeIndex::end();
922 iter.skip_start = NodeIndex::end();
923 }
924 iter
925 }
926
927 pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
942 Neighbors {
943 skip_start: a,
944 edges: &self.edges,
945 next: match self.nodes.get(a.index()) {
946 None => [EdgeIndex::end(), EdgeIndex::end()],
947 Some(n) => n.next,
948 },
949 }
950 }
951
952 pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
960 self.edges_directed(a, Outgoing)
961 }
962
963 pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix> {
975 Edges {
976 skip_start: a,
977 edges: &self.edges,
978 direction: dir,
979 next: match self.nodes.get(a.index()) {
980 None => [EdgeIndex::end(), EdgeIndex::end()],
981 Some(n) => n.next,
982 },
983 ty: PhantomData,
984 }
985 }
986
987 pub fn edges_connecting(
994 &self,
995 a: NodeIndex<Ix>,
996 b: NodeIndex<Ix>,
997 ) -> EdgesConnecting<E, Ty, Ix> {
998 EdgesConnecting {
999 target_node: b,
1000 edges: self.edges_directed(a, Direction::Outgoing),
1001 ty: PhantomData,
1002 }
1003 }
1004
1005 pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
1010 self.find_edge(a, b).is_some()
1011 }
1012
1013 pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>> {
1018 if !self.is_directed() {
1019 self.find_edge_undirected(a, b).map(|(ix, _)| ix)
1020 } else {
1021 match self.nodes.get(a.index()) {
1022 None => None,
1023 Some(node) => self.find_edge_directed_from_node(node, b),
1024 }
1025 }
1026 }
1027
1028 fn find_edge_directed_from_node(
1029 &self,
1030 node: &Node<N, Ix>,
1031 b: NodeIndex<Ix>,
1032 ) -> Option<EdgeIndex<Ix>> {
1033 let mut edix = node.next[0];
1034 while let Some(edge) = self.edges.get(edix.index()) {
1035 if edge.node[1] == b {
1036 return Some(edix);
1037 }
1038 edix = edge.next[0];
1039 }
1040 None
1041 }
1042
1043 pub fn find_edge_undirected(
1051 &self,
1052 a: NodeIndex<Ix>,
1053 b: NodeIndex<Ix>,
1054 ) -> Option<(EdgeIndex<Ix>, Direction)> {
1055 match self.nodes.get(a.index()) {
1056 None => None,
1057 Some(node) => self.find_edge_undirected_from_node(node, b),
1058 }
1059 }
1060
1061 fn find_edge_undirected_from_node(
1062 &self,
1063 node: &Node<N, Ix>,
1064 b: NodeIndex<Ix>,
1065 ) -> Option<(EdgeIndex<Ix>, Direction)> {
1066 for &d in &DIRECTIONS {
1067 let k = d.index();
1068 let mut edix = node.next[k];
1069 while let Some(edge) = self.edges.get(edix.index()) {
1070 if edge.node[1 - k] == b {
1071 return Some((edix, d));
1072 }
1073 edix = edge.next[k];
1074 }
1075 }
1076 None
1077 }
1078
1079 pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix> {
1091 Externals {
1092 iter: self.nodes.iter().enumerate(),
1093 dir,
1094 ty: PhantomData,
1095 }
1096 }
1097
1098 pub fn node_indices(&self) -> NodeIndices<Ix> {
1111 NodeIndices {
1112 r: 0..self.node_count(),
1113 ty: PhantomData,
1114 }
1115 }
1116
1117 pub fn node_weights_mut(&mut self) -> NodeWeightsMut<N, Ix> {
1122 NodeWeightsMut {
1123 nodes: self.nodes.iter_mut(),
1124 }
1125 }
1126
1127 pub fn node_weights(&self) -> NodeWeights<N, Ix> {
1132 NodeWeights {
1133 nodes: self.nodes.iter(),
1134 }
1135 }
1136
1137 pub fn edge_indices(&self) -> EdgeIndices<Ix> {
1139 EdgeIndices {
1140 r: 0..self.edge_count(),
1141 ty: PhantomData,
1142 }
1143 }
1144
1145 pub fn edge_references(&self) -> EdgeReferences<E, Ix> {
1149 EdgeReferences {
1150 iter: self.edges.iter().enumerate(),
1151 }
1152 }
1153
1154 pub fn edge_weights(&self) -> EdgeWeights<E, Ix> {
1159 EdgeWeights {
1160 edges: self.edges.iter(),
1161 }
1162 }
1163 pub fn edge_weights_mut(&mut self) -> EdgeWeightsMut<E, Ix> {
1168 EdgeWeightsMut {
1169 edges: self.edges.iter_mut(),
1170 }
1171 }
1172
1173 pub fn raw_nodes(&self) -> &[Node<N, Ix>] {
1178 &self.nodes
1179 }
1180
1181 pub fn raw_edges(&self) -> &[Edge<E, Ix>] {
1183 &self.edges
1184 }
1185
1186 #[allow(clippy::type_complexity)]
1187 pub fn into_nodes_edges(self) -> (Vec<Node<N, Ix>>, Vec<Edge<E, Ix>>) {
1189 (self.nodes, self.edges)
1190 }
1191
1192 pub fn first_edge(&self, a: NodeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>> {
1194 match self.nodes.get(a.index()) {
1195 None => None,
1196 Some(node) => {
1197 let edix = node.next[dir.index()];
1198 if edix == EdgeIndex::end() {
1199 None
1200 } else {
1201 Some(edix)
1202 }
1203 }
1204 }
1205 }
1206
1207 pub fn next_edge(&self, e: EdgeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>> {
1209 match self.edges.get(e.index()) {
1210 None => None,
1211 Some(node) => {
1212 let edix = node.next[dir.index()];
1213 if edix == EdgeIndex::end() {
1214 None
1215 } else {
1216 Some(edix)
1217 }
1218 }
1219 }
1220 }
1221
1222 #[track_caller]
1256 pub fn index_twice_mut<T, U>(
1257 &mut self,
1258 i: T,
1259 j: U,
1260 ) -> (
1261 &mut <Self as Index<T>>::Output,
1262 &mut <Self as Index<U>>::Output,
1263 )
1264 where
1265 Self: IndexMut<T> + IndexMut<U>,
1266 T: GraphIndex,
1267 U: GraphIndex,
1268 {
1269 assert!(T::is_node_index() != U::is_node_index() || i.index() != j.index());
1270
1271 unsafe {
1273 let self_mut = self as *mut _;
1274 (
1275 <Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
1276 <Self as IndexMut<U>>::index_mut(&mut *self_mut, j),
1277 )
1278 }
1279 }
1280
1281 pub fn reverse(&mut self) {
1283 for edge in &mut self.edges {
1287 edge.node.swap(0, 1);
1288 edge.next.swap(0, 1);
1289 }
1290 for node in &mut self.nodes {
1291 node.next.swap(0, 1);
1292 }
1293 }
1294
1295 pub fn clear(&mut self) {
1297 self.nodes.clear();
1298 self.edges.clear();
1299 }
1300
1301 pub fn clear_edges(&mut self) {
1303 self.edges.clear();
1304 for node in &mut self.nodes {
1305 node.next = [EdgeIndex::end(), EdgeIndex::end()];
1306 }
1307 }
1308
1309 pub fn capacity(&self) -> (usize, usize) {
1311 (self.nodes.capacity(), self.edges.capacity())
1312 }
1313
1314 #[track_caller]
1319 pub fn reserve_nodes(&mut self, additional: usize) {
1320 self.nodes.reserve(additional);
1321 }
1322
1323 #[track_caller]
1328 pub fn reserve_edges(&mut self, additional: usize) {
1329 self.edges.reserve(additional);
1330 }
1331
1332 #[track_caller]
1340 pub fn reserve_exact_nodes(&mut self, additional: usize) {
1341 self.nodes.reserve_exact(additional);
1342 }
1343
1344 #[track_caller]
1352 pub fn reserve_exact_edges(&mut self, additional: usize) {
1353 self.edges.reserve_exact(additional);
1354 }
1355
1356 pub fn shrink_to_fit_nodes(&mut self) {
1358 self.nodes.shrink_to_fit();
1359 }
1360
1361 pub fn shrink_to_fit_edges(&mut self) {
1363 self.edges.shrink_to_fit();
1364 }
1365
1366 pub fn shrink_to_fit(&mut self) {
1368 self.nodes.shrink_to_fit();
1369 self.edges.shrink_to_fit();
1370 }
1371
1372 pub fn retain_nodes<F>(&mut self, mut visit: F)
1380 where
1381 F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,
1382 {
1383 for index in self.node_indices().rev() {
1384 if !visit(Frozen(self), index) {
1385 let ret = self.remove_node(index);
1386 debug_assert!(ret.is_some());
1387 let _ = ret;
1388 }
1389 }
1390 }
1391
1392 pub fn retain_edges<F>(&mut self, mut visit: F)
1400 where
1401 F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,
1402 {
1403 for index in self.edge_indices().rev() {
1404 if !visit(Frozen(self), index) {
1405 let ret = self.remove_edge(index);
1406 debug_assert!(ret.is_some());
1407 let _ = ret;
1408 }
1409 }
1410 }
1411
1412 pub fn from_edges<I>(iterable: I) -> Self
1430 where
1431 I: IntoIterator,
1432 I::Item: IntoWeightedEdge<E>,
1433 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1434 N: Default,
1435 {
1436 let mut g = Self::with_capacity(0, 0);
1437 g.extend_with_edges(iterable);
1438 g
1439 }
1440
1441 pub fn extend_with_edges<I>(&mut self, iterable: I)
1449 where
1450 I: IntoIterator,
1451 I::Item: IntoWeightedEdge<E>,
1452 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1453 N: Default,
1454 {
1455 let iter = iterable.into_iter();
1456 let (low, _) = iter.size_hint();
1457 self.edges.reserve(low);
1458
1459 for elt in iter {
1460 let (source, target, weight) = elt.into_weighted_edge();
1461 let (source, target) = (source.into(), target.into());
1462 let nx = cmp::max(source, target);
1463 while nx.index() >= self.node_count() {
1464 self.add_node(N::default());
1465 }
1466 self.add_edge(source, target, weight);
1467 }
1468 }
1469
1470 pub fn map<'a, F, G, N2, E2>(
1476 &'a self,
1477 mut node_map: F,
1478 mut edge_map: G,
1479 ) -> Graph<N2, E2, Ty, Ix>
1480 where
1481 F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
1482 G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
1483 {
1484 let mut g = Graph::with_capacity(self.node_count(), self.edge_count());
1485 g.nodes.extend(enumerate(&self.nodes).map(|(i, node)| Node {
1486 weight: node_map(NodeIndex::new(i), &node.weight),
1487 next: node.next,
1488 }));
1489 g.edges.extend(enumerate(&self.edges).map(|(i, edge)| Edge {
1490 weight: edge_map(EdgeIndex::new(i), &edge.weight),
1491 next: edge.next,
1492 node: edge.node,
1493 }));
1494 g
1495 }
1496
1497 pub fn filter_map<'a, F, G, N2, E2>(
1510 &'a self,
1511 mut node_map: F,
1512 mut edge_map: G,
1513 ) -> Graph<N2, E2, Ty, Ix>
1514 where
1515 F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
1516 G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
1517 {
1518 let mut g = Graph::with_capacity(0, 0);
1519 let mut node_index_map = vec![NodeIndex::end(); self.node_count()];
1521 for (i, node) in enumerate(&self.nodes) {
1522 if let Some(nw) = node_map(NodeIndex::new(i), &node.weight) {
1523 node_index_map[i] = g.add_node(nw);
1524 }
1525 }
1526 for (i, edge) in enumerate(&self.edges) {
1527 let source = node_index_map[edge.source().index()];
1529 let target = node_index_map[edge.target().index()];
1530 if source != NodeIndex::end() && target != NodeIndex::end() {
1531 if let Some(ew) = edge_map(EdgeIndex::new(i), &edge.weight) {
1532 g.add_edge(source, target, ew);
1533 }
1534 }
1535 }
1536 g
1537 }
1538
1539 pub fn into_edge_type<NewTy>(self) -> Graph<N, E, NewTy, Ix>
1544 where
1545 NewTy: EdgeType,
1546 {
1547 Graph {
1548 nodes: self.nodes,
1549 edges: self.edges,
1550 ty: PhantomData,
1551 }
1552 }
1553
1554 #[cfg(feature = "serde-1")]
1558 fn link_edges(&mut self) -> Result<(), NodeIndex<Ix>> {
1560 for (edge_index, edge) in enumerate(&mut self.edges) {
1561 let a = edge.source();
1562 let b = edge.target();
1563 let edge_idx = EdgeIndex::new(edge_index);
1564 match index_twice(&mut self.nodes, a.index(), b.index()) {
1565 Pair::None => return Err(if a > b { a } else { b }),
1566 Pair::One(an) => {
1567 edge.next = an.next;
1568 an.next[0] = edge_idx;
1569 an.next[1] = edge_idx;
1570 }
1571 Pair::Both(an, bn) => {
1572 edge.next = [an.next[0], bn.next[1]];
1574 an.next[0] = edge_idx;
1575 bn.next[1] = edge_idx;
1576 }
1577 }
1578 }
1579 Ok(())
1580 }
1581}
1582
1583#[derive(Debug, Clone)]
1585pub struct Externals<'a, N: 'a, Ty, Ix: IndexType = DefaultIx> {
1586 iter: iter::Enumerate<slice::Iter<'a, Node<N, Ix>>>,
1587 dir: Direction,
1588 ty: PhantomData<Ty>,
1589}
1590
1591impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix>
1592where
1593 Ty: EdgeType,
1594 Ix: IndexType,
1595{
1596 type Item = NodeIndex<Ix>;
1597 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1598 let k = self.dir.index();
1599 loop {
1600 match self.iter.next() {
1601 None => return None,
1602 Some((index, node)) => {
1603 if node.next[k] == EdgeIndex::end()
1604 && (Ty::is_directed() || node.next[1 - k] == EdgeIndex::end())
1605 {
1606 return Some(NodeIndex::new(index));
1607 } else {
1608 continue;
1609 }
1610 }
1611 }
1612 }
1613 }
1614 fn size_hint(&self) -> (usize, Option<usize>) {
1615 let (_, upper) = self.iter.size_hint();
1616 (0, upper)
1617 }
1618}
1619
1620#[derive(Debug)]
1631pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx> {
1632 skip_start: NodeIndex<Ix>,
1634 edges: &'a [Edge<E, Ix>],
1635 next: [EdgeIndex<Ix>; 2],
1636}
1637
1638impl<E, Ix> Iterator for Neighbors<'_, E, Ix>
1639where
1640 Ix: IndexType,
1641{
1642 type Item = NodeIndex<Ix>;
1643
1644 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1645 match self.edges.get(self.next[0].index()) {
1647 None => {}
1648 Some(edge) => {
1649 self.next[0] = edge.next[0];
1650 return Some(edge.node[1]);
1651 }
1652 }
1653 while let Some(edge) = self.edges.get(self.next[1].index()) {
1658 self.next[1] = edge.next[1];
1659 if edge.node[0] != self.skip_start {
1660 return Some(edge.node[0]);
1661 }
1662 }
1663 None
1664 }
1665}
1666
1667impl<E, Ix> Clone for Neighbors<'_, E, Ix>
1668where
1669 Ix: IndexType,
1670{
1671 clone_fields!(Neighbors, skip_start, edges, next,);
1672}
1673
1674impl<E, Ix> Neighbors<'_, E, Ix>
1675where
1676 Ix: IndexType,
1677{
1678 pub fn detach(&self) -> WalkNeighbors<Ix> {
1684 WalkNeighbors {
1685 skip_start: self.skip_start,
1686 next: self.next,
1687 }
1688 }
1689}
1690
1691struct EdgesWalkerMut<'a, E: 'a, Ix: IndexType = DefaultIx> {
1692 edges: &'a mut [Edge<E, Ix>],
1693 next: EdgeIndex<Ix>,
1694 dir: Direction,
1695}
1696
1697fn edges_walker_mut<E, Ix>(
1698 edges: &mut [Edge<E, Ix>],
1699 next: EdgeIndex<Ix>,
1700 dir: Direction,
1701) -> EdgesWalkerMut<E, Ix>
1702where
1703 Ix: IndexType,
1704{
1705 EdgesWalkerMut { edges, next, dir }
1706}
1707
1708impl<E, Ix> EdgesWalkerMut<'_, E, Ix>
1709where
1710 Ix: IndexType,
1711{
1712 fn next_edge(&mut self) -> Option<&mut Edge<E, Ix>> {
1713 self.next().map(|t| t.1)
1714 }
1715
1716 fn next(&mut self) -> Option<(EdgeIndex<Ix>, &mut Edge<E, Ix>)> {
1717 let this_index = self.next;
1718 let k = self.dir.index();
1719 match self.edges.get_mut(self.next.index()) {
1720 None => None,
1721 Some(edge) => {
1722 self.next = edge.next[k];
1723 Some((this_index, edge))
1724 }
1725 }
1726 }
1727}
1728
1729impl<'a, N, E, Ty, Ix> visit::IntoEdges for &'a Graph<N, E, Ty, Ix>
1730where
1731 Ty: EdgeType,
1732 Ix: IndexType,
1733{
1734 type Edges = Edges<'a, E, Ty, Ix>;
1735 fn edges(self, a: Self::NodeId) -> Self::Edges {
1736 self.edges(a)
1737 }
1738}
1739
1740impl<'a, N, E, Ty, Ix> visit::IntoEdgesDirected for &'a Graph<N, E, Ty, Ix>
1741where
1742 Ty: EdgeType,
1743 Ix: IndexType,
1744{
1745 type EdgesDirected = Edges<'a, E, Ty, Ix>;
1746 fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
1747 self.edges_directed(a, dir)
1748 }
1749}
1750
1751#[derive(Debug)]
1753pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1754where
1755 Ty: EdgeType,
1756 Ix: IndexType,
1757{
1758 skip_start: NodeIndex<Ix>,
1760 edges: &'a [Edge<E, Ix>],
1761
1762 next: [EdgeIndex<Ix>; 2],
1764
1765 direction: Direction,
1768 ty: PhantomData<Ty>,
1769}
1770
1771impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1772where
1773 Ty: EdgeType,
1774 Ix: IndexType,
1775{
1776 type Item = EdgeReference<'a, E, Ix>;
1777
1778 fn next(&mut self) -> Option<Self::Item> {
1779 let (iterate_over, reverse) = if Ty::is_directed() {
1789 (Some(self.direction), None)
1790 } else {
1791 (None, Some(self.direction.opposite()))
1792 };
1793
1794 if iterate_over.unwrap_or(Outgoing) == Outgoing {
1795 let i = self.next[0].index();
1796 if let Some(Edge { node, weight, next }) = self.edges.get(i) {
1797 self.next[0] = next[0];
1798 return Some(EdgeReference {
1799 index: edge_index(i),
1800 node: if reverse == Some(Outgoing) {
1801 swap_pair(*node)
1802 } else {
1803 *node
1804 },
1805 weight,
1806 });
1807 }
1808 }
1809
1810 if iterate_over.unwrap_or(Incoming) == Incoming {
1811 while let Some(Edge { node, weight, next }) = self.edges.get(self.next[1].index()) {
1812 let edge_index = self.next[1];
1813 self.next[1] = next[1];
1814 if iterate_over.is_none() && node[0] == self.skip_start {
1817 continue;
1818 }
1819
1820 return Some(EdgeReference {
1821 index: edge_index,
1822 node: if reverse == Some(Incoming) {
1823 swap_pair(*node)
1824 } else {
1825 *node
1826 },
1827 weight,
1828 });
1829 }
1830 }
1831
1832 None
1833 }
1834}
1835
1836#[derive(Debug, Clone)]
1838pub struct EdgesConnecting<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1839where
1840 Ty: EdgeType,
1841 Ix: IndexType,
1842{
1843 target_node: NodeIndex<Ix>,
1844 edges: Edges<'a, E, Ty, Ix>,
1845 ty: PhantomData<Ty>,
1846}
1847
1848impl<'a, E, Ty, Ix> Iterator for EdgesConnecting<'a, E, Ty, Ix>
1849where
1850 Ty: EdgeType,
1851 Ix: IndexType,
1852{
1853 type Item = EdgeReference<'a, E, Ix>;
1854
1855 fn next(&mut self) -> Option<EdgeReference<'a, E, Ix>> {
1856 let target_node = self.target_node;
1857 self.edges
1858 .by_ref()
1859 .find(|&edge| edge.node[1] == target_node)
1860 }
1861 fn size_hint(&self) -> (usize, Option<usize>) {
1862 let (_, upper) = self.edges.size_hint();
1863 (0, upper)
1864 }
1865}
1866
1867fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1868 x.swap(0, 1);
1869 x
1870}
1871
1872impl<E, Ty, Ix> Clone for Edges<'_, E, Ty, Ix>
1873where
1874 Ix: IndexType,
1875 Ty: EdgeType,
1876{
1877 fn clone(&self) -> Self {
1878 Edges {
1879 skip_start: self.skip_start,
1880 edges: self.edges,
1881 next: self.next,
1882 direction: self.direction,
1883 ty: self.ty,
1884 }
1885 }
1886}
1887
1888pub struct NodeWeights<'a, N: 'a, Ix: IndexType = DefaultIx> {
1890 nodes: ::core::slice::Iter<'a, Node<N, Ix>>,
1891}
1892impl<'a, N, Ix> Iterator for NodeWeights<'a, N, Ix>
1893where
1894 Ix: IndexType,
1895{
1896 type Item = &'a N;
1897
1898 fn next(&mut self) -> Option<&'a N> {
1899 self.nodes.next().map(|node| &node.weight)
1900 }
1901
1902 fn size_hint(&self) -> (usize, Option<usize>) {
1903 self.nodes.size_hint()
1904 }
1905}
1906#[derive(Debug)]
1908pub struct NodeWeightsMut<'a, N: 'a, Ix: IndexType = DefaultIx> {
1909 nodes: ::core::slice::IterMut<'a, Node<N, Ix>>, }
1911
1912impl<'a, N, Ix> Iterator for NodeWeightsMut<'a, N, Ix>
1913where
1914 Ix: IndexType,
1915{
1916 type Item = &'a mut N;
1917
1918 fn next(&mut self) -> Option<&'a mut N> {
1919 self.nodes.next().map(|node| &mut node.weight)
1920 }
1921
1922 fn size_hint(&self) -> (usize, Option<usize>) {
1923 self.nodes.size_hint()
1924 }
1925}
1926
1927pub struct EdgeWeights<'a, E: 'a, Ix: IndexType = DefaultIx> {
1929 edges: ::core::slice::Iter<'a, Edge<E, Ix>>,
1930}
1931
1932impl<'a, E, Ix> Iterator for EdgeWeights<'a, E, Ix>
1933where
1934 Ix: IndexType,
1935{
1936 type Item = &'a E;
1937
1938 fn next(&mut self) -> Option<&'a E> {
1939 self.edges.next().map(|edge| &edge.weight)
1940 }
1941
1942 fn size_hint(&self) -> (usize, Option<usize>) {
1943 self.edges.size_hint()
1944 }
1945}
1946
1947#[derive(Debug)]
1949pub struct EdgeWeightsMut<'a, E: 'a, Ix: IndexType = DefaultIx> {
1950 edges: ::core::slice::IterMut<'a, Edge<E, Ix>>, }
1952
1953impl<'a, E, Ix> Iterator for EdgeWeightsMut<'a, E, Ix>
1954where
1955 Ix: IndexType,
1956{
1957 type Item = &'a mut E;
1958
1959 fn next(&mut self) -> Option<&'a mut E> {
1960 self.edges.next().map(|edge| &mut edge.weight)
1961 }
1962
1963 fn size_hint(&self) -> (usize, Option<usize>) {
1964 self.edges.size_hint()
1965 }
1966}
1967
1968impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for Graph<N, E, Ty, Ix>
1972where
1973 Ty: EdgeType,
1974 Ix: IndexType,
1975{
1976 type Output = N;
1977 fn index(&self, index: NodeIndex<Ix>) -> &N {
1978 &self.nodes[index.index()].weight
1979 }
1980}
1981
1982impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for Graph<N, E, Ty, Ix>
1986where
1987 Ty: EdgeType,
1988 Ix: IndexType,
1989{
1990 fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1991 &mut self.nodes[index.index()].weight
1992 }
1993}
1994
1995impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix>
1999where
2000 Ty: EdgeType,
2001 Ix: IndexType,
2002{
2003 type Output = E;
2004 fn index(&self, index: EdgeIndex<Ix>) -> &E {
2005 &self.edges[index.index()].weight
2006 }
2007}
2008
2009impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix>
2013where
2014 Ty: EdgeType,
2015 Ix: IndexType,
2016{
2017 fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
2018 &mut self.edges[index.index()].weight
2019 }
2020}
2021
2022impl<N, E, Ty, Ix> Default for Graph<N, E, Ty, Ix>
2024where
2025 Ty: EdgeType,
2026 Ix: IndexType,
2027{
2028 fn default() -> Self {
2029 Self::with_capacity(0, 0)
2030 }
2031}
2032
2033pub trait GraphIndex: Copy {
2035 #[doc(hidden)]
2036 fn index(&self) -> usize;
2037 #[doc(hidden)]
2038 fn is_node_index() -> bool;
2039}
2040
2041impl<Ix: IndexType> GraphIndex for NodeIndex<Ix> {
2042 #[inline]
2043 #[doc(hidden)]
2044 fn index(&self) -> usize {
2045 NodeIndex::index(*self)
2046 }
2047 #[inline]
2048 #[doc(hidden)]
2049 fn is_node_index() -> bool {
2050 true
2051 }
2052}
2053
2054impl<Ix: IndexType> GraphIndex for EdgeIndex<Ix> {
2055 #[inline]
2056 #[doc(hidden)]
2057 fn index(&self) -> usize {
2058 EdgeIndex::index(*self)
2059 }
2060 #[inline]
2061 #[doc(hidden)]
2062 fn is_node_index() -> bool {
2063 false
2064 }
2065}
2066
2067pub struct WalkNeighbors<Ix> {
2103 skip_start: NodeIndex<Ix>,
2104 next: [EdgeIndex<Ix>; 2],
2105}
2106
2107impl<Ix> Clone for WalkNeighbors<Ix>
2108where
2109 Ix: IndexType,
2110{
2111 fn clone(&self) -> Self {
2112 WalkNeighbors {
2113 skip_start: self.skip_start,
2114 next: self.next,
2115 }
2116 }
2117}
2118
2119impl<Ix: IndexType> WalkNeighbors<Ix> {
2120 pub fn next<N, E, Ty: EdgeType>(
2127 &mut self,
2128 g: &Graph<N, E, Ty, Ix>,
2129 ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
2130 match g.edges.get(self.next[0].index()) {
2132 None => {}
2133 Some(edge) => {
2134 let ed = self.next[0];
2135 self.next[0] = edge.next[0];
2136 return Some((ed, edge.node[1]));
2137 }
2138 }
2139 while let Some(edge) = g.edges.get(self.next[1].index()) {
2144 let ed = self.next[1];
2145 self.next[1] = edge.next[1];
2146 if edge.node[0] != self.skip_start {
2147 return Some((ed, edge.node[0]));
2148 }
2149 }
2150 None
2151 }
2152
2153 pub fn next_node<N, E, Ty: EdgeType>(
2154 &mut self,
2155 g: &Graph<N, E, Ty, Ix>,
2156 ) -> Option<NodeIndex<Ix>> {
2157 self.next(g).map(|t| t.1)
2158 }
2159
2160 pub fn next_edge<N, E, Ty: EdgeType>(
2161 &mut self,
2162 g: &Graph<N, E, Ty, Ix>,
2163 ) -> Option<EdgeIndex<Ix>> {
2164 self.next(g).map(|t| t.0)
2165 }
2166}
2167
2168#[derive(Clone, Debug)]
2170pub struct NodeIndices<Ix = DefaultIx> {
2171 r: Range<usize>,
2172 ty: PhantomData<fn() -> Ix>,
2173}
2174
2175impl<Ix: IndexType> Iterator for NodeIndices<Ix> {
2176 type Item = NodeIndex<Ix>;
2177
2178 fn next(&mut self) -> Option<Self::Item> {
2179 self.r.next().map(node_index)
2180 }
2181
2182 fn size_hint(&self) -> (usize, Option<usize>) {
2183 self.r.size_hint()
2184 }
2185}
2186
2187impl<Ix: IndexType> DoubleEndedIterator for NodeIndices<Ix> {
2188 fn next_back(&mut self) -> Option<Self::Item> {
2189 self.r.next_back().map(node_index)
2190 }
2191}
2192
2193impl<Ix: IndexType> ExactSizeIterator for NodeIndices<Ix> {}
2194
2195#[derive(Clone, Debug)]
2197pub struct EdgeIndices<Ix = DefaultIx> {
2198 r: Range<usize>,
2199 ty: PhantomData<fn() -> Ix>,
2200}
2201
2202impl<Ix: IndexType> Iterator for EdgeIndices<Ix> {
2203 type Item = EdgeIndex<Ix>;
2204
2205 fn next(&mut self) -> Option<Self::Item> {
2206 self.r.next().map(edge_index)
2207 }
2208
2209 fn size_hint(&self) -> (usize, Option<usize>) {
2210 self.r.size_hint()
2211 }
2212}
2213
2214impl<Ix: IndexType> DoubleEndedIterator for EdgeIndices<Ix> {
2215 fn next_back(&mut self) -> Option<Self::Item> {
2216 self.r.next_back().map(edge_index)
2217 }
2218}
2219
2220impl<Ix: IndexType> ExactSizeIterator for EdgeIndices<Ix> {}
2221
2222#[derive(Debug)]
2224pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
2225 index: EdgeIndex<Ix>,
2226 node: [NodeIndex<Ix>; 2],
2227 weight: &'a E,
2228}
2229
2230impl<E, Ix: IndexType> Clone for EdgeReference<'_, E, Ix> {
2231 fn clone(&self) -> Self {
2232 *self
2233 }
2234}
2235
2236impl<E, Ix: IndexType> Copy for EdgeReference<'_, E, Ix> {}
2237
2238impl<E, Ix: IndexType> PartialEq for EdgeReference<'_, E, Ix>
2239where
2240 E: PartialEq,
2241{
2242 fn eq(&self, rhs: &Self) -> bool {
2243 self.index == rhs.index && self.weight == rhs.weight
2244 }
2245}
2246
2247impl<N, E, Ty, Ix> visit::GraphBase for Graph<N, E, Ty, Ix>
2248where
2249 Ix: IndexType,
2250{
2251 type NodeId = NodeIndex<Ix>;
2252 type EdgeId = EdgeIndex<Ix>;
2253}
2254
2255impl<N, E, Ty, Ix> visit::Visitable for Graph<N, E, Ty, Ix>
2256where
2257 Ty: EdgeType,
2258 Ix: IndexType,
2259{
2260 type Map = FixedBitSet;
2261 fn visit_map(&self) -> FixedBitSet {
2262 FixedBitSet::with_capacity(self.node_count())
2263 }
2264
2265 fn reset_map(&self, map: &mut Self::Map) {
2266 map.clear();
2267 map.grow(self.node_count());
2268 }
2269}
2270
2271impl<N, E, Ty, Ix> visit::GraphProp for Graph<N, E, Ty, Ix>
2272where
2273 Ty: EdgeType,
2274 Ix: IndexType,
2275{
2276 type EdgeType = Ty;
2277}
2278
2279impl<'a, N, E: 'a, Ty, Ix> visit::IntoNodeIdentifiers for &'a Graph<N, E, Ty, Ix>
2280where
2281 Ty: EdgeType,
2282 Ix: IndexType,
2283{
2284 type NodeIdentifiers = NodeIndices<Ix>;
2285 fn node_identifiers(self) -> NodeIndices<Ix> {
2286 Graph::node_indices(self)
2287 }
2288}
2289
2290impl<N, E, Ty, Ix> visit::NodeCount for Graph<N, E, Ty, Ix>
2291where
2292 Ty: EdgeType,
2293 Ix: IndexType,
2294{
2295 fn node_count(&self) -> usize {
2296 self.node_count()
2297 }
2298}
2299
2300impl<N, E, Ty, Ix> visit::NodeIndexable for Graph<N, E, Ty, Ix>
2301where
2302 Ty: EdgeType,
2303 Ix: IndexType,
2304{
2305 #[inline]
2306 fn node_bound(&self) -> usize {
2307 self.node_count()
2308 }
2309 #[inline]
2310 fn to_index(&self, ix: NodeIndex<Ix>) -> usize {
2311 ix.index()
2312 }
2313 #[inline]
2314 fn from_index(&self, ix: usize) -> Self::NodeId {
2315 NodeIndex::new(ix)
2316 }
2317}
2318
2319impl<N, E, Ty, Ix> visit::NodeCompactIndexable for Graph<N, E, Ty, Ix>
2320where
2321 Ty: EdgeType,
2322 Ix: IndexType,
2323{
2324}
2325
2326impl<'a, N, E: 'a, Ty, Ix> visit::IntoNeighbors for &'a Graph<N, E, Ty, Ix>
2327where
2328 Ty: EdgeType,
2329 Ix: IndexType,
2330{
2331 type Neighbors = Neighbors<'a, E, Ix>;
2332 fn neighbors(self, n: NodeIndex<Ix>) -> Neighbors<'a, E, Ix> {
2333 Graph::neighbors(self, n)
2334 }
2335}
2336
2337impl<'a, N, E: 'a, Ty, Ix> visit::IntoNeighborsDirected for &'a Graph<N, E, Ty, Ix>
2338where
2339 Ty: EdgeType,
2340 Ix: IndexType,
2341{
2342 type NeighborsDirected = Neighbors<'a, E, Ix>;
2343 fn neighbors_directed(self, n: NodeIndex<Ix>, d: Direction) -> Neighbors<'a, E, Ix> {
2344 Graph::neighbors_directed(self, n, d)
2345 }
2346}
2347
2348impl<'a, N: 'a, E: 'a, Ty, Ix> visit::IntoEdgeReferences for &'a Graph<N, E, Ty, Ix>
2349where
2350 Ty: EdgeType,
2351 Ix: IndexType,
2352{
2353 type EdgeRef = EdgeReference<'a, E, Ix>;
2354 type EdgeReferences = EdgeReferences<'a, E, Ix>;
2355 fn edge_references(self) -> Self::EdgeReferences {
2356 (*self).edge_references()
2357 }
2358}
2359
2360impl<N, E, Ty, Ix> visit::EdgeCount for Graph<N, E, Ty, Ix>
2361where
2362 Ty: EdgeType,
2363 Ix: IndexType,
2364{
2365 #[inline]
2366 fn edge_count(&self) -> usize {
2367 self.edge_count()
2368 }
2369}
2370
2371impl<'a, N, E, Ty, Ix> visit::IntoNodeReferences for &'a Graph<N, E, Ty, Ix>
2372where
2373 Ty: EdgeType,
2374 Ix: IndexType,
2375{
2376 type NodeRef = (NodeIndex<Ix>, &'a N);
2377 type NodeReferences = NodeReferences<'a, N, Ix>;
2378 fn node_references(self) -> Self::NodeReferences {
2379 NodeReferences {
2380 iter: self.nodes.iter().enumerate(),
2381 }
2382 }
2383}
2384
2385#[derive(Debug, Clone)]
2387pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
2388 iter: iter::Enumerate<slice::Iter<'a, Node<N, Ix>>>,
2389}
2390
2391impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
2392where
2393 Ix: IndexType,
2394{
2395 type Item = (NodeIndex<Ix>, &'a N);
2396
2397 fn next(&mut self) -> Option<Self::Item> {
2398 self.iter
2399 .next()
2400 .map(|(i, node)| (node_index(i), &node.weight))
2401 }
2402
2403 fn size_hint(&self) -> (usize, Option<usize>) {
2404 self.iter.size_hint()
2405 }
2406}
2407
2408impl<N, Ix> DoubleEndedIterator for NodeReferences<'_, N, Ix>
2409where
2410 Ix: IndexType,
2411{
2412 fn next_back(&mut self) -> Option<Self::Item> {
2413 self.iter
2414 .next_back()
2415 .map(|(i, node)| (node_index(i), &node.weight))
2416 }
2417}
2418
2419impl<N, Ix> ExactSizeIterator for NodeReferences<'_, N, Ix> where Ix: IndexType {}
2420
2421impl<'a, Ix, E> EdgeReference<'a, E, Ix>
2422where
2423 Ix: IndexType,
2424{
2425 pub fn weight(&self) -> &'a E {
2430 self.weight
2431 }
2432}
2433
2434impl<Ix, E> visit::EdgeRef for EdgeReference<'_, E, Ix>
2435where
2436 Ix: IndexType,
2437{
2438 type NodeId = NodeIndex<Ix>;
2439 type EdgeId = EdgeIndex<Ix>;
2440 type Weight = E;
2441
2442 fn source(&self) -> Self::NodeId {
2443 self.node[0]
2444 }
2445 fn target(&self) -> Self::NodeId {
2446 self.node[1]
2447 }
2448 fn weight(&self) -> &E {
2449 self.weight
2450 }
2451 fn id(&self) -> Self::EdgeId {
2452 self.index
2453 }
2454}
2455
2456#[derive(Debug, Clone)]
2458pub struct EdgeReferences<'a, E: 'a, Ix: IndexType = DefaultIx> {
2459 iter: iter::Enumerate<slice::Iter<'a, Edge<E, Ix>>>,
2460}
2461
2462impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
2463where
2464 Ix: IndexType,
2465{
2466 type Item = EdgeReference<'a, E, Ix>;
2467
2468 fn next(&mut self) -> Option<Self::Item> {
2469 self.iter.next().map(|(i, edge)| EdgeReference {
2470 index: edge_index(i),
2471 node: edge.node,
2472 weight: &edge.weight,
2473 })
2474 }
2475
2476 fn size_hint(&self) -> (usize, Option<usize>) {
2477 self.iter.size_hint()
2478 }
2479}
2480
2481impl<E, Ix> DoubleEndedIterator for EdgeReferences<'_, E, Ix>
2482where
2483 Ix: IndexType,
2484{
2485 fn next_back(&mut self) -> Option<Self::Item> {
2486 self.iter.next_back().map(|(i, edge)| EdgeReference {
2487 index: edge_index(i),
2488 node: edge.node,
2489 weight: &edge.weight,
2490 })
2491 }
2492}
2493
2494impl<E, Ix> ExactSizeIterator for EdgeReferences<'_, E, Ix> where Ix: IndexType {}
2495
2496impl<N, E, Ty, Ix> visit::EdgeIndexable for Graph<N, E, Ty, Ix>
2497where
2498 Ty: EdgeType,
2499 Ix: IndexType,
2500{
2501 fn edge_bound(&self) -> usize {
2502 self.edge_count()
2503 }
2504
2505 fn to_index(&self, ix: EdgeIndex<Ix>) -> usize {
2506 ix.index()
2507 }
2508
2509 fn from_index(&self, ix: usize) -> Self::EdgeId {
2510 EdgeIndex::new(ix)
2511 }
2512}
2513
2514mod frozen;
2515#[cfg(feature = "stable_graph")]
2516pub mod stable_graph;
2517
2518pub struct Frozen<'a, G: 'a>(&'a mut G);