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 {
11 Direction, Outgoing, Incoming,
12 Undirected,
13 Directed,
14 EdgeType,
15 IntoWeightedEdge,
16};
17
18use iter_format::{
19 IterFormatExt,
20 NoPretty,
21 DebugMap,
22};
23
24use visit::EdgeRef;
25use visit::{IntoNodeReferences, IntoEdges, IntoEdgesDirected};
26use util::enumerate;
27
28#[cfg(feature = "serde-1")]
29mod serialization;
30
31
32pub type DefaultIx = u32;
39
40pub unsafe trait IndexType : Copy + Default + Hash + Ord + fmt::Debug + 'static
45{
46 fn new(x: usize) -> Self;
47 fn index(&self) -> usize;
48 fn max() -> Self;
49}
50
51unsafe impl IndexType for usize {
52 #[inline(always)]
53 fn new(x: usize) -> Self { x }
54 #[inline(always)]
55 fn index(&self) -> Self { *self }
56 #[inline(always)]
57 fn max() -> Self { ::std::usize::MAX }
58}
59
60unsafe impl IndexType for u32 {
61 #[inline(always)]
62 fn new(x: usize) -> Self { x as u32 }
63 #[inline(always)]
64 fn index(&self) -> usize { *self as usize }
65 #[inline(always)]
66 fn max() -> Self { ::std::u32::MAX }
67}
68
69unsafe impl IndexType for u16 {
70 #[inline(always)]
71 fn new(x: usize) -> Self { x as u16 }
72 #[inline(always)]
73 fn index(&self) -> usize { *self as usize }
74 #[inline(always)]
75 fn max() -> Self { ::std::u16::MAX }
76}
77
78unsafe impl IndexType for u8 {
79 #[inline(always)]
80 fn new(x: usize) -> Self { x as u8 }
81 #[inline(always)]
82 fn index(&self) -> usize { *self as usize }
83 #[inline(always)]
84 fn max() -> Self { ::std::u8::MAX }
85}
86
87#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
89pub struct NodeIndex<Ix=DefaultIx>(Ix);
90
91impl<Ix: IndexType> NodeIndex<Ix>
92{
93 #[inline]
94 pub fn new(x: usize) -> Self {
95 NodeIndex(IndexType::new(x))
96 }
97
98 #[inline]
99 pub fn index(self) -> usize
100 {
101 self.0.index()
102 }
103
104 #[inline]
105 pub fn end() -> Self
106 {
107 NodeIndex(IndexType::max())
108 }
109
110 fn _into_edge(self) -> EdgeIndex<Ix> {
111 EdgeIndex(self.0)
112 }
113}
114
115impl<Ix: IndexType> From<Ix> for NodeIndex<Ix> {
116 fn from(ix: Ix) -> Self { NodeIndex(ix) }
117}
118
119impl<Ix: fmt::Debug> fmt::Debug for NodeIndex<Ix>
120{
121 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
122 write!(f, "NodeIndex({:?})", self.0)
123 }
124}
125
126pub fn node_index<Ix: IndexType>(index: usize) -> NodeIndex<Ix> { NodeIndex::new(index) }
128
129pub fn edge_index<Ix: IndexType>(index: usize) -> EdgeIndex<Ix> { EdgeIndex::new(index) }
131
132#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
134pub struct EdgeIndex<Ix=DefaultIx>(Ix);
135
136impl<Ix: IndexType> EdgeIndex<Ix>
137{
138 #[inline]
139 pub fn new(x: usize) -> Self {
140 EdgeIndex(IndexType::new(x))
141 }
142
143 #[inline]
144 pub fn index(self) -> usize
145 {
146 self.0.index()
147 }
148
149 #[inline]
152 pub fn end() -> Self {
153 EdgeIndex(IndexType::max())
154 }
155
156 fn _into_node(self) -> NodeIndex<Ix> {
157 NodeIndex(self.0)
158 }
159}
160
161impl<Ix: fmt::Debug> fmt::Debug for EdgeIndex<Ix>
162{
163 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
164 write!(f, "EdgeIndex({:?})", self.0)
165 }
166}
167const DIRECTIONS: [Direction; 2] = [Outgoing, Incoming];
184
185#[derive(Debug)]
187pub struct Node<N, Ix = DefaultIx> {
188 pub weight: N,
190 next: [EdgeIndex<Ix>; 2],
192}
193
194impl<E, Ix> Clone for Node<E, Ix> where E: Clone, Ix: Copy {
195 clone_fields!(Node,
196 weight,
197 next,
198 );
199}
200
201
202impl<N, Ix: IndexType> Node<N, Ix>
203{
204 pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix>
206 {
207 self.next[dir.index()]
208 }
209}
210
211
212#[derive(Debug)]
214pub struct Edge<E, Ix = DefaultIx> {
215 pub weight: E,
217 next: [EdgeIndex<Ix>; 2],
219 node: [NodeIndex<Ix>; 2],
221}
222
223impl<E, Ix> Clone for Edge<E, Ix> where E: Clone, Ix: Copy {
224 clone_fields!(Edge,
225 weight,
226 next,
227 node,
228 );
229}
230
231impl<E, Ix: IndexType> Edge<E, Ix>
232{
233 pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix>
235 {
236 self.next[dir.index()]
237 }
238
239 pub fn source(&self) -> NodeIndex<Ix>
241 {
242 self.node[0]
243 }
244
245 pub fn target(&self) -> NodeIndex<Ix>
247 {
248 self.node[1]
249 }
250}
251
252pub struct Graph<N, E, Ty = Directed, Ix = DefaultIx> {
326 nodes: Vec<Node<N, Ix>>,
327 edges: Vec<Edge<E, Ix>>,
328 ty: PhantomData<Ty>,
329}
330
331pub type DiGraph<N, E, Ix = DefaultIx> = Graph<N, E, Directed, Ix>;
336
337pub type UnGraph<N, E, Ix = DefaultIx> = Graph<N, E, Undirected, Ix>;
342
343
344impl<N, E, Ty, Ix: IndexType> Clone for Graph<N, E, Ty, Ix>
346 where N: Clone, E: Clone,
347{
348 fn clone(&self) -> Self {
349 Graph {
350 nodes: self.nodes.clone(),
351 edges: self.edges.clone(),
352 ty: self.ty,
353 }
354 }
355
356 fn clone_from(&mut self, rhs: &Self) {
357 self.nodes.clone_from(&rhs.nodes);
358 self.edges.clone_from(&rhs.edges);
359 self.ty = rhs.ty;
360 }
361}
362
363impl<N, E, Ty, Ix> fmt::Debug for Graph<N, E, Ty, Ix>
364 where N: fmt::Debug,
365 E: fmt::Debug,
366 Ty: EdgeType,
367 Ix: IndexType,
368{
369 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
370 let etype = if self.is_directed() { "Directed" } else { "Undirected" };
371 let mut fmt_struct = f.debug_struct("Graph");
372 fmt_struct.field("Ty", &etype);
373 fmt_struct.field("node_count", &self.node_count());
374 fmt_struct.field("edge_count", &self.edge_count());
375 if self.edge_count() > 0 {
376 fmt_struct.field("edges",
377 &self.edges
378 .iter()
379 .map(|e| NoPretty((e.source().index(), e.target().index())))
380 .format(", "));
381 }
382 if size_of::<N>() != 0 {
384 fmt_struct.field("node weights", &DebugMap(|| self.nodes.iter()
385 .map(|n| &n.weight)
386 .enumerate()));
387 }
388 if size_of::<E>() != 0 {
389 fmt_struct.field("edge weights", &DebugMap(|| self.edges.iter()
390 .map(|n| &n.weight)
391 .enumerate()));
392 }
393 fmt_struct.finish()
394 }
395}
396
397enum Pair<T> {
398 Both(T, T),
399 One(T),
400 None,
401}
402
403use std::cmp::max;
404
405fn index_twice<T>(slc: &mut [T], a: usize, b: usize) -> Pair<&mut T> {
407 if max(a, b) >= slc.len() {
408 Pair::None
409 } else if a == b {
410 Pair::One(&mut slc[max(a, b)])
411 } else {
412 unsafe {
414 let ar = &mut *(slc.get_unchecked_mut(a) as *mut _);
415 let br = &mut *(slc.get_unchecked_mut(b) as *mut _);
416 Pair::Both(ar, br)
417 }
418 }
419}
420
421impl<N, E> Graph<N, E, Directed>
422{
423 pub fn new() -> Self
428 {
429 Graph{nodes: Vec::new(), edges: Vec::new(),
430 ty: PhantomData}
431 }
432}
433
434impl<N, E> Graph<N, E, Undirected>
435{
436 pub fn new_undirected() -> Self
441 {
442 Graph{nodes: Vec::new(), edges: Vec::new(),
443 ty: PhantomData}
444 }
445}
446
447impl<N, E, Ty, Ix> Graph<N, E, Ty, Ix>
448 where Ty: EdgeType,
449 Ix: IndexType,
450{
451 pub fn with_capacity(nodes: usize, edges: usize) -> Self
453 {
454 Graph{nodes: Vec::with_capacity(nodes), edges: Vec::with_capacity(edges),
455 ty: PhantomData}
456 }
457
458 pub fn node_count(&self) -> usize
462 {
463 self.nodes.len()
464 }
465
466 pub fn edge_count(&self) -> usize
470 {
471 self.edges.len()
472 }
473
474 #[inline]
476 pub fn is_directed(&self) -> bool
477 {
478 Ty::is_directed()
479 }
480
481 pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix>
490 {
491 let node = Node{weight: weight, next: [EdgeIndex::end(), EdgeIndex::end()]};
492 let node_idx = NodeIndex::new(self.nodes.len());
493 assert!(<Ix as IndexType>::max().index() == !0 || NodeIndex::end() != node_idx);
495 self.nodes.push(node);
496 node_idx
497 }
498
499 pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N>
503 {
504 self.nodes.get(a.index()).map(|n| &n.weight)
505 }
506
507 pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N>
511 {
512 self.nodes.get_mut(a.index()).map(|n| &mut n.weight)
513 }
514
515 pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix>
529 {
530 let edge_idx = EdgeIndex::new(self.edges.len());
531 assert!(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx);
532 let mut edge = Edge {
533 weight: weight,
534 node: [a, b],
535 next: [EdgeIndex::end(); 2],
536 };
537 match index_twice(&mut self.nodes, a.index(), b.index()) {
538 Pair::None => panic!("Graph::add_edge: node indices out of bounds"),
539 Pair::One(an) => {
540 edge.next = an.next;
541 an.next[0] = edge_idx;
542 an.next[1] = edge_idx;
543 }
544 Pair::Both(an, bn) => {
545 edge.next = [an.next[0], bn.next[1]];
547 an.next[0] = edge_idx;
548 bn.next[1] = edge_idx;
549 }
550 }
551 self.edges.push(edge);
552 edge_idx
553 }
554
555 pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix>
565 {
566 if let Some(ix) = self.find_edge(a, b) {
567 if let Some(ed) = self.edge_weight_mut(ix) {
568 *ed = weight;
569 return ix;
570 }
571 }
572 self.add_edge(a, b, weight)
573 }
574
575 pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E>
579 {
580 self.edges.get(e.index()).map(|ed| &ed.weight)
581 }
582
583 pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E>
587 {
588 self.edges.get_mut(e.index()).map(|ed| &mut ed.weight)
589 }
590
591 pub fn edge_endpoints(&self, e: EdgeIndex<Ix>)
593 -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)>
594 {
595 self.edges.get(e.index()).map(|ed| (ed.source(), ed.target()))
596 }
597
598 pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N>
611 {
612 if self.nodes.get(a.index()).is_none() {
613 return None
614 }
615 for d in &DIRECTIONS {
616 let k = d.index();
617
618 loop {
620 let next = self.nodes[a.index()].next[k];
621 if next == EdgeIndex::end() {
622 break
623 }
624 let ret = self.remove_edge(next);
625 debug_assert!(ret.is_some());
626 let _ = ret;
627 }
628 }
629
630 let node = self.nodes.swap_remove(a.index());
634
635 let swap_edges = match self.nodes.get(a.index()) {
638 None => return Some(node.weight),
639 Some(ed) => ed.next,
640 };
641
642 let old_index = NodeIndex::new(self.nodes.len());
644 let new_index = a;
645
646 for &d in &DIRECTIONS {
648 let k = d.index();
649 let mut edges = edges_walker_mut(&mut self.edges, swap_edges[k], d);
650 while let Some(curedge) = edges.next_edge() {
651 debug_assert!(curedge.node[k] == old_index);
652 curedge.node[k] = new_index;
653 }
654 }
655 Some(node.weight)
656 }
657
658 fn change_edge_links(&mut self, edge_node: [NodeIndex<Ix>; 2], e: EdgeIndex<Ix>,
661 edge_next: [EdgeIndex<Ix>; 2])
662 {
663 for &d in &DIRECTIONS {
664 let k = d.index();
665 let node = match self.nodes.get_mut(edge_node[k].index()) {
666 Some(r) => r,
667 None => {
668 debug_assert!(false, "Edge's endpoint dir={:?} index={:?} not found",
669 d, edge_node[k]);
670 return
671 }
672 };
673 let fst = node.next[k];
674 if fst == e {
675 node.next[k] = edge_next[k];
677 } else {
678 let mut edges = edges_walker_mut(&mut self.edges, fst, d);
679 while let Some(curedge) = edges.next_edge() {
680 if curedge.next[k] == e {
681 curedge.next[k] = edge_next[k];
682 break; }
684 }
685 }
686 }
687 }
688
689 pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E>
697 {
698 let (edge_node, edge_next) = match self.edges.get(e.index()) {
702 None => return None,
703 Some(x) => (x.node, x.next),
704 };
705 self.change_edge_links(edge_node, e, edge_next);
708 self.remove_edge_adjust_indices(e)
709 }
710
711 fn remove_edge_adjust_indices(&mut self, e: EdgeIndex<Ix>) -> Option<E>
712 {
713 let edge = self.edges.swap_remove(e.index());
717 let swap = match self.edges.get(e.index()) {
718 None => return Some(edge.weight),
720 Some(ed) => ed.node,
721 };
722 let swapped_e = EdgeIndex::new(self.edges.len());
723
724 self.change_edge_links(swap, swapped_e, [e, e]);
727 Some(edge.weight)
728 }
729
730 pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix>
743 {
744 self.neighbors_directed(a, Outgoing)
745 }
746
747 pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix>
767 {
768 let mut iter = self.neighbors_undirected(a);
769 if self.is_directed() {
770 let k = dir.index();
771 iter.next[1 - k] = EdgeIndex::end();
772 iter.skip_start = NodeIndex::end();
773 }
774 iter
775 }
776
777 pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix>
792 {
793 Neighbors {
794 skip_start: a,
795 edges: &self.edges,
796 next: match self.nodes.get(a.index()) {
797 None => [EdgeIndex::end(), EdgeIndex::end()],
798 Some(n) => n.next,
799 }
800 }
801 }
802
803 pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
811 self.edges_directed(a, Outgoing)
812 }
813
814 pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix>
823 {
824 let mut iter = self.edges_undirected(a);
825 if self.is_directed() {
826 iter.direction = Some(dir);
827 }
828 if self.is_directed() && dir == Incoming {
829 iter.next.swap(0, 1);
830 }
831 iter
832 }
833
834 fn edges_undirected(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
841 Edges {
842 skip_start: a,
843 edges: &self.edges,
844 direction: None,
845 next: match self.nodes.get(a.index()) {
846 None => [EdgeIndex::end(), EdgeIndex::end()],
847 Some(n) => n.next,
848 },
849 ty: PhantomData,
850 }
851 }
852
853 pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
858 self.find_edge(a, b).is_some()
859 }
860
861 pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>>
866 {
867 if !self.is_directed() {
868 self.find_edge_undirected(a, b).map(|(ix, _)| ix)
869 } else {
870 match self.nodes.get(a.index()) {
871 None => None,
872 Some(node) => self.find_edge_directed_from_node(node, b)
873 }
874 }
875 }
876
877 fn find_edge_directed_from_node(&self, node: &Node<N, Ix>, b: NodeIndex<Ix>)
878 -> Option<EdgeIndex<Ix>>
879 {
880 let mut edix = node.next[0];
881 while let Some(edge) = self.edges.get(edix.index()) {
882 if edge.node[1] == b {
883 return Some(edix)
884 }
885 edix = edge.next[0];
886 }
887 None
888 }
889
890 pub fn find_edge_undirected(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<(EdgeIndex<Ix>, Direction)>
898 {
899 match self.nodes.get(a.index()) {
900 None => None,
901 Some(node) => self.find_edge_undirected_from_node(node, b),
902 }
903 }
904
905 fn find_edge_undirected_from_node(&self, node: &Node<N, Ix>, b: NodeIndex<Ix>)
906 -> Option<(EdgeIndex<Ix>, Direction)>
907 {
908 for &d in &DIRECTIONS {
909 let k = d.index();
910 let mut edix = node.next[k];
911 while let Some(edge) = self.edges.get(edix.index()) {
912 if edge.node[1 - k] == b {
913 return Some((edix, d))
914 }
915 edix = edge.next[k];
916 }
917 }
918 None
919 }
920
921 pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix>
933 {
934 Externals{iter: self.nodes.iter().enumerate(), dir: dir, ty: PhantomData}
935 }
936
937 pub fn node_indices(&self) -> NodeIndices<Ix> {
939 NodeIndices { r: 0..self.node_count(), ty: PhantomData }
940 }
941
942 pub fn node_weights_mut(&mut self) -> NodeWeightsMut<N, Ix>
947 {
948 NodeWeightsMut { nodes: self.nodes.iter_mut() }
949 }
950
951 pub fn edge_indices(&self) -> EdgeIndices<Ix> {
953 EdgeIndices { r: 0..self.edge_count(), ty: PhantomData }
954 }
955
956 pub fn edge_references(&self) -> EdgeReferences<E, Ix> {
960 EdgeReferences {
961 iter: self.edges.iter().enumerate()
962 }
963 }
964
965 pub fn edge_weights_mut(&mut self) -> EdgeWeightsMut<E, Ix>
970 {
971 EdgeWeightsMut { edges: self.edges.iter_mut() }
972 }
973
974 pub fn raw_nodes(&self) -> &[Node<N, Ix>]
979 {
980 &self.nodes
981 }
982
983 pub fn raw_edges(&self) -> &[Edge<E, Ix>]
985 {
986 &self.edges
987 }
988
989 pub fn into_nodes_edges(self) -> (Vec<Node<N, Ix>>, Vec<Edge<E, Ix>>) {
991 (self.nodes, self.edges)
992 }
993
994 pub fn first_edge(&self, a: NodeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>>
996 {
997 match self.nodes.get(a.index()) {
998 None => None,
999 Some(node) => {
1000 let edix = node.next[dir.index()];
1001 if edix == EdgeIndex::end() {
1002 None
1003 } else { Some(edix) }
1004 }
1005 }
1006 }
1007
1008 pub fn next_edge(&self, e: EdgeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>>
1010 {
1011 match self.edges.get(e.index()) {
1012 None => None,
1013 Some(node) => {
1014 let edix = node.next[dir.index()];
1015 if edix == EdgeIndex::end() {
1016 None
1017 } else { Some(edix) }
1018 }
1019 }
1020 }
1021
1022 pub fn index_twice_mut<T, U>(&mut self, i: T, j: U)
1056 -> (&mut <Self as Index<T>>::Output,
1057 &mut <Self as Index<U>>::Output)
1058 where Self: IndexMut<T> + IndexMut<U>,
1059 T: GraphIndex,
1060 U: GraphIndex,
1061 {
1062 assert!(T::is_node_index() != U::is_node_index() ||
1063 i.index() != j.index());
1064
1065 unsafe {
1067 let self_mut = self as *mut _;
1068 (<Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
1069 <Self as IndexMut<U>>::index_mut(&mut *self_mut, j))
1070 }
1071 }
1072
1073 pub fn reverse(&mut self) {
1075 for edge in &mut self.edges {
1079 edge.node.swap(0, 1);
1080 edge.next.swap(0, 1);
1081 }
1082 for node in &mut self.nodes {
1083 node.next.swap(0, 1);
1084 }
1085 }
1086
1087 pub fn clear(&mut self) {
1089 self.nodes.clear();
1090 self.edges.clear();
1091 }
1092
1093 pub fn clear_edges(&mut self) {
1095 self.edges.clear();
1096 for node in &mut self.nodes {
1097 node.next = [EdgeIndex::end(), EdgeIndex::end()];
1098 }
1099 }
1100
1101 pub fn capacity(&self) -> (usize, usize) {
1103 (self.nodes.capacity(), self.edges.capacity())
1104 }
1105
1106 pub fn reserve_nodes(&mut self, additional: usize) {
1111 self.nodes.reserve(additional);
1112 }
1113
1114 pub fn reserve_edges(&mut self, additional: usize) {
1119 self.edges.reserve(additional);
1120 }
1121
1122 pub fn reserve_exact_nodes(&mut self, additional: usize) {
1130 self.nodes.reserve_exact(additional);
1131 }
1132
1133 pub fn reserve_exact_edges(&mut self, additional: usize) {
1141 self.edges.reserve_exact(additional);
1142 }
1143
1144 pub fn shrink_to_fit_nodes(&mut self) {
1146 self.nodes.shrink_to_fit();
1147 }
1148
1149 pub fn shrink_to_fit_edges(&mut self) {
1151 self.edges.shrink_to_fit();
1152 }
1153
1154 pub fn shrink_to_fit(&mut self) {
1156 self.nodes.shrink_to_fit();
1157 self.edges.shrink_to_fit();
1158 }
1159
1160 pub fn retain_nodes<F>(&mut self, mut visit: F)
1168 where F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool
1169 {
1170 for index in self.node_indices().rev() {
1171 if !visit(Frozen(self), index) {
1172 let ret = self.remove_node(index);
1173 debug_assert!(ret.is_some());
1174 let _ = ret;
1175 }
1176 }
1177 }
1178
1179 pub fn retain_edges<F>(&mut self, mut visit: F)
1187 where F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool
1188 {
1189 for index in self.edge_indices().rev() {
1190 if !visit(Frozen(self), index) {
1191 let ret = self.remove_edge(index);
1192 debug_assert!(ret.is_some());
1193 let _ = ret;
1194 }
1195 }
1196 }
1197
1198
1199 pub fn from_edges<I>(iterable: I) -> Self
1217 where I: IntoIterator,
1218 I::Item: IntoWeightedEdge<E>,
1219 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1220 N: Default,
1221 {
1222 let mut g = Self::with_capacity(0, 0);
1223 g.extend_with_edges(iterable);
1224 g
1225 }
1226
1227 pub fn extend_with_edges<I>(&mut self, iterable: I)
1235 where I: IntoIterator,
1236 I::Item: IntoWeightedEdge<E>,
1237 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
1238 N: Default,
1239 {
1240 let iter = iterable.into_iter();
1241 let (low, _) = iter.size_hint();
1242 self.edges.reserve(low);
1243
1244 for elt in iter {
1245 let (source, target, weight) = elt.into_weighted_edge();
1246 let (source, target) = (source.into(), target.into());
1247 let nx = cmp::max(source, target);
1248 while nx.index() >= self.node_count() {
1249 self.add_node(N::default());
1250 }
1251 self.add_edge(source, target, weight);
1252 }
1253 }
1254
1255
1256 pub fn map<'a, F, G, N2, E2>(&'a self, mut node_map: F, mut edge_map: G)
1262 -> Graph<N2, E2, Ty, Ix>
1263 where F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
1264 G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
1265 {
1266 let mut g = Graph::with_capacity(self.node_count(), self.edge_count());
1267 g.nodes.extend(enumerate(&self.nodes).map(|(i, node)|
1268 Node {
1269 weight: node_map(NodeIndex::new(i), &node.weight),
1270 next: node.next,
1271 }));
1272 g.edges.extend(enumerate(&self.edges).map(|(i, edge)|
1273 Edge {
1274 weight: edge_map(EdgeIndex::new(i), &edge.weight),
1275 next: edge.next,
1276 node: edge.node,
1277 }));
1278 g
1279 }
1280
1281 pub fn filter_map<'a, F, G, N2, E2>(&'a self, mut node_map: F, mut edge_map: G)
1294 -> Graph<N2, E2, Ty, Ix>
1295 where F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
1296 G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
1297 {
1298 let mut g = Graph::with_capacity(0, 0);
1299 let mut node_index_map = vec![NodeIndex::end(); self.node_count()];
1301 for (i, node) in enumerate(&self.nodes) {
1302 if let Some(nw) = node_map(NodeIndex::new(i), &node.weight) {
1303 node_index_map[i] = g.add_node(nw);
1304 }
1305 }
1306 for (i, edge) in enumerate(&self.edges) {
1307 let source = node_index_map[edge.source().index()];
1309 let target = node_index_map[edge.target().index()];
1310 if source != NodeIndex::end() && target != NodeIndex::end() {
1311 if let Some(ew) = edge_map(EdgeIndex::new(i), &edge.weight) {
1312 g.add_edge(source, target, ew);
1313 }
1314 }
1315 }
1316 g
1317 }
1318
1319 pub fn into_edge_type<NewTy>(self) -> Graph<N, E, NewTy, Ix> where
1324 NewTy: EdgeType
1325 {
1326 Graph{nodes: self.nodes, edges: self.edges,
1327 ty: PhantomData}
1328 }
1329
1330
1331 #[cfg(feature = "serde-1")]
1335 fn link_edges(&mut self) -> Result<(), NodeIndex<Ix>> {
1337 for (edge_index, edge) in enumerate(&mut self.edges) {
1338 let a = edge.source();
1339 let b = edge.target();
1340 let edge_idx = EdgeIndex::new(edge_index);
1341 match index_twice(&mut self.nodes, a.index(), b.index()) {
1342 Pair::None => return Err(if a > b { a } else { b }),
1343 Pair::One(an) => {
1344 edge.next = an.next;
1345 an.next[0] = edge_idx;
1346 an.next[1] = edge_idx;
1347 }
1348 Pair::Both(an, bn) => {
1349 edge.next = [an.next[0], bn.next[1]];
1351 an.next[0] = edge_idx;
1352 bn.next[1] = edge_idx;
1353 }
1354 }
1355 }
1356 Ok(())
1357 }
1358}
1359
1360pub struct Externals<'a, N: 'a, Ty, Ix: IndexType = DefaultIx> {
1362 iter: iter::Enumerate<slice::Iter<'a, Node<N, Ix>>>,
1363 dir: Direction,
1364 ty: PhantomData<Ty>,
1365}
1366
1367impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix> where
1368 Ty: EdgeType,
1369 Ix: IndexType,
1370{
1371 type Item = NodeIndex<Ix>;
1372 fn next(&mut self) -> Option<NodeIndex<Ix>>
1373 {
1374 let k = self.dir.index();
1375 loop {
1376 match self.iter.next() {
1377 None => return None,
1378 Some((index, node)) => {
1379 if node.next[k] == EdgeIndex::end() &&
1380 (Ty::is_directed() ||
1381 node.next[1-k] == EdgeIndex::end()) {
1382 return Some(NodeIndex::new(index))
1383 } else {
1384 continue
1385 }
1386 },
1387 }
1388 }
1389 }
1390}
1391
1392pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx>
1403{
1404 skip_start: NodeIndex<Ix>,
1406 edges: &'a [Edge<E, Ix>],
1407 next: [EdgeIndex<Ix>; 2],
1408}
1409
1410impl<'a, E, Ix> Iterator for Neighbors<'a, E, Ix> where
1411 Ix: IndexType,
1412{
1413 type Item = NodeIndex<Ix>;
1414
1415 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1416 match self.edges.get(self.next[0].index()) {
1418 None => {}
1419 Some(edge) => {
1420 self.next[0] = edge.next[0];
1421 return Some(edge.node[1]);
1422 }
1423 }
1424 while let Some(edge) = self.edges.get(self.next[1].index()) {
1429 self.next[1] = edge.next[1];
1430 if edge.node[0] != self.skip_start {
1431 return Some(edge.node[0]);
1432 }
1433 }
1434 None
1435 }
1436}
1437
1438
1439impl<'a, E, Ix> Clone for Neighbors<'a, E, Ix>
1440 where Ix: IndexType,
1441{
1442 clone_fields!(Neighbors,
1443 skip_start,
1444 edges,
1445 next,
1446 );
1447}
1448
1449impl<'a, E, Ix> Neighbors<'a, E, Ix>
1450 where Ix: IndexType,
1451{
1452 pub fn detach(&self) -> WalkNeighbors<Ix> {
1458 WalkNeighbors {
1459 skip_start: self.skip_start,
1460 next: self.next
1461 }
1462 }
1463}
1464
1465struct EdgesWalkerMut<'a, E: 'a, Ix: IndexType = DefaultIx> {
1466 edges: &'a mut [Edge<E, Ix>],
1467 next: EdgeIndex<Ix>,
1468 dir: Direction,
1469}
1470
1471fn edges_walker_mut<E, Ix>(edges: &mut [Edge<E, Ix>], next: EdgeIndex<Ix>, dir: Direction)
1472 -> EdgesWalkerMut<E, Ix>
1473 where Ix: IndexType,
1474{
1475 EdgesWalkerMut {
1476 edges: edges,
1477 next: next,
1478 dir: dir
1479 }
1480}
1481
1482impl<'a, E, Ix> EdgesWalkerMut<'a, E, Ix> where
1483 Ix: IndexType,
1484{
1485 fn next_edge(&mut self) -> Option<&mut Edge<E, Ix>> {
1486 self.next().map(|t| t.1)
1487 }
1488
1489 fn next(&mut self) -> Option<(EdgeIndex<Ix>, &mut Edge<E, Ix>)> {
1490 let this_index = self.next;
1491 let k = self.dir.index();
1492 match self.edges.get_mut(self.next.index()) {
1493 None => None,
1494 Some(edge) => {
1495 self.next = edge.next[k];
1496 Some((this_index, edge))
1497 }
1498 }
1499 }
1500}
1501
1502
1503impl<'a, N, E, Ty, Ix> IntoEdges for &'a Graph<N, E, Ty, Ix>
1504 where Ty: EdgeType,
1505 Ix: IndexType,
1506{
1507 type Edges = Edges<'a, E, Ty, Ix>;
1508 fn edges(self, a: Self::NodeId) -> Self::Edges {
1509 self.edges(a)
1510 }
1511}
1512
1513impl<'a, N, E, Ty, Ix> IntoEdgesDirected for &'a Graph<N, E, Ty, Ix>
1514 where Ty: EdgeType,
1515 Ix: IndexType,
1516{
1517 type EdgesDirected = Edges<'a, E, Ty, Ix>;
1518 fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
1519 self.edges_directed(a, dir)
1520 }
1521}
1522
1523
1524pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1526 where Ty: EdgeType,
1527 Ix: IndexType,
1528{
1529 skip_start: NodeIndex<Ix>,
1531 edges: &'a [Edge<E, Ix>],
1532
1533 next: [EdgeIndex<Ix>; 2],
1536
1537 direction: Option<Direction>,
1541 ty: PhantomData<Ty>,
1542}
1543
1544impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1545 where Ty: EdgeType,
1546 Ix: IndexType,
1547{
1548 type Item = EdgeReference<'a, E, Ix>;
1549
1550 fn next(&mut self) -> Option<Self::Item> {
1551 let k = self.direction.unwrap_or(Outgoing).index();
1553 let i = self.next[0].index();
1554 match self.edges.get(i) {
1555 None => {}
1556 Some(&Edge { ref node, ref weight, ref next }) => {
1557 self.next[0] = next[k];
1558 return Some(EdgeReference {
1559 index: edge_index(i),
1560 node: *node,
1561 weight: weight,
1562 });
1563 }
1564 }
1565 if self.direction.is_some() {
1567 return None;
1568 }
1569 debug_assert_eq!(k, 0);
1576 while let Some(edge) = self.edges.get(self.next[1].index()) {
1577 let i = self.next[1].index();
1578 self.next[1] = edge.next[1];
1579 if edge.node[0] != self.skip_start {
1580 return Some(EdgeReference {
1581 index: edge_index(i),
1582 node: swap_pair(edge.node),
1583 weight: &edge.weight,
1584 });
1585 }
1586 }
1587 None
1588 }
1589}
1590
1591fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1592 x.swap(0, 1);
1593 x
1594}
1595
1596impl<'a, E, Ty, Ix> Clone for Edges<'a, E, Ty, Ix>
1597 where Ix: IndexType,
1598 Ty: EdgeType,
1599{
1600 fn clone(&self) -> Self {
1601 Edges {
1602 skip_start: self.skip_start,
1603 edges: self.edges,
1604 next: self.next,
1605 direction: self.direction,
1606 ty: self.ty,
1607 }
1608 }
1609}
1610
1611pub struct NodeWeightsMut<'a, N: 'a, Ix: IndexType = DefaultIx> {
1613 nodes: ::std::slice::IterMut<'a, Node<N, Ix>>,
1614}
1615
1616impl<'a, N, Ix> Iterator for NodeWeightsMut<'a, N, Ix> where
1617 Ix: IndexType,
1618{
1619 type Item = &'a mut N;
1620
1621 fn next(&mut self) -> Option<&'a mut N> {
1622 self.nodes.next().map(|node| &mut node.weight)
1623 }
1624
1625 fn size_hint(&self) -> (usize, Option<usize>) {
1626 self.nodes.size_hint()
1627 }
1628}
1629
1630pub struct EdgeWeightsMut<'a, E: 'a, Ix: IndexType = DefaultIx> {
1632 edges: ::std::slice::IterMut<'a, Edge<E, Ix>>,
1633}
1634
1635impl<'a, E, Ix> Iterator for EdgeWeightsMut<'a, E, Ix> where
1636 Ix: IndexType,
1637{
1638 type Item = &'a mut E;
1639
1640 fn next(&mut self) -> Option<&'a mut E> {
1641 self.edges.next().map(|edge| &mut edge.weight)
1642 }
1643
1644 fn size_hint(&self) -> (usize, Option<usize>) {
1645 self.edges.size_hint()
1646 }
1647}
1648
1649impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for Graph<N, E, Ty, Ix> where
1653 Ty: EdgeType,
1654 Ix: IndexType,
1655{
1656 type Output = N;
1657 fn index(&self, index: NodeIndex<Ix>) -> &N {
1658 &self.nodes[index.index()].weight
1659 }
1660}
1661
1662impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for Graph<N, E, Ty, Ix> where
1666 Ty: EdgeType,
1667 Ix: IndexType,
1668{
1669 fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1670 &mut self.nodes[index.index()].weight
1671 }
1672
1673}
1674
1675impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix> where
1679 Ty: EdgeType,
1680 Ix: IndexType,
1681{
1682 type Output = E;
1683 fn index(&self, index: EdgeIndex<Ix>) -> &E {
1684 &self.edges[index.index()].weight
1685 }
1686}
1687
1688impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix> where
1692 Ty: EdgeType,
1693 Ix: IndexType,
1694{
1695 fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
1696 &mut self.edges[index.index()].weight
1697 }
1698}
1699
1700impl<N, E, Ty, Ix> Default for Graph<N, E, Ty, Ix>
1702 where Ty: EdgeType,
1703 Ix: IndexType,
1704{
1705 fn default() -> Self { Self::with_capacity(0, 0) }
1706}
1707
1708pub trait GraphIndex : Copy {
1710 #[doc(hidden)]
1711 fn index(&self) -> usize;
1712 #[doc(hidden)]
1713 fn is_node_index() -> bool;
1714}
1715
1716impl<Ix: IndexType> GraphIndex for NodeIndex<Ix> {
1717 #[inline]
1718 fn index(&self) -> usize { NodeIndex::index(*self) }
1719 #[inline]
1720 fn is_node_index() -> bool { true }
1721}
1722
1723impl<Ix: IndexType> GraphIndex for EdgeIndex<Ix> {
1724 #[inline]
1725 fn index(&self) -> usize { EdgeIndex::index(*self) }
1726 #[inline]
1727 fn is_node_index() -> bool { false }
1728}
1729
1730pub struct WalkNeighbors<Ix> {
1766 skip_start: NodeIndex<Ix>,
1767 next: [EdgeIndex<Ix>; 2],
1768}
1769
1770impl<Ix> Clone for WalkNeighbors<Ix>
1771 where Ix: IndexType,
1772{
1773 fn clone(&self) -> Self {
1774 WalkNeighbors {
1775 skip_start: self.skip_start,
1776 next: self.next,
1777 }
1778 }
1779}
1780
1781impl<Ix: IndexType> WalkNeighbors<Ix> {
1782 pub fn next<N, E, Ty: EdgeType>(&mut self, g: &Graph<N, E, Ty, Ix>)
1789 -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
1790 match g.edges.get(self.next[0].index()) {
1792 None => {}
1793 Some(edge) => {
1794 let ed = self.next[0];
1795 self.next[0] = edge.next[0];
1796 return Some((ed, edge.node[1]));
1797 }
1798 }
1799 while let Some(edge) = g.edges.get(self.next[1].index()) {
1804 let ed = self.next[1];
1805 self.next[1] = edge.next[1];
1806 if edge.node[0] != self.skip_start {
1807 return Some((ed, edge.node[0]));
1808 }
1809 }
1810 None
1811 }
1812
1813 pub fn next_node<N, E, Ty: EdgeType>(&mut self, g: &Graph<N, E, Ty, Ix>)
1814 -> Option<NodeIndex<Ix>>
1815 {
1816 self.next(g).map(|t| t.1)
1817 }
1818
1819 pub fn next_edge<N, E, Ty: EdgeType>(&mut self, g: &Graph<N, E, Ty, Ix>)
1820 -> Option<EdgeIndex<Ix>>
1821 {
1822 self.next(g).map(|t| t.0)
1823 }
1824}
1825
1826#[derive(Clone, Debug)]
1828pub struct NodeIndices<Ix = DefaultIx> {
1829 r: Range<usize>,
1830 ty: PhantomData<fn() -> Ix>,
1831}
1832
1833impl<Ix: IndexType> Iterator for NodeIndices<Ix> {
1834 type Item = NodeIndex<Ix>;
1835
1836 fn next(&mut self) -> Option<Self::Item> {
1837 self.r.next().map(node_index)
1838 }
1839
1840 fn size_hint(&self) -> (usize, Option<usize>) {
1841 self.r.size_hint()
1842 }
1843}
1844
1845impl<Ix: IndexType> DoubleEndedIterator for NodeIndices<Ix> {
1846 fn next_back(&mut self) -> Option<Self::Item> {
1847 self.r.next_back().map(node_index)
1848 }
1849}
1850
1851impl<Ix: IndexType> ExactSizeIterator for NodeIndices<Ix> {}
1852
1853#[derive(Clone, Debug)]
1855pub struct EdgeIndices<Ix = DefaultIx> {
1856 r: Range<usize>,
1857 ty: PhantomData<fn() -> Ix>,
1858}
1859
1860impl<Ix: IndexType> Iterator for EdgeIndices<Ix> {
1861 type Item = EdgeIndex<Ix>;
1862
1863 fn next(&mut self) -> Option<Self::Item> {
1864 self.r.next().map(edge_index)
1865 }
1866
1867 fn size_hint(&self) -> (usize, Option<usize>) {
1868 self.r.size_hint()
1869 }
1870}
1871
1872impl<Ix: IndexType> DoubleEndedIterator for EdgeIndices<Ix> {
1873 fn next_back(&mut self) -> Option<Self::Item> {
1874 self.r.next_back().map(edge_index)
1875 }
1876}
1877
1878impl<Ix: IndexType> ExactSizeIterator for EdgeIndices<Ix> {}
1879
1880#[derive(Debug)]
1882pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
1883 index: EdgeIndex<Ix>,
1884 node: [NodeIndex<Ix>; 2],
1885 weight: &'a E,
1886}
1887
1888impl<'a, E, Ix: IndexType> Clone for EdgeReference<'a, E, Ix> {
1889 fn clone(&self) -> Self {
1890 *self
1891 }
1892}
1893
1894impl<'a, E, Ix: IndexType> Copy for EdgeReference<'a, E, Ix> { }
1895
1896impl<'a, E, Ix: IndexType> PartialEq for EdgeReference<'a, E, Ix>
1897 where E: PartialEq,
1898{
1899 fn eq(&self, rhs: &Self) -> bool {
1900 self.index == rhs.index && self.weight == rhs.weight
1901 }
1902}
1903
1904impl<'a, N, E, Ty, Ix> IntoNodeReferences for &'a Graph<N, E, Ty, Ix>
1905 where Ty: EdgeType,
1906 Ix: IndexType,
1907{
1908 type NodeRef = (NodeIndex<Ix>, &'a N);
1909 type NodeReferences = NodeReferences<'a, N, Ix>;
1910 fn node_references(self) -> Self::NodeReferences {
1911 NodeReferences {
1912 iter: self.nodes.iter().enumerate()
1913 }
1914 }
1915}
1916
1917pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
1919 iter: iter::Enumerate<slice::Iter<'a, Node<N, Ix>>>,
1920}
1921
1922impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
1923 where Ix: IndexType
1924{
1925 type Item = (NodeIndex<Ix>, &'a N);
1926
1927 fn next(&mut self) -> Option<Self::Item> {
1928 self.iter.next().map(|(i, node)|
1929 (node_index(i), &node.weight)
1930 )
1931 }
1932
1933 fn size_hint(&self) -> (usize, Option<usize>) {
1934 self.iter.size_hint()
1935 }
1936}
1937
1938impl<'a, N, Ix> DoubleEndedIterator for NodeReferences<'a, N, Ix>
1939 where Ix: IndexType
1940{
1941 fn next_back(&mut self) -> Option<Self::Item> {
1942 self.iter.next_back().map(|(i, node)|
1943 (node_index(i), &node.weight)
1944 )
1945 }
1946}
1947
1948impl<'a, N, Ix> ExactSizeIterator for NodeReferences<'a, N, Ix>
1949 where Ix: IndexType
1950{ }
1951
1952impl<'a, Ix, E> EdgeReference<'a, E, Ix>
1953 where Ix: IndexType,
1954{
1955 pub fn weight(&self) -> &'a E { self.weight }
1960}
1961
1962impl<'a, Ix, E> EdgeRef for EdgeReference<'a, E, Ix>
1963 where Ix: IndexType,
1964{
1965 type NodeId = NodeIndex<Ix>;
1966 type EdgeId = EdgeIndex<Ix>;
1967 type Weight = E;
1968
1969 fn source(&self) -> Self::NodeId { self.node[0] }
1970 fn target(&self) -> Self::NodeId { self.node[1] }
1971 fn weight(&self) -> &E { self.weight }
1972 fn id(&self) -> Self::EdgeId { self.index }
1973}
1974
1975
1976pub struct EdgeReferences<'a, E: 'a, Ix: IndexType = DefaultIx> {
1978 iter: iter::Enumerate<slice::Iter<'a, Edge<E, Ix>>>,
1979}
1980
1981impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
1982 where Ix: IndexType
1983{
1984 type Item = EdgeReference<'a, E, Ix>;
1985
1986 fn next(&mut self) -> Option<Self::Item> {
1987 self.iter.next().map(|(i, edge)|
1988 EdgeReference {
1989 index: edge_index(i),
1990 node: edge.node,
1991 weight: &edge.weight,
1992 }
1993 )
1994 }
1995
1996 fn size_hint(&self) -> (usize, Option<usize>) {
1997 self.iter.size_hint()
1998 }
1999}
2000
2001impl<'a, E, Ix> DoubleEndedIterator for EdgeReferences<'a, E, Ix>
2002 where Ix: IndexType
2003{
2004 fn next_back(&mut self) -> Option<Self::Item> {
2005 self.iter.next_back().map(|(i, edge)|
2006 EdgeReference {
2007 index: edge_index(i),
2008 node: edge.node,
2009 weight: &edge.weight,
2010 }
2011 )
2012 }
2013}
2014
2015impl<'a, E, Ix> ExactSizeIterator for EdgeReferences<'a, E, Ix>
2016 where Ix: IndexType
2017{}
2018
2019#[cfg(feature = "stable_graph")]
2020pub mod stable_graph;
2021mod frozen;
2022
2023pub struct Frozen<'a, G: 'a>(&'a mut G);
2035