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 crate::{Directed, Direction, EdgeType, Incoming, IntoWeightedEdge, Outgoing, Undirected};
11
12use crate::iter_format::{DebugMap, IterFormatExt, NoPretty};
13
14use crate::util::enumerate;
15use crate::visit::EdgeRef;
16use crate::visit::{IntoEdges, IntoEdgesDirected, IntoNodeReferences};
17
18#[cfg(feature = "serde-1")]
19mod serialization;
20
21pub type DefaultIx = u32;
28
29pub unsafe trait IndexType: Copy + Default + Hash + Ord + fmt::Debug + 'static {
34 fn new(x: usize) -> Self;
35 fn index(&self) -> usize;
36 fn max() -> Self;
37}
38
39unsafe impl IndexType for usize {
40 #[inline(always)]
41 fn new(x: usize) -> Self {
42 x
43 }
44 #[inline(always)]
45 fn index(&self) -> Self {
46 *self
47 }
48 #[inline(always)]
49 fn max() -> Self {
50 ::std::usize::MAX
51 }
52}
53
54unsafe impl IndexType for u32 {
55 #[inline(always)]
56 fn new(x: usize) -> Self {
57 x as u32
58 }
59 #[inline(always)]
60 fn index(&self) -> usize {
61 *self as usize
62 }
63 #[inline(always)]
64 fn max() -> Self {
65 ::std::u32::MAX
66 }
67}
68
69unsafe impl IndexType for u16 {
70 #[inline(always)]
71 fn new(x: usize) -> Self {
72 x as u16
73 }
74 #[inline(always)]
75 fn index(&self) -> usize {
76 *self as usize
77 }
78 #[inline(always)]
79 fn max() -> Self {
80 ::std::u16::MAX
81 }
82}
83
84unsafe impl IndexType for u8 {
85 #[inline(always)]
86 fn new(x: usize) -> Self {
87 x as u8
88 }
89 #[inline(always)]
90 fn index(&self) -> usize {
91 *self as usize
92 }
93 #[inline(always)]
94 fn max() -> Self {
95 ::std::u8::MAX
96 }
97}
98
99#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
101pub struct NodeIndex<Ix = DefaultIx>(Ix);
102
103impl<Ix: IndexType> NodeIndex<Ix> {
104 #[inline]
105 pub fn new(x: usize) -> Self {
106 NodeIndex(IndexType::new(x))
107 }
108
109 #[inline]
110 pub fn index(self) -> usize {
111 self.0.index()
112 }
113
114 #[inline]
115 pub fn end() -> Self {
116 NodeIndex(IndexType::max())
117 }
118
119 fn _into_edge(self) -> EdgeIndex<Ix> {
120 EdgeIndex(self.0)
121 }
122}
123
124unsafe impl<Ix: IndexType> IndexType for NodeIndex<Ix> {
125 fn index(&self) -> usize {
126 self.0.index()
127 }
128 fn new(x: usize) -> Self {
129 NodeIndex::new(x)
130 }
131 fn max() -> Self {
132 NodeIndex(<Ix as IndexType>::max())
133 }
134}
135
136impl<Ix: IndexType> From<Ix> for NodeIndex<Ix> {
137 fn from(ix: Ix) -> Self {
138 NodeIndex(ix)
139 }
140}
141
142impl<Ix: fmt::Debug> fmt::Debug for NodeIndex<Ix> {
143 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
144 write!(f, "NodeIndex({:?})", self.0)
145 }
146}
147
148pub fn node_index<Ix: IndexType>(index: usize) -> NodeIndex<Ix> {
150 NodeIndex::new(index)
151}
152
153pub fn edge_index<Ix: IndexType>(index: usize) -> EdgeIndex<Ix> {
155 EdgeIndex::new(index)
156}
157
158#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
160pub struct EdgeIndex<Ix = DefaultIx>(Ix);
161
162impl<Ix: IndexType> EdgeIndex<Ix> {
163 #[inline]
164 pub fn new(x: usize) -> Self {
165 EdgeIndex(IndexType::new(x))
166 }
167
168 #[inline]
169 pub fn index(self) -> usize {
170 self.0.index()
171 }
172
173 #[inline]
176 pub fn end() -> Self {
177 EdgeIndex(IndexType::max())
178 }
179
180 fn _into_node(self) -> NodeIndex<Ix> {
181 NodeIndex(self.0)
182 }
183}
184
185impl<Ix: IndexType> From<Ix> for EdgeIndex<Ix> {
186 fn from(ix: Ix) -> Self {
187 EdgeIndex(ix)
188 }
189}
190
191impl<Ix: fmt::Debug> fmt::Debug for EdgeIndex<Ix> {
192 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
193 write!(f, "EdgeIndex({:?})", self.0)
194 }
195}
196const DIRECTIONS: [Direction; 2] = [Outgoing, Incoming];
213
214#[derive(Debug)]
216pub struct Node<N, Ix = DefaultIx> {
217 pub weight: N,
219 next: [EdgeIndex<Ix>; 2],
221}
222
223impl<E, Ix> Clone for Node<E, Ix>
224where
225 E: Clone,
226 Ix: Copy,
227{
228 clone_fields!(Node, weight, next,);
229}
230
231impl<N, Ix: IndexType> Node<N, Ix> {
232 pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix> {
234 self.next[dir.index()]
235 }
236}
237
238#[derive(Debug)]
240pub struct Edge<E, Ix = DefaultIx> {
241 pub weight: E,
243 next: [EdgeIndex<Ix>; 2],
245 node: [NodeIndex<Ix>; 2],
247}
248
249impl<E, Ix> Clone for Edge<E, Ix>
250where
251 E: Clone,
252 Ix: Copy,
253{
254 clone_fields!(Edge, weight, next, node,);
255}
256
257impl<E, Ix: IndexType> Edge<E, Ix> {
258 pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix> {
260 self.next[dir.index()]
261 }
262
263 pub fn source(&self) -> NodeIndex<Ix> {
265 self.node[0]
266 }
267
268 pub fn target(&self) -> NodeIndex<Ix> {
270 self.node[1]
271 }
272}
273
274pub struct Graph<N, E, Ty = Directed, Ix = DefaultIx> {
345 nodes: Vec<Node<N, Ix>>,
346 edges: Vec<Edge<E, Ix>>,
347 ty: PhantomData<Ty>,
348}
349
350pub type DiGraph<N, E, Ix = DefaultIx> = Graph<N, E, Directed, Ix>;
355
356pub type UnGraph<N, E, Ix = DefaultIx> = Graph<N, E, Undirected, Ix>;
361
362impl<N, E, Ty, Ix: IndexType> Clone for Graph<N, E, Ty, Ix>
364where
365 N: Clone,
366 E: Clone,
367{
368 fn clone(&self) -> Self {
369 Graph {
370 nodes: self.nodes.clone(),
371 edges: self.edges.clone(),
372 ty: self.ty,
373 }
374 }
375
376 fn clone_from(&mut self, rhs: &Self) {
377 self.nodes.clone_from(&rhs.nodes);
378 self.edges.clone_from(&rhs.edges);
379 self.ty = rhs.ty;
380 }
381}
382
383impl<N, E, Ty, Ix> fmt::Debug for Graph<N, E, Ty, Ix>
384where
385 N: fmt::Debug,
386 E: fmt::Debug,
387 Ty: EdgeType,
388 Ix: IndexType,
389{
390 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
391 let etype = if self.is_directed() {
392 "Directed"
393 } else {
394 "Undirected"
395 };
396 let mut fmt_struct = f.debug_struct("Graph");
397 fmt_struct.field("Ty", &etype);
398 fmt_struct.field("node_count", &self.node_count());
399 fmt_struct.field("edge_count", &self.edge_count());
400 if self.edge_count() > 0 {
401 fmt_struct.field(
402 "edges",
403 &self
404 .edges
405 .iter()
406 .map(|e| NoPretty((e.source().index(), e.target().index())))
407 .format(", "),
408 );
409 }
410 if size_of::<N>() != 0 {
412 fmt_struct.field(
413 "node weights",
414 &DebugMap(|| self.nodes.iter().map(|n| &n.weight).enumerate()),
415 );
416 }
417 if size_of::<E>() != 0 {
418 fmt_struct.field(
419 "edge weights",
420 &DebugMap(|| self.edges.iter().map(|n| &n.weight).enumerate()),
421 );
422 }
423 fmt_struct.finish()
424 }
425}
426
427enum Pair<T> {
428 Both(T, T),
429 One(T),
430 None,
431}
432
433use std::cmp::max;
434
435fn index_twice<T>(slc: &mut [T], a: usize, b: usize) -> Pair<&mut T> {
437 if max(a, b) >= slc.len() {
438 Pair::None
439 } else if a == b {
440 Pair::One(&mut slc[max(a, b)])
441 } else {
442 unsafe {
444 let ar = &mut *(slc.get_unchecked_mut(a) as *mut _);
445 let br = &mut *(slc.get_unchecked_mut(b) as *mut _);
446 Pair::Both(ar, br)
447 }
448 }
449}
450
451impl<N, E> Graph<N, E, Directed> {
452 pub fn new() -> Self {
457 Graph {
458 nodes: Vec::new(),
459 edges: Vec::new(),
460 ty: PhantomData,
461 }
462 }
463}
464
465impl<N, E> Graph<N, E, Undirected> {
466 pub fn new_undirected() -> Self {
471 Graph {
472 nodes: Vec::new(),
473 edges: Vec::new(),
474 ty: PhantomData,
475 }
476 }
477}
478
479impl<N, E, Ty, Ix> Graph<N, E, Ty, Ix>
480where
481 Ty: EdgeType,
482 Ix: IndexType,
483{
484 pub fn with_capacity(nodes: usize, edges: usize) -> Self {
486 Graph {
487 nodes: Vec::with_capacity(nodes),
488 edges: Vec::with_capacity(edges),
489 ty: PhantomData,
490 }
491 }
492
493 pub fn node_count(&self) -> usize {
497 self.nodes.len()
498 }
499
500 pub fn edge_count(&self) -> usize {
504 self.edges.len()
505 }
506
507 #[inline]
509 pub fn is_directed(&self) -> bool {
510 Ty::is_directed()
511 }
512
513 pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
522 let node = Node {
523 weight,
524 next: [EdgeIndex::end(), EdgeIndex::end()],
525 };
526 let node_idx = NodeIndex::new(self.nodes.len());
527 assert!(<Ix as IndexType>::max().index() == !0 || NodeIndex::end() != node_idx);
529 self.nodes.push(node);
530 node_idx
531 }
532
533 pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
537 self.nodes.get(a.index()).map(|n| &n.weight)
538 }
539
540 pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
544 self.nodes.get_mut(a.index()).map(|n| &mut n.weight)
545 }
546
547 pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
561 let edge_idx = EdgeIndex::new(self.edges.len());
562 assert!(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx);
563 let mut edge = Edge {
564 weight,
565 node: [a, b],
566 next: [EdgeIndex::end(); 2],
567 };
568 match index_twice(&mut self.nodes, a.index(), b.index()) {
569 Pair::None => panic!("Graph::add_edge: node indices out of bounds"),
570 Pair::One(an) => {
571 edge.next = an.next;
572 an.next[0] = edge_idx;
573 an.next[1] = edge_idx;
574 }
575 Pair::Both(an, bn) => {
576 edge.next = [an.next[0], bn.next[1]];
578 an.next[0] = edge_idx;
579 bn.next[1] = edge_idx;
580 }
581 }
582 self.edges.push(edge);
583 edge_idx
584 }
585
586 pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
596 if let Some(ix) = self.find_edge(a, b) {
597 if let Some(ed) = self.edge_weight_mut(ix) {
598 *ed = weight;
599 return ix;
600 }
601 }
602 self.add_edge(a, b, weight)
603 }
604
605 pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
609 self.edges.get(e.index()).map(|ed| &ed.weight)
610 }
611
612 pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
616 self.edges.get_mut(e.index()).map(|ed| &mut ed.weight)
617 }
618
619 pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)> {
621 self.edges
622 .get(e.index())
623 .map(|ed| (ed.source(), ed.target()))
624 }
625
626 pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N> {
639 self.nodes.get(a.index())?;
640 for d in &DIRECTIONS {
641 let k = d.index();
642
643 loop {
645 let next = self.nodes[a.index()].next[k];
646 if next == EdgeIndex::end() {
647 break;
648 }
649 let ret = self.remove_edge(next);
650 debug_assert!(ret.is_some());
651 let _ = ret;
652 }
653 }
654
655 let node = self.nodes.swap_remove(a.index());
659
660 let swap_edges = match self.nodes.get(a.index()) {
663 None => return Some(node.weight),
664 Some(ed) => ed.next,
665 };
666
667 let old_index = NodeIndex::new(self.nodes.len());
669 let new_index = a;
670
671 for &d in &DIRECTIONS {
673 let k = d.index();
674 let mut edges = edges_walker_mut(&mut self.edges, swap_edges[k], d);
675 while let Some(curedge) = edges.next_edge() {
676 debug_assert!(curedge.node[k] == old_index);
677 curedge.node[k] = new_index;
678 }
679 }
680 Some(node.weight)
681 }
682
683 fn change_edge_links(
686 &mut self,
687 edge_node: [NodeIndex<Ix>; 2],
688 e: EdgeIndex<Ix>,
689 edge_next: [EdgeIndex<Ix>; 2],
690 ) {
691 for &d in &DIRECTIONS {
692 let k = d.index();
693 let node = match self.nodes.get_mut(edge_node[k].index()) {
694 Some(r) => r,
695 None => {
696 debug_assert!(
697 false,
698 "Edge's endpoint dir={:?} index={:?} not found",
699 d, edge_node[k]
700 );
701 return;
702 }
703 };
704 let fst = node.next[k];
705 if fst == e {
706 node.next[k] = edge_next[k];
708 } else {
709 let mut edges = edges_walker_mut(&mut self.edges, fst, d);
710 while let Some(curedge) = edges.next_edge() {
711 if curedge.next[k] == e {
712 curedge.next[k] = edge_next[k];
713 break; }
715 }
716 }
717 }
718 }
719
720 pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
728 let (edge_node, edge_next) = match self.edges.get(e.index()) {
732 None => return None,
733 Some(x) => (x.node, x.next),
734 };
735 self.change_edge_links(edge_node, e, edge_next);
738 self.remove_edge_adjust_indices(e)
739 }
740
741 fn remove_edge_adjust_indices(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
742 let edge = self.edges.swap_remove(e.index());
746 let swap = match self.edges.get(e.index()) {
747 None => return Some(edge.weight),
749 Some(ed) => ed.node,
750 };
751 let swapped_e = EdgeIndex::new(self.edges.len());
752
753 self.change_edge_links(swap, swapped_e, [e, e]);
756 Some(edge.weight)
757 }
758
759 pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
772 self.neighbors_directed(a, Outgoing)
773 }
774
775 pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix> {
795 let mut iter = self.neighbors_undirected(a);
796 if self.is_directed() {
797 let k = dir.index();
798 iter.next[1 - k] = EdgeIndex::end();
799 iter.skip_start = NodeIndex::end();
800 }
801 iter
802 }
803
804 pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
819 Neighbors {
820 skip_start: a,
821 edges: &self.edges,
822 next: match self.nodes.get(a.index()) {
823 None => [EdgeIndex::end(), EdgeIndex::end()],
824 Some(n) => n.next,
825 },
826 }
827 }
828
829 pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
837 self.edges_directed(a, Outgoing)
838 }
839
840 pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix> {
852 Edges {
853 skip_start: a,
854 edges: &self.edges,
855 direction: dir,
856 next: match self.nodes.get(a.index()) {
857 None => [EdgeIndex::end(), EdgeIndex::end()],
858 Some(n) => n.next,
859 },
860 ty: PhantomData,
861 }
862 }
863
864 pub fn edges_connecting(
871 &self,
872 a: NodeIndex<Ix>,
873 b: NodeIndex<Ix>,
874 ) -> EdgesConnecting<E, Ty, Ix> {
875 EdgesConnecting {
876 target_node: b,
877 edges: self.edges_directed(a, Direction::Outgoing),
878 ty: PhantomData,
879 }
880 }
881
882 pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
887 self.find_edge(a, b).is_some()
888 }
889
890 pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>> {
895 if !self.is_directed() {
896 self.find_edge_undirected(a, b).map(|(ix, _)| ix)
897 } else {
898 match self.nodes.get(a.index()) {
899 None => None,
900 Some(node) => self.find_edge_directed_from_node(node, b),
901 }
902 }
903 }
904
905 fn find_edge_directed_from_node(
906 &self,
907 node: &Node<N, Ix>,
908 b: NodeIndex<Ix>,
909 ) -> Option<EdgeIndex<Ix>> {
910 let mut edix = node.next[0];
911 while let Some(edge) = self.edges.get(edix.index()) {
912 if edge.node[1] == b {
913 return Some(edix);
914 }
915 edix = edge.next[0];
916 }
917 None
918 }
919
920 pub fn find_edge_undirected(
928 &self,
929 a: NodeIndex<Ix>,
930 b: NodeIndex<Ix>,
931 ) -> Option<(EdgeIndex<Ix>, Direction)> {
932 match self.nodes.get(a.index()) {
933 None => None,
934 Some(node) => self.find_edge_undirected_from_node(node, b),
935 }
936 }
937
938 fn find_edge_undirected_from_node(
939 &self,
940 node: &Node<N, Ix>,
941 b: NodeIndex<Ix>,
942 ) -> Option<(EdgeIndex<Ix>, Direction)> {
943 for &d in &DIRECTIONS {
944 let k = d.index();
945 let mut edix = node.next[k];
946 while let Some(edge) = self.edges.get(edix.index()) {
947 if edge.node[1 - k] == b {
948 return Some((edix, d));
949 }
950 edix = edge.next[k];
951 }
952 }
953 None
954 }
955
956 pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix> {
968 Externals {
969 iter: self.nodes.iter().enumerate(),
970 dir,
971 ty: PhantomData,
972 }
973 }
974
975 pub fn node_indices(&self) -> NodeIndices<Ix> {
988 NodeIndices {
989 r: 0..self.node_count(),
990 ty: PhantomData,
991 }
992 }
993
994 pub fn node_weights_mut(&mut self) -> NodeWeightsMut<N, Ix> {
999 NodeWeightsMut {
1000 nodes: self.nodes.iter_mut(),
1001 }
1002 }
1003
1004 pub fn edge_indices(&self) -> EdgeIndices<Ix> {
1006 EdgeIndices {
1007 r: 0..self.edge_count(),
1008 ty: PhantomData,
1009 }
1010 }
1011
1012 pub fn edge_references(&self) -> EdgeReferences<E, Ix> {
1016 EdgeReferences {
1017 iter: self.edges.iter().enumerate(),
1018 }
1019 }
1020
1021 pub fn edge_weights_mut(&mut self) -> EdgeWeightsMut<E, Ix> {
1026 EdgeWeightsMut {
1027 edges: self.edges.iter_mut(),
1028 }
1029 }
1030
1031 pub fn raw_nodes(&self) -> &[Node<N, Ix>] {
1036 &self.nodes
1037 }
1038
1039 pub fn raw_edges(&self) -> &[Edge<E, Ix>] {
1041 &self.edges
1042 }
1043
1044 pub fn into_nodes_edges(self) -> (Vec<Node<N, Ix>>, Vec<Edge<E, Ix>>) {
1046 (self.nodes, self.edges)
1047 }
1048
1049 pub fn first_edge(&self, a: NodeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>> {
1051 match self.nodes.get(a.index()) {
1052 None => None,
1053 Some(node) => {
1054 let edix = node.next[dir.index()];
1055 if edix == EdgeIndex::end() {
1056 None
1057 } else {
1058 Some(edix)
1059 }
1060 }
1061 }
1062 }
1063
1064 pub fn next_edge(&self, e: EdgeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>> {
1066 match self.edges.get(e.index()) {
1067 None => None,
1068 Some(node) => {
1069 let edix = node.next[dir.index()];
1070 if edix == EdgeIndex::end() {
1071 None
1072 } else {
1073 Some(edix)
1074 }
1075 }
1076 }
1077 }
1078
1079 pub fn index_twice_mut<T, U>(
1113 &mut self,
1114 i: T,
1115 j: U,
1116 ) -> (
1117 &mut <Self as Index<T>>::Output,
1118 &mut <Self as Index<U>>::Output,
1119 )
1120 where
1121 Self: IndexMut<T> + IndexMut<U>,
1122 T: GraphIndex,
1123 U: GraphIndex,
1124 {
1125 assert!(T::is_node_index() != U::is_node_index() || i.index() != j.index());
1126
1127 unsafe {
1129 let self_mut = self as *mut _;
1130 (
1131 <Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
1132 <Self as IndexMut<U>>::index_mut(&mut *self_mut, j),
1133 )
1134 }
1135 }
1136
1137 pub fn reverse(&mut self) {
1139 for edge in &mut self.edges {
1143 edge.node.swap(0, 1);
1144 edge.next.swap(0, 1);
1145 }
1146 for node in &mut self.nodes {
1147 node.next.swap(0, 1);
1148 }
1149 }
1150
1151 pub fn clear(&mut self) {
1153 self.nodes.clear();
1154 self.edges.clear();
1155 }
1156
1157 pub fn clear_edges(&mut self) {
1159 self.edges.clear();
1160 for node in &mut self.nodes {
1161 node.next = [EdgeIndex::end(), EdgeIndex::end()];
1162 }
1163 }
1164
1165 pub fn capacity(&self) -> (usize, usize) {
1167 (self.nodes.capacity(), self.edges.capacity())
1168 }
1169
1170 pub fn reserve_nodes(&mut self, additional: usize) {
1175 self.nodes.reserve(additional);
1176 }
1177
1178 pub fn reserve_edges(&mut self, additional: usize) {
1183 self.edges.reserve(additional);
1184 }
1185
1186 pub fn reserve_exact_nodes(&mut self, additional: usize) {
1194 self.nodes.reserve_exact(additional);
1195 }
1196
1197 pub fn reserve_exact_edges(&mut self, additional: usize) {
1205 self.edges.reserve_exact(additional);
1206 }
1207
1208 pub fn shrink_to_fit_nodes(&mut self) {
1210 self.nodes.shrink_to_fit();
1211 }
1212
1213 pub fn shrink_to_fit_edges(&mut self) {
1215 self.edges.shrink_to_fit();
1216 }
1217
1218 pub fn shrink_to_fit(&mut self) {
1220 self.nodes.shrink_to_fit();
1221 self.edges.shrink_to_fit();
1222 }
1223
1224 pub fn retain_nodes<F>(&mut self, mut visit: F)
1232 where
1233 F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,
1234 {
1235 for index in self.node_indices().rev() {
1236 if !visit(Frozen(self), index) {
1237 let ret = self.remove_node(index);
1238 debug_assert!(ret.is_some());
1239 let _ = ret;
1240 }
1241 }
1242 }
1243
1244 pub fn retain_edges<F>(&mut self, mut visit: F)
1252 where
1253 F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,
1254 {
1255 for index in self.edge_indices().rev() {
1256 if !visit(Frozen(self), index) {
1257 let ret = self.remove_edge(index);
1258 debug_assert!(ret.is_some());
1259 let _ = ret;
1260 }
1261 }
1262 }
1263
1264 pub fn from_edges<I>(iterable: I) -> Self
1282 where
1283 I: IntoIterator,
1284 I::Item: IntoWeightedEdge<E>,
1285 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1286 N: Default,
1287 {
1288 let mut g = Self::with_capacity(0, 0);
1289 g.extend_with_edges(iterable);
1290 g
1291 }
1292
1293 pub fn extend_with_edges<I>(&mut self, iterable: I)
1301 where
1302 I: IntoIterator,
1303 I::Item: IntoWeightedEdge<E>,
1304 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1305 N: Default,
1306 {
1307 let iter = iterable.into_iter();
1308 let (low, _) = iter.size_hint();
1309 self.edges.reserve(low);
1310
1311 for elt in iter {
1312 let (source, target, weight) = elt.into_weighted_edge();
1313 let (source, target) = (source.into(), target.into());
1314 let nx = cmp::max(source, target);
1315 while nx.index() >= self.node_count() {
1316 self.add_node(N::default());
1317 }
1318 self.add_edge(source, target, weight);
1319 }
1320 }
1321
1322 pub fn map<'a, F, G, N2, E2>(
1328 &'a self,
1329 mut node_map: F,
1330 mut edge_map: G,
1331 ) -> Graph<N2, E2, Ty, Ix>
1332 where
1333 F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
1334 G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
1335 {
1336 let mut g = Graph::with_capacity(self.node_count(), self.edge_count());
1337 g.nodes.extend(enumerate(&self.nodes).map(|(i, node)| Node {
1338 weight: node_map(NodeIndex::new(i), &node.weight),
1339 next: node.next,
1340 }));
1341 g.edges.extend(enumerate(&self.edges).map(|(i, edge)| Edge {
1342 weight: edge_map(EdgeIndex::new(i), &edge.weight),
1343 next: edge.next,
1344 node: edge.node,
1345 }));
1346 g
1347 }
1348
1349 pub fn filter_map<'a, F, G, N2, E2>(
1362 &'a self,
1363 mut node_map: F,
1364 mut edge_map: G,
1365 ) -> Graph<N2, E2, Ty, Ix>
1366 where
1367 F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
1368 G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
1369 {
1370 let mut g = Graph::with_capacity(0, 0);
1371 let mut node_index_map = vec![NodeIndex::end(); self.node_count()];
1373 for (i, node) in enumerate(&self.nodes) {
1374 if let Some(nw) = node_map(NodeIndex::new(i), &node.weight) {
1375 node_index_map[i] = g.add_node(nw);
1376 }
1377 }
1378 for (i, edge) in enumerate(&self.edges) {
1379 let source = node_index_map[edge.source().index()];
1381 let target = node_index_map[edge.target().index()];
1382 if source != NodeIndex::end() && target != NodeIndex::end() {
1383 if let Some(ew) = edge_map(EdgeIndex::new(i), &edge.weight) {
1384 g.add_edge(source, target, ew);
1385 }
1386 }
1387 }
1388 g
1389 }
1390
1391 pub fn into_edge_type<NewTy>(self) -> Graph<N, E, NewTy, Ix>
1396 where
1397 NewTy: EdgeType,
1398 {
1399 Graph {
1400 nodes: self.nodes,
1401 edges: self.edges,
1402 ty: PhantomData,
1403 }
1404 }
1405
1406 #[cfg(feature = "serde-1")]
1410 fn link_edges(&mut self) -> Result<(), NodeIndex<Ix>> {
1412 for (edge_index, edge) in enumerate(&mut self.edges) {
1413 let a = edge.source();
1414 let b = edge.target();
1415 let edge_idx = EdgeIndex::new(edge_index);
1416 match index_twice(&mut self.nodes, a.index(), b.index()) {
1417 Pair::None => return Err(if a > b { a } else { b }),
1418 Pair::One(an) => {
1419 edge.next = an.next;
1420 an.next[0] = edge_idx;
1421 an.next[1] = edge_idx;
1422 }
1423 Pair::Both(an, bn) => {
1424 edge.next = [an.next[0], bn.next[1]];
1426 an.next[0] = edge_idx;
1427 bn.next[1] = edge_idx;
1428 }
1429 }
1430 }
1431 Ok(())
1432 }
1433}
1434
1435pub struct Externals<'a, N: 'a, Ty, Ix: IndexType = DefaultIx> {
1437 iter: iter::Enumerate<slice::Iter<'a, Node<N, Ix>>>,
1438 dir: Direction,
1439 ty: PhantomData<Ty>,
1440}
1441
1442impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix>
1443where
1444 Ty: EdgeType,
1445 Ix: IndexType,
1446{
1447 type Item = NodeIndex<Ix>;
1448 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1449 let k = self.dir.index();
1450 loop {
1451 match self.iter.next() {
1452 None => return None,
1453 Some((index, node)) => {
1454 if node.next[k] == EdgeIndex::end()
1455 && (Ty::is_directed() || node.next[1 - k] == EdgeIndex::end())
1456 {
1457 return Some(NodeIndex::new(index));
1458 } else {
1459 continue;
1460 }
1461 }
1462 }
1463 }
1464 }
1465}
1466
1467pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx> {
1478 skip_start: NodeIndex<Ix>,
1480 edges: &'a [Edge<E, Ix>],
1481 next: [EdgeIndex<Ix>; 2],
1482}
1483
1484impl<'a, E, Ix> Iterator for Neighbors<'a, E, Ix>
1485where
1486 Ix: IndexType,
1487{
1488 type Item = NodeIndex<Ix>;
1489
1490 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1491 match self.edges.get(self.next[0].index()) {
1493 None => {}
1494 Some(edge) => {
1495 self.next[0] = edge.next[0];
1496 return Some(edge.node[1]);
1497 }
1498 }
1499 while let Some(edge) = self.edges.get(self.next[1].index()) {
1504 self.next[1] = edge.next[1];
1505 if edge.node[0] != self.skip_start {
1506 return Some(edge.node[0]);
1507 }
1508 }
1509 None
1510 }
1511}
1512
1513impl<'a, E, Ix> Clone for Neighbors<'a, E, Ix>
1514where
1515 Ix: IndexType,
1516{
1517 clone_fields!(Neighbors, skip_start, edges, next,);
1518}
1519
1520impl<'a, E, Ix> Neighbors<'a, E, Ix>
1521where
1522 Ix: IndexType,
1523{
1524 pub fn detach(&self) -> WalkNeighbors<Ix> {
1530 WalkNeighbors {
1531 skip_start: self.skip_start,
1532 next: self.next,
1533 }
1534 }
1535}
1536
1537struct EdgesWalkerMut<'a, E: 'a, Ix: IndexType = DefaultIx> {
1538 edges: &'a mut [Edge<E, Ix>],
1539 next: EdgeIndex<Ix>,
1540 dir: Direction,
1541}
1542
1543fn edges_walker_mut<E, Ix>(
1544 edges: &mut [Edge<E, Ix>],
1545 next: EdgeIndex<Ix>,
1546 dir: Direction,
1547) -> EdgesWalkerMut<E, Ix>
1548where
1549 Ix: IndexType,
1550{
1551 EdgesWalkerMut { edges, next, dir }
1552}
1553
1554impl<'a, E, Ix> EdgesWalkerMut<'a, E, Ix>
1555where
1556 Ix: IndexType,
1557{
1558 fn next_edge(&mut self) -> Option<&mut Edge<E, Ix>> {
1559 self.next().map(|t| t.1)
1560 }
1561
1562 fn next(&mut self) -> Option<(EdgeIndex<Ix>, &mut Edge<E, Ix>)> {
1563 let this_index = self.next;
1564 let k = self.dir.index();
1565 match self.edges.get_mut(self.next.index()) {
1566 None => None,
1567 Some(edge) => {
1568 self.next = edge.next[k];
1569 Some((this_index, edge))
1570 }
1571 }
1572 }
1573}
1574
1575impl<'a, N, E, Ty, Ix> IntoEdges for &'a Graph<N, E, Ty, Ix>
1576where
1577 Ty: EdgeType,
1578 Ix: IndexType,
1579{
1580 type Edges = Edges<'a, E, Ty, Ix>;
1581 fn edges(self, a: Self::NodeId) -> Self::Edges {
1582 self.edges(a)
1583 }
1584}
1585
1586impl<'a, N, E, Ty, Ix> IntoEdgesDirected for &'a Graph<N, E, Ty, Ix>
1587where
1588 Ty: EdgeType,
1589 Ix: IndexType,
1590{
1591 type EdgesDirected = Edges<'a, E, Ty, Ix>;
1592 fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
1593 self.edges_directed(a, dir)
1594 }
1595}
1596
1597pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1599where
1600 Ty: EdgeType,
1601 Ix: IndexType,
1602{
1603 skip_start: NodeIndex<Ix>,
1605 edges: &'a [Edge<E, Ix>],
1606
1607 next: [EdgeIndex<Ix>; 2],
1609
1610 direction: Direction,
1613 ty: PhantomData<Ty>,
1614}
1615
1616impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1617where
1618 Ty: EdgeType,
1619 Ix: IndexType,
1620{
1621 type Item = EdgeReference<'a, E, Ix>;
1622
1623 fn next(&mut self) -> Option<Self::Item> {
1624 let (iterate_over, reverse) = if Ty::is_directed() {
1634 (Some(self.direction), None)
1635 } else {
1636 (None, Some(self.direction.opposite()))
1637 };
1638
1639 if iterate_over.unwrap_or(Outgoing) == Outgoing {
1640 let i = self.next[0].index();
1641 if let Some(Edge { node, weight, next }) = self.edges.get(i) {
1642 self.next[0] = next[0];
1643 return Some(EdgeReference {
1644 index: edge_index(i),
1645 node: if reverse == Some(Outgoing) {
1646 swap_pair(*node)
1647 } else {
1648 *node
1649 },
1650 weight,
1651 });
1652 }
1653 }
1654
1655 if iterate_over.unwrap_or(Incoming) == Incoming {
1656 while let Some(Edge { node, weight, next }) = self.edges.get(self.next[1].index()) {
1657 let edge_index = self.next[1];
1658 self.next[1] = next[1];
1659 if iterate_over.is_none() && node[0] == self.skip_start {
1662 continue;
1663 }
1664
1665 return Some(EdgeReference {
1666 index: edge_index,
1667 node: if reverse == Some(Incoming) {
1668 swap_pair(*node)
1669 } else {
1670 *node
1671 },
1672 weight,
1673 });
1674 }
1675 }
1676
1677 None
1678 }
1679}
1680
1681pub struct EdgesConnecting<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1683where
1684 Ty: EdgeType,
1685 Ix: IndexType,
1686{
1687 target_node: NodeIndex<Ix>,
1688 edges: Edges<'a, E, Ty, Ix>,
1689 ty: PhantomData<Ty>,
1690}
1691
1692impl<'a, E, Ty, Ix> Iterator for EdgesConnecting<'a, E, Ty, Ix>
1693where
1694 Ty: EdgeType,
1695 Ix: IndexType,
1696{
1697 type Item = EdgeReference<'a, E, Ix>;
1698
1699 fn next(&mut self) -> Option<EdgeReference<'a, E, Ix>> {
1700 while let Some(edge) = self.edges.next() {
1701 if edge.node[1] == self.target_node {
1702 return Some(edge);
1703 }
1704 }
1705
1706 None
1707 }
1708}
1709
1710fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1711 x.swap(0, 1);
1712 x
1713}
1714
1715impl<'a, E, Ty, Ix> Clone for Edges<'a, E, Ty, Ix>
1716where
1717 Ix: IndexType,
1718 Ty: EdgeType,
1719{
1720 fn clone(&self) -> Self {
1721 Edges {
1722 skip_start: self.skip_start,
1723 edges: self.edges,
1724 next: self.next,
1725 direction: self.direction,
1726 ty: self.ty,
1727 }
1728 }
1729}
1730
1731pub struct NodeWeightsMut<'a, N: 'a, Ix: IndexType = DefaultIx> {
1733 nodes: ::std::slice::IterMut<'a, Node<N, Ix>>,
1734}
1735
1736impl<'a, N, Ix> Iterator for NodeWeightsMut<'a, N, Ix>
1737where
1738 Ix: IndexType,
1739{
1740 type Item = &'a mut N;
1741
1742 fn next(&mut self) -> Option<&'a mut N> {
1743 self.nodes.next().map(|node| &mut node.weight)
1744 }
1745
1746 fn size_hint(&self) -> (usize, Option<usize>) {
1747 self.nodes.size_hint()
1748 }
1749}
1750
1751pub struct EdgeWeightsMut<'a, E: 'a, Ix: IndexType = DefaultIx> {
1753 edges: ::std::slice::IterMut<'a, Edge<E, Ix>>,
1754}
1755
1756impl<'a, E, Ix> Iterator for EdgeWeightsMut<'a, E, Ix>
1757where
1758 Ix: IndexType,
1759{
1760 type Item = &'a mut E;
1761
1762 fn next(&mut self) -> Option<&'a mut E> {
1763 self.edges.next().map(|edge| &mut edge.weight)
1764 }
1765
1766 fn size_hint(&self) -> (usize, Option<usize>) {
1767 self.edges.size_hint()
1768 }
1769}
1770
1771impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for Graph<N, E, Ty, Ix>
1775where
1776 Ty: EdgeType,
1777 Ix: IndexType,
1778{
1779 type Output = N;
1780 fn index(&self, index: NodeIndex<Ix>) -> &N {
1781 &self.nodes[index.index()].weight
1782 }
1783}
1784
1785impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for Graph<N, E, Ty, Ix>
1789where
1790 Ty: EdgeType,
1791 Ix: IndexType,
1792{
1793 fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1794 &mut self.nodes[index.index()].weight
1795 }
1796}
1797
1798impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix>
1802where
1803 Ty: EdgeType,
1804 Ix: IndexType,
1805{
1806 type Output = E;
1807 fn index(&self, index: EdgeIndex<Ix>) -> &E {
1808 &self.edges[index.index()].weight
1809 }
1810}
1811
1812impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix>
1816where
1817 Ty: EdgeType,
1818 Ix: IndexType,
1819{
1820 fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
1821 &mut self.edges[index.index()].weight
1822 }
1823}
1824
1825impl<N, E, Ty, Ix> Default for Graph<N, E, Ty, Ix>
1827where
1828 Ty: EdgeType,
1829 Ix: IndexType,
1830{
1831 fn default() -> Self {
1832 Self::with_capacity(0, 0)
1833 }
1834}
1835
1836pub trait GraphIndex: Copy {
1838 #[doc(hidden)]
1839 fn index(&self) -> usize;
1840 #[doc(hidden)]
1841 fn is_node_index() -> bool;
1842}
1843
1844impl<Ix: IndexType> GraphIndex for NodeIndex<Ix> {
1845 #[inline]
1846 fn index(&self) -> usize {
1847 NodeIndex::index(*self)
1848 }
1849 #[inline]
1850 fn is_node_index() -> bool {
1851 true
1852 }
1853}
1854
1855impl<Ix: IndexType> GraphIndex for EdgeIndex<Ix> {
1856 #[inline]
1857 fn index(&self) -> usize {
1858 EdgeIndex::index(*self)
1859 }
1860 #[inline]
1861 fn is_node_index() -> bool {
1862 false
1863 }
1864}
1865
1866pub struct WalkNeighbors<Ix> {
1902 skip_start: NodeIndex<Ix>,
1903 next: [EdgeIndex<Ix>; 2],
1904}
1905
1906impl<Ix> Clone for WalkNeighbors<Ix>
1907where
1908 Ix: IndexType,
1909{
1910 fn clone(&self) -> Self {
1911 WalkNeighbors {
1912 skip_start: self.skip_start,
1913 next: self.next,
1914 }
1915 }
1916}
1917
1918impl<Ix: IndexType> WalkNeighbors<Ix> {
1919 pub fn next<N, E, Ty: EdgeType>(
1926 &mut self,
1927 g: &Graph<N, E, Ty, Ix>,
1928 ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
1929 match g.edges.get(self.next[0].index()) {
1931 None => {}
1932 Some(edge) => {
1933 let ed = self.next[0];
1934 self.next[0] = edge.next[0];
1935 return Some((ed, edge.node[1]));
1936 }
1937 }
1938 while let Some(edge) = g.edges.get(self.next[1].index()) {
1943 let ed = self.next[1];
1944 self.next[1] = edge.next[1];
1945 if edge.node[0] != self.skip_start {
1946 return Some((ed, edge.node[0]));
1947 }
1948 }
1949 None
1950 }
1951
1952 pub fn next_node<N, E, Ty: EdgeType>(
1953 &mut self,
1954 g: &Graph<N, E, Ty, Ix>,
1955 ) -> Option<NodeIndex<Ix>> {
1956 self.next(g).map(|t| t.1)
1957 }
1958
1959 pub fn next_edge<N, E, Ty: EdgeType>(
1960 &mut self,
1961 g: &Graph<N, E, Ty, Ix>,
1962 ) -> Option<EdgeIndex<Ix>> {
1963 self.next(g).map(|t| t.0)
1964 }
1965}
1966
1967#[derive(Clone, Debug)]
1969pub struct NodeIndices<Ix = DefaultIx> {
1970 r: Range<usize>,
1971 ty: PhantomData<fn() -> Ix>,
1972}
1973
1974impl<Ix: IndexType> Iterator for NodeIndices<Ix> {
1975 type Item = NodeIndex<Ix>;
1976
1977 fn next(&mut self) -> Option<Self::Item> {
1978 self.r.next().map(node_index)
1979 }
1980
1981 fn size_hint(&self) -> (usize, Option<usize>) {
1982 self.r.size_hint()
1983 }
1984}
1985
1986impl<Ix: IndexType> DoubleEndedIterator for NodeIndices<Ix> {
1987 fn next_back(&mut self) -> Option<Self::Item> {
1988 self.r.next_back().map(node_index)
1989 }
1990}
1991
1992impl<Ix: IndexType> ExactSizeIterator for NodeIndices<Ix> {}
1993
1994#[derive(Clone, Debug)]
1996pub struct EdgeIndices<Ix = DefaultIx> {
1997 r: Range<usize>,
1998 ty: PhantomData<fn() -> Ix>,
1999}
2000
2001impl<Ix: IndexType> Iterator for EdgeIndices<Ix> {
2002 type Item = EdgeIndex<Ix>;
2003
2004 fn next(&mut self) -> Option<Self::Item> {
2005 self.r.next().map(edge_index)
2006 }
2007
2008 fn size_hint(&self) -> (usize, Option<usize>) {
2009 self.r.size_hint()
2010 }
2011}
2012
2013impl<Ix: IndexType> DoubleEndedIterator for EdgeIndices<Ix> {
2014 fn next_back(&mut self) -> Option<Self::Item> {
2015 self.r.next_back().map(edge_index)
2016 }
2017}
2018
2019impl<Ix: IndexType> ExactSizeIterator for EdgeIndices<Ix> {}
2020
2021#[derive(Debug)]
2023pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
2024 index: EdgeIndex<Ix>,
2025 node: [NodeIndex<Ix>; 2],
2026 weight: &'a E,
2027}
2028
2029impl<'a, E, Ix: IndexType> Clone for EdgeReference<'a, E, Ix> {
2030 fn clone(&self) -> Self {
2031 *self
2032 }
2033}
2034
2035impl<'a, E, Ix: IndexType> Copy for EdgeReference<'a, E, Ix> {}
2036
2037impl<'a, E, Ix: IndexType> PartialEq for EdgeReference<'a, E, Ix>
2038where
2039 E: PartialEq,
2040{
2041 fn eq(&self, rhs: &Self) -> bool {
2042 self.index == rhs.index && self.weight == rhs.weight
2043 }
2044}
2045
2046impl<'a, N, E, Ty, Ix> IntoNodeReferences for &'a Graph<N, E, Ty, Ix>
2047where
2048 Ty: EdgeType,
2049 Ix: IndexType,
2050{
2051 type NodeRef = (NodeIndex<Ix>, &'a N);
2052 type NodeReferences = NodeReferences<'a, N, Ix>;
2053 fn node_references(self) -> Self::NodeReferences {
2054 NodeReferences {
2055 iter: self.nodes.iter().enumerate(),
2056 }
2057 }
2058}
2059
2060pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
2062 iter: iter::Enumerate<slice::Iter<'a, Node<N, Ix>>>,
2063}
2064
2065impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
2066where
2067 Ix: IndexType,
2068{
2069 type Item = (NodeIndex<Ix>, &'a N);
2070
2071 fn next(&mut self) -> Option<Self::Item> {
2072 self.iter
2073 .next()
2074 .map(|(i, node)| (node_index(i), &node.weight))
2075 }
2076
2077 fn size_hint(&self) -> (usize, Option<usize>) {
2078 self.iter.size_hint()
2079 }
2080}
2081
2082impl<'a, N, Ix> DoubleEndedIterator for NodeReferences<'a, N, Ix>
2083where
2084 Ix: IndexType,
2085{
2086 fn next_back(&mut self) -> Option<Self::Item> {
2087 self.iter
2088 .next_back()
2089 .map(|(i, node)| (node_index(i), &node.weight))
2090 }
2091}
2092
2093impl<'a, N, Ix> ExactSizeIterator for NodeReferences<'a, N, Ix> where Ix: IndexType {}
2094
2095impl<'a, Ix, E> EdgeReference<'a, E, Ix>
2096where
2097 Ix: IndexType,
2098{
2099 pub fn weight(&self) -> &'a E {
2104 self.weight
2105 }
2106}
2107
2108impl<'a, Ix, E> EdgeRef for EdgeReference<'a, E, Ix>
2109where
2110 Ix: IndexType,
2111{
2112 type NodeId = NodeIndex<Ix>;
2113 type EdgeId = EdgeIndex<Ix>;
2114 type Weight = E;
2115
2116 fn source(&self) -> Self::NodeId {
2117 self.node[0]
2118 }
2119 fn target(&self) -> Self::NodeId {
2120 self.node[1]
2121 }
2122 fn weight(&self) -> &E {
2123 self.weight
2124 }
2125 fn id(&self) -> Self::EdgeId {
2126 self.index
2127 }
2128}
2129
2130pub struct EdgeReferences<'a, E: 'a, Ix: IndexType = DefaultIx> {
2132 iter: iter::Enumerate<slice::Iter<'a, Edge<E, Ix>>>,
2133}
2134
2135impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
2136where
2137 Ix: IndexType,
2138{
2139 type Item = EdgeReference<'a, E, Ix>;
2140
2141 fn next(&mut self) -> Option<Self::Item> {
2142 self.iter.next().map(|(i, edge)| EdgeReference {
2143 index: edge_index(i),
2144 node: edge.node,
2145 weight: &edge.weight,
2146 })
2147 }
2148
2149 fn size_hint(&self) -> (usize, Option<usize>) {
2150 self.iter.size_hint()
2151 }
2152}
2153
2154impl<'a, E, Ix> DoubleEndedIterator for EdgeReferences<'a, E, Ix>
2155where
2156 Ix: IndexType,
2157{
2158 fn next_back(&mut self) -> Option<Self::Item> {
2159 self.iter.next_back().map(|(i, edge)| EdgeReference {
2160 index: edge_index(i),
2161 node: edge.node,
2162 weight: &edge.weight,
2163 })
2164 }
2165}
2166
2167impl<'a, E, Ix> ExactSizeIterator for EdgeReferences<'a, E, Ix> where Ix: IndexType {}
2168
2169mod frozen;
2170#[cfg(feature = "stable_graph")]
2171pub mod stable_graph;
2172
2173pub struct Frozen<'a, G: 'a>(&'a mut G);