1#[cfg(feature = "std")]
2use std::{
3 cmp::{self, max},
4 fmt,
5 hash::Hash,
6 iter,
7 marker::PhantomData,
8 mem::size_of,
9 ops::{Index, IndexMut, Range},
10 slice, u16, u32, u8, usize,
11};
12
13#[cfg(not(feature = "std"))]
14use core::{
15 cmp::{self, max},
16 fmt,
17 hash::Hash,
18 iter,
19 marker::PhantomData,
20 mem::size_of,
21 ops::{Index, IndexMut, Range},
22 slice, u16, u32, u8, usize,
23};
24
25#[cfg(not(feature = "std"))]
26use alloc::vec::Vec;
27
28use crate::{Directed, Direction, EdgeType, Incoming, IntoWeightedEdge, Outgoing, Undirected};
29
30use crate::iter_format::{DebugMap, IterFormatExt, NoPretty};
31
32use crate::util::enumerate;
33use crate::visit::EdgeRef;
34use crate::visit::{IntoEdges, IntoEdgesDirected, IntoNodeReferences};
35
36#[cfg(feature = "serde-1")]
37mod serialization;
38
39pub type DefaultIx = u32;
46
47pub unsafe trait IndexType: Copy + Default + Hash + Ord + fmt::Debug + 'static {
52 fn new(x: usize) -> Self;
53 fn index(&self) -> usize;
54 fn max() -> Self;
55}
56
57unsafe impl IndexType for usize {
58 #[inline(always)]
59 fn new(x: usize) -> Self {
60 x
61 }
62 #[inline(always)]
63 fn index(&self) -> Self {
64 *self
65 }
66 #[inline(always)]
67 fn max() -> Self {
68 usize::MAX
69 }
70}
71
72unsafe impl IndexType for u32 {
73 #[inline(always)]
74 fn new(x: usize) -> Self {
75 x as u32
76 }
77 #[inline(always)]
78 fn index(&self) -> usize {
79 *self as usize
80 }
81 #[inline(always)]
82 fn max() -> Self {
83 u32::MAX
84 }
85}
86
87unsafe impl IndexType for u16 {
88 #[inline(always)]
89 fn new(x: usize) -> Self {
90 x as u16
91 }
92 #[inline(always)]
93 fn index(&self) -> usize {
94 *self as usize
95 }
96 #[inline(always)]
97 fn max() -> Self {
98 u16::MAX
99 }
100}
101
102unsafe impl IndexType for u8 {
103 #[inline(always)]
104 fn new(x: usize) -> Self {
105 x as u8
106 }
107 #[inline(always)]
108 fn index(&self) -> usize {
109 *self as usize
110 }
111 #[inline(always)]
112 fn max() -> Self {
113 u8::MAX
114 }
115}
116
117#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
119pub struct NodeIndex<Ix = DefaultIx>(Ix);
120
121impl<Ix: IndexType> NodeIndex<Ix> {
122 #[inline]
123 pub fn new(x: usize) -> Self {
124 NodeIndex(IndexType::new(x))
125 }
126
127 #[inline]
128 pub fn index(self) -> usize {
129 self.0.index()
130 }
131
132 #[inline]
133 pub fn end() -> Self {
134 NodeIndex(IndexType::max())
135 }
136
137 fn _into_edge(self) -> EdgeIndex<Ix> {
138 EdgeIndex(self.0)
139 }
140}
141
142unsafe impl<Ix: IndexType> IndexType for NodeIndex<Ix> {
143 fn index(&self) -> usize {
144 self.0.index()
145 }
146 fn new(x: usize) -> Self {
147 NodeIndex::new(x)
148 }
149 fn max() -> Self {
150 NodeIndex(<Ix as IndexType>::max())
151 }
152}
153
154impl<Ix: IndexType> From<Ix> for NodeIndex<Ix> {
155 fn from(ix: Ix) -> Self {
156 NodeIndex(ix)
157 }
158}
159
160impl<Ix: fmt::Debug> fmt::Debug for NodeIndex<Ix> {
161 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
162 write!(f, "NodeIndex({:?})", self.0)
163 }
164}
165
166pub fn node_index<Ix: IndexType>(index: usize) -> NodeIndex<Ix> {
168 NodeIndex::new(index)
169}
170
171pub fn edge_index<Ix: IndexType>(index: usize) -> EdgeIndex<Ix> {
173 EdgeIndex::new(index)
174}
175
176#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
178pub struct EdgeIndex<Ix = DefaultIx>(Ix);
179
180impl<Ix: IndexType> EdgeIndex<Ix> {
181 #[inline]
182 pub fn new(x: usize) -> Self {
183 EdgeIndex(IndexType::new(x))
184 }
185
186 #[inline]
187 pub fn index(self) -> usize {
188 self.0.index()
189 }
190
191 #[inline]
194 pub fn end() -> Self {
195 EdgeIndex(IndexType::max())
196 }
197
198 fn _into_node(self) -> NodeIndex<Ix> {
199 NodeIndex(self.0)
200 }
201}
202
203impl<Ix: IndexType> From<Ix> for EdgeIndex<Ix> {
204 fn from(ix: Ix) -> Self {
205 EdgeIndex(ix)
206 }
207}
208
209impl<Ix: fmt::Debug> fmt::Debug for EdgeIndex<Ix> {
210 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
211 write!(f, "EdgeIndex({:?})", self.0)
212 }
213}
214const DIRECTIONS: [Direction; 2] = [Outgoing, Incoming];
231
232#[derive(Debug)]
234pub struct Node<N, Ix = DefaultIx> {
235 pub weight: N,
237 next: [EdgeIndex<Ix>; 2],
239}
240
241impl<E, Ix> Clone for Node<E, Ix>
242where
243 E: Clone,
244 Ix: Copy,
245{
246 clone_fields!(Node, weight, next,);
247}
248
249impl<N, Ix: IndexType> Node<N, Ix> {
250 pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix> {
252 self.next[dir.index()]
253 }
254}
255
256#[derive(Debug)]
258pub struct Edge<E, Ix = DefaultIx> {
259 pub weight: E,
261 next: [EdgeIndex<Ix>; 2],
263 node: [NodeIndex<Ix>; 2],
265}
266
267impl<E, Ix> Clone for Edge<E, Ix>
268where
269 E: Clone,
270 Ix: Copy,
271{
272 clone_fields!(Edge, weight, next, node,);
273}
274
275impl<E, Ix: IndexType> Edge<E, Ix> {
276 pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix> {
278 self.next[dir.index()]
279 }
280
281 pub fn source(&self) -> NodeIndex<Ix> {
283 self.node[0]
284 }
285
286 pub fn target(&self) -> NodeIndex<Ix> {
288 self.node[1]
289 }
290}
291
292pub struct Graph<N, E, Ty = Directed, Ix = DefaultIx> {
363 nodes: Vec<Node<N, Ix>>,
364 edges: Vec<Edge<E, Ix>>,
365 ty: PhantomData<Ty>,
366}
367
368pub type DiGraph<N, E, Ix = DefaultIx> = Graph<N, E, Directed, Ix>;
373
374pub type UnGraph<N, E, Ix = DefaultIx> = Graph<N, E, Undirected, Ix>;
379
380impl<N, E, Ty, Ix: IndexType> Clone for Graph<N, E, Ty, Ix>
382where
383 N: Clone,
384 E: Clone,
385{
386 fn clone(&self) -> Self {
387 Graph {
388 nodes: self.nodes.clone(),
389 edges: self.edges.clone(),
390 ty: self.ty,
391 }
392 }
393
394 fn clone_from(&mut self, rhs: &Self) {
395 self.nodes.clone_from(&rhs.nodes);
396 self.edges.clone_from(&rhs.edges);
397 self.ty = rhs.ty;
398 }
399}
400
401impl<N, E, Ty, Ix> fmt::Debug for Graph<N, E, Ty, Ix>
402where
403 N: fmt::Debug,
404 E: fmt::Debug,
405 Ty: EdgeType,
406 Ix: IndexType,
407{
408 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
409 let etype = if self.is_directed() {
410 "Directed"
411 } else {
412 "Undirected"
413 };
414 let mut fmt_struct = f.debug_struct("Graph");
415 fmt_struct.field("Ty", &etype);
416 fmt_struct.field("node_count", &self.node_count());
417 fmt_struct.field("edge_count", &self.edge_count());
418 if self.edge_count() > 0 {
419 fmt_struct.field(
420 "edges",
421 &self
422 .edges
423 .iter()
424 .map(|e| NoPretty((e.source().index(), e.target().index())))
425 .format(", "),
426 );
427 }
428 if size_of::<N>() != 0 {
430 fmt_struct.field(
431 "node weights",
432 &DebugMap(|| self.nodes.iter().map(|n| &n.weight).enumerate()),
433 );
434 }
435 if size_of::<E>() != 0 {
436 fmt_struct.field(
437 "edge weights",
438 &DebugMap(|| self.edges.iter().map(|n| &n.weight).enumerate()),
439 );
440 }
441 fmt_struct.finish()
442 }
443}
444
445enum Pair<T> {
446 Both(T, T),
447 One(T),
448 None,
449}
450
451fn index_twice<T>(slc: &mut [T], a: usize, b: usize) -> Pair<&mut T> {
453 if max(a, b) >= slc.len() {
454 Pair::None
455 } else if a == b {
456 Pair::One(&mut slc[max(a, b)])
457 } else {
458 unsafe {
460 let ar = &mut *(slc.get_unchecked_mut(a) as *mut _);
461 let br = &mut *(slc.get_unchecked_mut(b) as *mut _);
462 Pair::Both(ar, br)
463 }
464 }
465}
466
467impl<N, E> Graph<N, E, Directed> {
468 pub fn new() -> Self {
473 Graph {
474 nodes: Vec::new(),
475 edges: Vec::new(),
476 ty: PhantomData,
477 }
478 }
479}
480
481impl<N, E> Graph<N, E, Undirected> {
482 pub fn new_undirected() -> Self {
487 Graph {
488 nodes: Vec::new(),
489 edges: Vec::new(),
490 ty: PhantomData,
491 }
492 }
493}
494
495impl<N, E, Ty, Ix> Graph<N, E, Ty, Ix>
496where
497 Ty: EdgeType,
498 Ix: IndexType,
499{
500 pub fn with_capacity(nodes: usize, edges: usize) -> Self {
502 Graph {
503 nodes: Vec::with_capacity(nodes),
504 edges: Vec::with_capacity(edges),
505 ty: PhantomData,
506 }
507 }
508
509 pub fn node_count(&self) -> usize {
513 self.nodes.len()
514 }
515
516 pub fn edge_count(&self) -> usize {
520 self.edges.len()
521 }
522
523 #[inline]
525 pub fn is_directed(&self) -> bool {
526 Ty::is_directed()
527 }
528
529 pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
538 let node = Node {
539 weight,
540 next: [EdgeIndex::end(), EdgeIndex::end()],
541 };
542 let node_idx = NodeIndex::new(self.nodes.len());
543 assert!(<Ix as IndexType>::max().index() == !0 || NodeIndex::end() != node_idx);
545 self.nodes.push(node);
546 node_idx
547 }
548
549 pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
553 self.nodes.get(a.index()).map(|n| &n.weight)
554 }
555
556 pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
560 self.nodes.get_mut(a.index()).map(|n| &mut n.weight)
561 }
562
563 pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
577 let edge_idx = EdgeIndex::new(self.edges.len());
578 assert!(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx);
579 let mut edge = Edge {
580 weight,
581 node: [a, b],
582 next: [EdgeIndex::end(); 2],
583 };
584 match index_twice(&mut self.nodes, a.index(), b.index()) {
585 Pair::None => panic!("Graph::add_edge: node indices out of bounds"),
586 Pair::One(an) => {
587 edge.next = an.next;
588 an.next[0] = edge_idx;
589 an.next[1] = edge_idx;
590 }
591 Pair::Both(an, bn) => {
592 edge.next = [an.next[0], bn.next[1]];
594 an.next[0] = edge_idx;
595 bn.next[1] = edge_idx;
596 }
597 }
598 self.edges.push(edge);
599 edge_idx
600 }
601
602 pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
612 if let Some(ix) = self.find_edge(a, b) {
613 if let Some(ed) = self.edge_weight_mut(ix) {
614 *ed = weight;
615 return ix;
616 }
617 }
618 self.add_edge(a, b, weight)
619 }
620
621 pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
625 self.edges.get(e.index()).map(|ed| &ed.weight)
626 }
627
628 pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
632 self.edges.get_mut(e.index()).map(|ed| &mut ed.weight)
633 }
634
635 pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)> {
637 self.edges
638 .get(e.index())
639 .map(|ed| (ed.source(), ed.target()))
640 }
641
642 pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N> {
655 self.nodes.get(a.index())?;
656 for d in &DIRECTIONS {
657 let k = d.index();
658
659 loop {
661 let next = self.nodes[a.index()].next[k];
662 if next == EdgeIndex::end() {
663 break;
664 }
665 let ret = self.remove_edge(next);
666 debug_assert!(ret.is_some());
667 let _ = ret;
668 }
669 }
670
671 let node = self.nodes.swap_remove(a.index());
675
676 let swap_edges = match self.nodes.get(a.index()) {
679 None => return Some(node.weight),
680 Some(ed) => ed.next,
681 };
682
683 let old_index = NodeIndex::new(self.nodes.len());
685 let new_index = a;
686
687 for &d in &DIRECTIONS {
689 let k = d.index();
690 let mut edges = edges_walker_mut(&mut self.edges, swap_edges[k], d);
691 while let Some(curedge) = edges.next_edge() {
692 debug_assert!(curedge.node[k] == old_index);
693 curedge.node[k] = new_index;
694 }
695 }
696 Some(node.weight)
697 }
698
699 fn change_edge_links(
702 &mut self,
703 edge_node: [NodeIndex<Ix>; 2],
704 e: EdgeIndex<Ix>,
705 edge_next: [EdgeIndex<Ix>; 2],
706 ) {
707 for &d in &DIRECTIONS {
708 let k = d.index();
709 let node = match self.nodes.get_mut(edge_node[k].index()) {
710 Some(r) => r,
711 None => {
712 debug_assert!(
713 false,
714 "Edge's endpoint dir={:?} index={:?} not found",
715 d, edge_node[k]
716 );
717 return;
718 }
719 };
720 let fst = node.next[k];
721 if fst == e {
722 node.next[k] = edge_next[k];
724 } else {
725 let mut edges = edges_walker_mut(&mut self.edges, fst, d);
726 while let Some(curedge) = edges.next_edge() {
727 if curedge.next[k] == e {
728 curedge.next[k] = edge_next[k];
729 break; }
731 }
732 }
733 }
734 }
735
736 pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
744 let (edge_node, edge_next) = match self.edges.get(e.index()) {
748 None => return None,
749 Some(x) => (x.node, x.next),
750 };
751 self.change_edge_links(edge_node, e, edge_next);
754 self.remove_edge_adjust_indices(e)
755 }
756
757 fn remove_edge_adjust_indices(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
758 let edge = self.edges.swap_remove(e.index());
762 let swap = match self.edges.get(e.index()) {
763 None => return Some(edge.weight),
765 Some(ed) => ed.node,
766 };
767 let swapped_e = EdgeIndex::new(self.edges.len());
768
769 self.change_edge_links(swap, swapped_e, [e, e]);
772 Some(edge.weight)
773 }
774
775 pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
788 self.neighbors_directed(a, Outgoing)
789 }
790
791 pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix> {
811 let mut iter = self.neighbors_undirected(a);
812 if self.is_directed() {
813 let k = dir.index();
814 iter.next[1 - k] = EdgeIndex::end();
815 iter.skip_start = NodeIndex::end();
816 }
817 iter
818 }
819
820 pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
835 Neighbors {
836 skip_start: a,
837 edges: &self.edges,
838 next: match self.nodes.get(a.index()) {
839 None => [EdgeIndex::end(), EdgeIndex::end()],
840 Some(n) => n.next,
841 },
842 }
843 }
844
845 pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
853 self.edges_directed(a, Outgoing)
854 }
855
856 pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix> {
868 Edges {
869 skip_start: a,
870 edges: &self.edges,
871 direction: dir,
872 next: match self.nodes.get(a.index()) {
873 None => [EdgeIndex::end(), EdgeIndex::end()],
874 Some(n) => n.next,
875 },
876 ty: PhantomData,
877 }
878 }
879
880 pub fn edges_connecting(
887 &self,
888 a: NodeIndex<Ix>,
889 b: NodeIndex<Ix>,
890 ) -> EdgesConnecting<E, Ty, Ix> {
891 EdgesConnecting {
892 target_node: b,
893 edges: self.edges_directed(a, Direction::Outgoing),
894 ty: PhantomData,
895 }
896 }
897
898 pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
903 self.find_edge(a, b).is_some()
904 }
905
906 pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>> {
911 if !self.is_directed() {
912 self.find_edge_undirected(a, b).map(|(ix, _)| ix)
913 } else {
914 match self.nodes.get(a.index()) {
915 None => None,
916 Some(node) => self.find_edge_directed_from_node(node, b),
917 }
918 }
919 }
920
921 fn find_edge_directed_from_node(
922 &self,
923 node: &Node<N, Ix>,
924 b: NodeIndex<Ix>,
925 ) -> Option<EdgeIndex<Ix>> {
926 let mut edix = node.next[0];
927 while let Some(edge) = self.edges.get(edix.index()) {
928 if edge.node[1] == b {
929 return Some(edix);
930 }
931 edix = edge.next[0];
932 }
933 None
934 }
935
936 pub fn find_edge_undirected(
944 &self,
945 a: NodeIndex<Ix>,
946 b: NodeIndex<Ix>,
947 ) -> Option<(EdgeIndex<Ix>, Direction)> {
948 match self.nodes.get(a.index()) {
949 None => None,
950 Some(node) => self.find_edge_undirected_from_node(node, b),
951 }
952 }
953
954 fn find_edge_undirected_from_node(
955 &self,
956 node: &Node<N, Ix>,
957 b: NodeIndex<Ix>,
958 ) -> Option<(EdgeIndex<Ix>, Direction)> {
959 for &d in &DIRECTIONS {
960 let k = d.index();
961 let mut edix = node.next[k];
962 while let Some(edge) = self.edges.get(edix.index()) {
963 if edge.node[1 - k] == b {
964 return Some((edix, d));
965 }
966 edix = edge.next[k];
967 }
968 }
969 None
970 }
971
972 pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix> {
984 Externals {
985 iter: self.nodes.iter().enumerate(),
986 dir,
987 ty: PhantomData,
988 }
989 }
990
991 pub fn node_indices(&self) -> NodeIndices<Ix> {
1004 NodeIndices {
1005 r: 0..self.node_count(),
1006 ty: PhantomData,
1007 }
1008 }
1009
1010 pub fn node_weights_mut(&mut self) -> NodeWeightsMut<N, Ix> {
1015 NodeWeightsMut {
1016 nodes: self.nodes.iter_mut(),
1017 }
1018 }
1019
1020 pub fn edge_indices(&self) -> EdgeIndices<Ix> {
1022 EdgeIndices {
1023 r: 0..self.edge_count(),
1024 ty: PhantomData,
1025 }
1026 }
1027
1028 pub fn edge_references(&self) -> EdgeReferences<E, Ix> {
1032 EdgeReferences {
1033 iter: self.edges.iter().enumerate(),
1034 }
1035 }
1036
1037 pub fn edge_weights_mut(&mut self) -> EdgeWeightsMut<E, Ix> {
1042 EdgeWeightsMut {
1043 edges: self.edges.iter_mut(),
1044 }
1045 }
1046
1047 pub fn raw_nodes(&self) -> &[Node<N, Ix>] {
1052 &self.nodes
1053 }
1054
1055 pub fn raw_edges(&self) -> &[Edge<E, Ix>] {
1057 &self.edges
1058 }
1059
1060 pub fn into_nodes_edges(self) -> (Vec<Node<N, Ix>>, Vec<Edge<E, Ix>>) {
1062 (self.nodes, self.edges)
1063 }
1064
1065 pub fn first_edge(&self, a: NodeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>> {
1067 match self.nodes.get(a.index()) {
1068 None => None,
1069 Some(node) => {
1070 let edix = node.next[dir.index()];
1071 if edix == EdgeIndex::end() {
1072 None
1073 } else {
1074 Some(edix)
1075 }
1076 }
1077 }
1078 }
1079
1080 pub fn next_edge(&self, e: EdgeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>> {
1082 match self.edges.get(e.index()) {
1083 None => None,
1084 Some(node) => {
1085 let edix = node.next[dir.index()];
1086 if edix == EdgeIndex::end() {
1087 None
1088 } else {
1089 Some(edix)
1090 }
1091 }
1092 }
1093 }
1094
1095 pub fn index_twice_mut<T, U>(
1129 &mut self,
1130 i: T,
1131 j: U,
1132 ) -> (
1133 &mut <Self as Index<T>>::Output,
1134 &mut <Self as Index<U>>::Output,
1135 )
1136 where
1137 Self: IndexMut<T> + IndexMut<U>,
1138 T: GraphIndex,
1139 U: GraphIndex,
1140 {
1141 assert!(T::is_node_index() != U::is_node_index() || i.index() != j.index());
1142
1143 unsafe {
1145 let self_mut = self as *mut _;
1146 (
1147 <Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
1148 <Self as IndexMut<U>>::index_mut(&mut *self_mut, j),
1149 )
1150 }
1151 }
1152
1153 pub fn reverse(&mut self) {
1155 for edge in &mut self.edges {
1159 edge.node.swap(0, 1);
1160 edge.next.swap(0, 1);
1161 }
1162 for node in &mut self.nodes {
1163 node.next.swap(0, 1);
1164 }
1165 }
1166
1167 pub fn clear(&mut self) {
1169 self.nodes.clear();
1170 self.edges.clear();
1171 }
1172
1173 pub fn clear_edges(&mut self) {
1175 self.edges.clear();
1176 for node in &mut self.nodes {
1177 node.next = [EdgeIndex::end(), EdgeIndex::end()];
1178 }
1179 }
1180
1181 pub fn capacity(&self) -> (usize, usize) {
1183 (self.nodes.capacity(), self.edges.capacity())
1184 }
1185
1186 pub fn reserve_nodes(&mut self, additional: usize) {
1191 self.nodes.reserve(additional);
1192 }
1193
1194 pub fn reserve_edges(&mut self, additional: usize) {
1199 self.edges.reserve(additional);
1200 }
1201
1202 pub fn reserve_exact_nodes(&mut self, additional: usize) {
1210 self.nodes.reserve_exact(additional);
1211 }
1212
1213 pub fn reserve_exact_edges(&mut self, additional: usize) {
1221 self.edges.reserve_exact(additional);
1222 }
1223
1224 pub fn shrink_to_fit_nodes(&mut self) {
1226 self.nodes.shrink_to_fit();
1227 }
1228
1229 pub fn shrink_to_fit_edges(&mut self) {
1231 self.edges.shrink_to_fit();
1232 }
1233
1234 pub fn shrink_to_fit(&mut self) {
1236 self.nodes.shrink_to_fit();
1237 self.edges.shrink_to_fit();
1238 }
1239
1240 pub fn retain_nodes<F>(&mut self, mut visit: F)
1248 where
1249 F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,
1250 {
1251 for index in self.node_indices().rev() {
1252 if !visit(Frozen(self), index) {
1253 let ret = self.remove_node(index);
1254 debug_assert!(ret.is_some());
1255 let _ = ret;
1256 }
1257 }
1258 }
1259
1260 pub fn retain_edges<F>(&mut self, mut visit: F)
1268 where
1269 F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,
1270 {
1271 for index in self.edge_indices().rev() {
1272 if !visit(Frozen(self), index) {
1273 let ret = self.remove_edge(index);
1274 debug_assert!(ret.is_some());
1275 let _ = ret;
1276 }
1277 }
1278 }
1279
1280 pub fn from_edges<I>(iterable: I) -> Self
1298 where
1299 I: IntoIterator,
1300 I::Item: IntoWeightedEdge<E>,
1301 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1302 N: Default,
1303 {
1304 let mut g = Self::with_capacity(0, 0);
1305 g.extend_with_edges(iterable);
1306 g
1307 }
1308
1309 pub fn extend_with_edges<I>(&mut self, iterable: I)
1317 where
1318 I: IntoIterator,
1319 I::Item: IntoWeightedEdge<E>,
1320 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1321 N: Default,
1322 {
1323 let iter = iterable.into_iter();
1324 let (low, _) = iter.size_hint();
1325 self.edges.reserve(low);
1326
1327 for elt in iter {
1328 let (source, target, weight) = elt.into_weighted_edge();
1329 let (source, target) = (source.into(), target.into());
1330 let nx = cmp::max(source, target);
1331 while nx.index() >= self.node_count() {
1332 self.add_node(N::default());
1333 }
1334 self.add_edge(source, target, weight);
1335 }
1336 }
1337
1338 pub fn map<'a, F, G, N2, E2>(
1344 &'a self,
1345 mut node_map: F,
1346 mut edge_map: G,
1347 ) -> Graph<N2, E2, Ty, Ix>
1348 where
1349 F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
1350 G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
1351 {
1352 let mut g = Graph::with_capacity(self.node_count(), self.edge_count());
1353 g.nodes.extend(enumerate(&self.nodes).map(|(i, node)| Node {
1354 weight: node_map(NodeIndex::new(i), &node.weight),
1355 next: node.next,
1356 }));
1357 g.edges.extend(enumerate(&self.edges).map(|(i, edge)| Edge {
1358 weight: edge_map(EdgeIndex::new(i), &edge.weight),
1359 next: edge.next,
1360 node: edge.node,
1361 }));
1362 g
1363 }
1364
1365 pub fn filter_map<'a, F, G, N2, E2>(
1378 &'a self,
1379 mut node_map: F,
1380 mut edge_map: G,
1381 ) -> Graph<N2, E2, Ty, Ix>
1382 where
1383 F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
1384 G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
1385 {
1386 let mut g = Graph::with_capacity(0, 0);
1387 let mut node_index_map = vec![NodeIndex::end(); self.node_count()];
1389 for (i, node) in enumerate(&self.nodes) {
1390 if let Some(nw) = node_map(NodeIndex::new(i), &node.weight) {
1391 node_index_map[i] = g.add_node(nw);
1392 }
1393 }
1394 for (i, edge) in enumerate(&self.edges) {
1395 let source = node_index_map[edge.source().index()];
1397 let target = node_index_map[edge.target().index()];
1398 if source != NodeIndex::end() && target != NodeIndex::end() {
1399 if let Some(ew) = edge_map(EdgeIndex::new(i), &edge.weight) {
1400 g.add_edge(source, target, ew);
1401 }
1402 }
1403 }
1404 g
1405 }
1406
1407 pub fn into_edge_type<NewTy>(self) -> Graph<N, E, NewTy, Ix>
1412 where
1413 NewTy: EdgeType,
1414 {
1415 Graph {
1416 nodes: self.nodes,
1417 edges: self.edges,
1418 ty: PhantomData,
1419 }
1420 }
1421
1422 #[cfg(feature = "serde-1")]
1426 fn link_edges(&mut self) -> Result<(), NodeIndex<Ix>> {
1428 for (edge_index, edge) in enumerate(&mut self.edges) {
1429 let a = edge.source();
1430 let b = edge.target();
1431 let edge_idx = EdgeIndex::new(edge_index);
1432 match index_twice(&mut self.nodes, a.index(), b.index()) {
1433 Pair::None => return Err(if a > b { a } else { b }),
1434 Pair::One(an) => {
1435 edge.next = an.next;
1436 an.next[0] = edge_idx;
1437 an.next[1] = edge_idx;
1438 }
1439 Pair::Both(an, bn) => {
1440 edge.next = [an.next[0], bn.next[1]];
1442 an.next[0] = edge_idx;
1443 bn.next[1] = edge_idx;
1444 }
1445 }
1446 }
1447 Ok(())
1448 }
1449}
1450
1451pub struct Externals<'a, N: 'a, Ty, Ix: IndexType = DefaultIx> {
1453 iter: iter::Enumerate<slice::Iter<'a, Node<N, Ix>>>,
1454 dir: Direction,
1455 ty: PhantomData<Ty>,
1456}
1457
1458impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix>
1459where
1460 Ty: EdgeType,
1461 Ix: IndexType,
1462{
1463 type Item = NodeIndex<Ix>;
1464 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1465 let k = self.dir.index();
1466 loop {
1467 match self.iter.next() {
1468 None => return None,
1469 Some((index, node)) => {
1470 if node.next[k] == EdgeIndex::end()
1471 && (Ty::is_directed() || node.next[1 - k] == EdgeIndex::end())
1472 {
1473 return Some(NodeIndex::new(index));
1474 } else {
1475 continue;
1476 }
1477 }
1478 }
1479 }
1480 }
1481}
1482
1483pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx> {
1494 skip_start: NodeIndex<Ix>,
1496 edges: &'a [Edge<E, Ix>],
1497 next: [EdgeIndex<Ix>; 2],
1498}
1499
1500impl<'a, E, Ix> Iterator for Neighbors<'a, E, Ix>
1501where
1502 Ix: IndexType,
1503{
1504 type Item = NodeIndex<Ix>;
1505
1506 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1507 match self.edges.get(self.next[0].index()) {
1509 None => {}
1510 Some(edge) => {
1511 self.next[0] = edge.next[0];
1512 return Some(edge.node[1]);
1513 }
1514 }
1515 while let Some(edge) = self.edges.get(self.next[1].index()) {
1520 self.next[1] = edge.next[1];
1521 if edge.node[0] != self.skip_start {
1522 return Some(edge.node[0]);
1523 }
1524 }
1525 None
1526 }
1527}
1528
1529impl<'a, E, Ix> Clone for Neighbors<'a, E, Ix>
1530where
1531 Ix: IndexType,
1532{
1533 clone_fields!(Neighbors, skip_start, edges, next,);
1534}
1535
1536impl<'a, E, Ix> Neighbors<'a, E, Ix>
1537where
1538 Ix: IndexType,
1539{
1540 pub fn detach(&self) -> WalkNeighbors<Ix> {
1546 WalkNeighbors {
1547 skip_start: self.skip_start,
1548 next: self.next,
1549 }
1550 }
1551}
1552
1553struct EdgesWalkerMut<'a, E: 'a, Ix: IndexType = DefaultIx> {
1554 edges: &'a mut [Edge<E, Ix>],
1555 next: EdgeIndex<Ix>,
1556 dir: Direction,
1557}
1558
1559fn edges_walker_mut<E, Ix>(
1560 edges: &mut [Edge<E, Ix>],
1561 next: EdgeIndex<Ix>,
1562 dir: Direction,
1563) -> EdgesWalkerMut<E, Ix>
1564where
1565 Ix: IndexType,
1566{
1567 EdgesWalkerMut { edges, next, dir }
1568}
1569
1570impl<'a, E, Ix> EdgesWalkerMut<'a, E, Ix>
1571where
1572 Ix: IndexType,
1573{
1574 fn next_edge(&mut self) -> Option<&mut Edge<E, Ix>> {
1575 self.next().map(|t| t.1)
1576 }
1577
1578 fn next(&mut self) -> Option<(EdgeIndex<Ix>, &mut Edge<E, Ix>)> {
1579 let this_index = self.next;
1580 let k = self.dir.index();
1581 match self.edges.get_mut(self.next.index()) {
1582 None => None,
1583 Some(edge) => {
1584 self.next = edge.next[k];
1585 Some((this_index, edge))
1586 }
1587 }
1588 }
1589}
1590
1591impl<'a, N, E, Ty, Ix> IntoEdges for &'a Graph<N, E, Ty, Ix>
1592where
1593 Ty: EdgeType,
1594 Ix: IndexType,
1595{
1596 type Edges = Edges<'a, E, Ty, Ix>;
1597 fn edges(self, a: Self::NodeId) -> Self::Edges {
1598 self.edges(a)
1599 }
1600}
1601
1602impl<'a, N, E, Ty, Ix> IntoEdgesDirected for &'a Graph<N, E, Ty, Ix>
1603where
1604 Ty: EdgeType,
1605 Ix: IndexType,
1606{
1607 type EdgesDirected = Edges<'a, E, Ty, Ix>;
1608 fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
1609 self.edges_directed(a, dir)
1610 }
1611}
1612
1613pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1615where
1616 Ty: EdgeType,
1617 Ix: IndexType,
1618{
1619 skip_start: NodeIndex<Ix>,
1621 edges: &'a [Edge<E, Ix>],
1622
1623 next: [EdgeIndex<Ix>; 2],
1625
1626 direction: Direction,
1629 ty: PhantomData<Ty>,
1630}
1631
1632impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1633where
1634 Ty: EdgeType,
1635 Ix: IndexType,
1636{
1637 type Item = EdgeReference<'a, E, Ix>;
1638
1639 fn next(&mut self) -> Option<Self::Item> {
1640 let (iterate_over, reverse) = if Ty::is_directed() {
1650 (Some(self.direction), None)
1651 } else {
1652 (None, Some(self.direction.opposite()))
1653 };
1654
1655 if iterate_over.unwrap_or(Outgoing) == Outgoing {
1656 let i = self.next[0].index();
1657 if let Some(Edge { node, weight, next }) = self.edges.get(i) {
1658 self.next[0] = next[0];
1659 return Some(EdgeReference {
1660 index: edge_index(i),
1661 node: if reverse == Some(Outgoing) {
1662 swap_pair(*node)
1663 } else {
1664 *node
1665 },
1666 weight,
1667 });
1668 }
1669 }
1670
1671 if iterate_over.unwrap_or(Incoming) == Incoming {
1672 while let Some(Edge { node, weight, next }) = self.edges.get(self.next[1].index()) {
1673 let edge_index = self.next[1];
1674 self.next[1] = next[1];
1675 if iterate_over.is_none() && node[0] == self.skip_start {
1678 continue;
1679 }
1680
1681 return Some(EdgeReference {
1682 index: edge_index,
1683 node: if reverse == Some(Incoming) {
1684 swap_pair(*node)
1685 } else {
1686 *node
1687 },
1688 weight,
1689 });
1690 }
1691 }
1692
1693 None
1694 }
1695}
1696
1697pub struct EdgesConnecting<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1699where
1700 Ty: EdgeType,
1701 Ix: IndexType,
1702{
1703 target_node: NodeIndex<Ix>,
1704 edges: Edges<'a, E, Ty, Ix>,
1705 ty: PhantomData<Ty>,
1706}
1707
1708impl<'a, E, Ty, Ix> Iterator for EdgesConnecting<'a, E, Ty, Ix>
1709where
1710 Ty: EdgeType,
1711 Ix: IndexType,
1712{
1713 type Item = EdgeReference<'a, E, Ix>;
1714
1715 fn next(&mut self) -> Option<EdgeReference<'a, E, Ix>> {
1716 while let Some(edge) = self.edges.next() {
1717 if edge.node[1] == self.target_node {
1718 return Some(edge);
1719 }
1720 }
1721
1722 None
1723 }
1724}
1725
1726fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1727 x.swap(0, 1);
1728 x
1729}
1730
1731impl<'a, E, Ty, Ix> Clone for Edges<'a, E, Ty, Ix>
1732where
1733 Ix: IndexType,
1734 Ty: EdgeType,
1735{
1736 fn clone(&self) -> Self {
1737 Edges {
1738 skip_start: self.skip_start,
1739 edges: self.edges,
1740 next: self.next,
1741 direction: self.direction,
1742 ty: self.ty,
1743 }
1744 }
1745}
1746
1747pub struct NodeWeightsMut<'a, N: 'a, Ix: IndexType = DefaultIx> {
1749 nodes: slice::IterMut<'a, Node<N, Ix>>,
1750}
1751
1752impl<'a, N, Ix> Iterator for NodeWeightsMut<'a, N, Ix>
1753where
1754 Ix: IndexType,
1755{
1756 type Item = &'a mut N;
1757
1758 fn next(&mut self) -> Option<&'a mut N> {
1759 self.nodes.next().map(|node| &mut node.weight)
1760 }
1761
1762 fn size_hint(&self) -> (usize, Option<usize>) {
1763 self.nodes.size_hint()
1764 }
1765}
1766
1767pub struct EdgeWeightsMut<'a, E: 'a, Ix: IndexType = DefaultIx> {
1769 edges: slice::IterMut<'a, Edge<E, Ix>>,
1770}
1771
1772impl<'a, E, Ix> Iterator for EdgeWeightsMut<'a, E, Ix>
1773where
1774 Ix: IndexType,
1775{
1776 type Item = &'a mut E;
1777
1778 fn next(&mut self) -> Option<&'a mut E> {
1779 self.edges.next().map(|edge| &mut edge.weight)
1780 }
1781
1782 fn size_hint(&self) -> (usize, Option<usize>) {
1783 self.edges.size_hint()
1784 }
1785}
1786
1787impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for Graph<N, E, Ty, Ix>
1791where
1792 Ty: EdgeType,
1793 Ix: IndexType,
1794{
1795 type Output = N;
1796 fn index(&self, index: NodeIndex<Ix>) -> &N {
1797 &self.nodes[index.index()].weight
1798 }
1799}
1800
1801impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for Graph<N, E, Ty, Ix>
1805where
1806 Ty: EdgeType,
1807 Ix: IndexType,
1808{
1809 fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1810 &mut self.nodes[index.index()].weight
1811 }
1812}
1813
1814impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix>
1818where
1819 Ty: EdgeType,
1820 Ix: IndexType,
1821{
1822 type Output = E;
1823 fn index(&self, index: EdgeIndex<Ix>) -> &E {
1824 &self.edges[index.index()].weight
1825 }
1826}
1827
1828impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix>
1832where
1833 Ty: EdgeType,
1834 Ix: IndexType,
1835{
1836 fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
1837 &mut self.edges[index.index()].weight
1838 }
1839}
1840
1841impl<N, E, Ty, Ix> Default for Graph<N, E, Ty, Ix>
1843where
1844 Ty: EdgeType,
1845 Ix: IndexType,
1846{
1847 fn default() -> Self {
1848 Self::with_capacity(0, 0)
1849 }
1850}
1851
1852pub trait GraphIndex: Copy {
1854 #[doc(hidden)]
1855 fn index(&self) -> usize;
1856 #[doc(hidden)]
1857 fn is_node_index() -> bool;
1858}
1859
1860impl<Ix: IndexType> GraphIndex for NodeIndex<Ix> {
1861 #[inline]
1862 fn index(&self) -> usize {
1863 NodeIndex::index(*self)
1864 }
1865 #[inline]
1866 fn is_node_index() -> bool {
1867 true
1868 }
1869}
1870
1871impl<Ix: IndexType> GraphIndex for EdgeIndex<Ix> {
1872 #[inline]
1873 fn index(&self) -> usize {
1874 EdgeIndex::index(*self)
1875 }
1876 #[inline]
1877 fn is_node_index() -> bool {
1878 false
1879 }
1880}
1881
1882pub struct WalkNeighbors<Ix> {
1918 skip_start: NodeIndex<Ix>,
1919 next: [EdgeIndex<Ix>; 2],
1920}
1921
1922impl<Ix> Clone for WalkNeighbors<Ix>
1923where
1924 Ix: IndexType,
1925{
1926 fn clone(&self) -> Self {
1927 WalkNeighbors {
1928 skip_start: self.skip_start,
1929 next: self.next,
1930 }
1931 }
1932}
1933
1934impl<Ix: IndexType> WalkNeighbors<Ix> {
1935 pub fn next<N, E, Ty: EdgeType>(
1942 &mut self,
1943 g: &Graph<N, E, Ty, Ix>,
1944 ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
1945 match g.edges.get(self.next[0].index()) {
1947 None => {}
1948 Some(edge) => {
1949 let ed = self.next[0];
1950 self.next[0] = edge.next[0];
1951 return Some((ed, edge.node[1]));
1952 }
1953 }
1954 while let Some(edge) = g.edges.get(self.next[1].index()) {
1959 let ed = self.next[1];
1960 self.next[1] = edge.next[1];
1961 if edge.node[0] != self.skip_start {
1962 return Some((ed, edge.node[0]));
1963 }
1964 }
1965 None
1966 }
1967
1968 pub fn next_node<N, E, Ty: EdgeType>(
1969 &mut self,
1970 g: &Graph<N, E, Ty, Ix>,
1971 ) -> Option<NodeIndex<Ix>> {
1972 self.next(g).map(|t| t.1)
1973 }
1974
1975 pub fn next_edge<N, E, Ty: EdgeType>(
1976 &mut self,
1977 g: &Graph<N, E, Ty, Ix>,
1978 ) -> Option<EdgeIndex<Ix>> {
1979 self.next(g).map(|t| t.0)
1980 }
1981}
1982
1983#[derive(Clone, Debug)]
1985pub struct NodeIndices<Ix = DefaultIx> {
1986 r: Range<usize>,
1987 ty: PhantomData<fn() -> Ix>,
1988}
1989
1990impl<Ix: IndexType> Iterator for NodeIndices<Ix> {
1991 type Item = NodeIndex<Ix>;
1992
1993 fn next(&mut self) -> Option<Self::Item> {
1994 self.r.next().map(node_index)
1995 }
1996
1997 fn size_hint(&self) -> (usize, Option<usize>) {
1998 self.r.size_hint()
1999 }
2000}
2001
2002impl<Ix: IndexType> DoubleEndedIterator for NodeIndices<Ix> {
2003 fn next_back(&mut self) -> Option<Self::Item> {
2004 self.r.next_back().map(node_index)
2005 }
2006}
2007
2008impl<Ix: IndexType> ExactSizeIterator for NodeIndices<Ix> {}
2009
2010#[derive(Clone, Debug)]
2012pub struct EdgeIndices<Ix = DefaultIx> {
2013 r: Range<usize>,
2014 ty: PhantomData<fn() -> Ix>,
2015}
2016
2017impl<Ix: IndexType> Iterator for EdgeIndices<Ix> {
2018 type Item = EdgeIndex<Ix>;
2019
2020 fn next(&mut self) -> Option<Self::Item> {
2021 self.r.next().map(edge_index)
2022 }
2023
2024 fn size_hint(&self) -> (usize, Option<usize>) {
2025 self.r.size_hint()
2026 }
2027}
2028
2029impl<Ix: IndexType> DoubleEndedIterator for EdgeIndices<Ix> {
2030 fn next_back(&mut self) -> Option<Self::Item> {
2031 self.r.next_back().map(edge_index)
2032 }
2033}
2034
2035impl<Ix: IndexType> ExactSizeIterator for EdgeIndices<Ix> {}
2036
2037#[derive(Debug)]
2039pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
2040 index: EdgeIndex<Ix>,
2041 node: [NodeIndex<Ix>; 2],
2042 weight: &'a E,
2043}
2044
2045impl<'a, E, Ix: IndexType> Clone for EdgeReference<'a, E, Ix> {
2046 fn clone(&self) -> Self {
2047 *self
2048 }
2049}
2050
2051impl<'a, E, Ix: IndexType> Copy for EdgeReference<'a, E, Ix> {}
2052
2053impl<'a, E, Ix: IndexType> PartialEq for EdgeReference<'a, E, Ix>
2054where
2055 E: PartialEq,
2056{
2057 fn eq(&self, rhs: &Self) -> bool {
2058 self.index == rhs.index && self.weight == rhs.weight
2059 }
2060}
2061
2062impl<'a, N, E, Ty, Ix> IntoNodeReferences for &'a Graph<N, E, Ty, Ix>
2063where
2064 Ty: EdgeType,
2065 Ix: IndexType,
2066{
2067 type NodeRef = (NodeIndex<Ix>, &'a N);
2068 type NodeReferences = NodeReferences<'a, N, Ix>;
2069 fn node_references(self) -> Self::NodeReferences {
2070 NodeReferences {
2071 iter: self.nodes.iter().enumerate(),
2072 }
2073 }
2074}
2075
2076pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
2078 iter: iter::Enumerate<slice::Iter<'a, Node<N, Ix>>>,
2079}
2080
2081impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
2082where
2083 Ix: IndexType,
2084{
2085 type Item = (NodeIndex<Ix>, &'a N);
2086
2087 fn next(&mut self) -> Option<Self::Item> {
2088 self.iter
2089 .next()
2090 .map(|(i, node)| (node_index(i), &node.weight))
2091 }
2092
2093 fn size_hint(&self) -> (usize, Option<usize>) {
2094 self.iter.size_hint()
2095 }
2096}
2097
2098impl<'a, N, Ix> DoubleEndedIterator for NodeReferences<'a, N, Ix>
2099where
2100 Ix: IndexType,
2101{
2102 fn next_back(&mut self) -> Option<Self::Item> {
2103 self.iter
2104 .next_back()
2105 .map(|(i, node)| (node_index(i), &node.weight))
2106 }
2107}
2108
2109impl<'a, N, Ix> ExactSizeIterator for NodeReferences<'a, N, Ix> where Ix: IndexType {}
2110
2111impl<'a, Ix, E> EdgeReference<'a, E, Ix>
2112where
2113 Ix: IndexType,
2114{
2115 pub fn weight(&self) -> &'a E {
2120 self.weight
2121 }
2122}
2123
2124impl<'a, Ix, E> EdgeRef for EdgeReference<'a, E, Ix>
2125where
2126 Ix: IndexType,
2127{
2128 type NodeId = NodeIndex<Ix>;
2129 type EdgeId = EdgeIndex<Ix>;
2130 type Weight = E;
2131
2132 fn source(&self) -> Self::NodeId {
2133 self.node[0]
2134 }
2135 fn target(&self) -> Self::NodeId {
2136 self.node[1]
2137 }
2138 fn weight(&self) -> &E {
2139 self.weight
2140 }
2141 fn id(&self) -> Self::EdgeId {
2142 self.index
2143 }
2144}
2145
2146pub struct EdgeReferences<'a, E: 'a, Ix: IndexType = DefaultIx> {
2148 iter: iter::Enumerate<slice::Iter<'a, Edge<E, Ix>>>,
2149}
2150
2151impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
2152where
2153 Ix: IndexType,
2154{
2155 type Item = EdgeReference<'a, E, Ix>;
2156
2157 fn next(&mut self) -> Option<Self::Item> {
2158 self.iter.next().map(|(i, edge)| EdgeReference {
2159 index: edge_index(i),
2160 node: edge.node,
2161 weight: &edge.weight,
2162 })
2163 }
2164
2165 fn size_hint(&self) -> (usize, Option<usize>) {
2166 self.iter.size_hint()
2167 }
2168}
2169
2170impl<'a, E, Ix> DoubleEndedIterator for EdgeReferences<'a, E, Ix>
2171where
2172 Ix: IndexType,
2173{
2174 fn next_back(&mut self) -> Option<Self::Item> {
2175 self.iter.next_back().map(|(i, edge)| EdgeReference {
2176 index: edge_index(i),
2177 node: edge.node,
2178 weight: &edge.weight,
2179 })
2180 }
2181}
2182
2183impl<'a, E, Ix> ExactSizeIterator for EdgeReferences<'a, E, Ix> where Ix: IndexType {}
2184
2185mod frozen;
2186#[cfg(feature = "stable_graph")]
2187pub mod stable_graph;
2188
2189pub struct Frozen<'a, G: 'a>(&'a mut G);