1use std::cmp;
7use std::fmt;
8use std::iter;
9use std::marker::PhantomData;
10use std::mem::replace;
11use std::mem::size_of;
12use std::ops::{Index, IndexMut};
13use std::slice;
14
15use {
16 Graph,
17 EdgeType,
18 Directed,
19 Undirected,
20 Direction,
21 Incoming,
22 Outgoing,
23};
24
25use iter_format::{
26 IterFormatExt,
27 NoPretty,
28 DebugMap,
29};
30use iter_utils::IterUtilsExt;
31
32use super::{
33 Edge,
34 index_twice,
35 Node,
36 DIRECTIONS,
37 Pair,
38 Frozen,
39};
40use IntoWeightedEdge;
41use visit::{
42 EdgeRef,
43 IntoNodeReferences,
44 IntoEdges,
45 IntoEdgesDirected,
46 IntoEdgeReferences,
47 NodeIndexable,
48};
49
50#[doc(no_inline)]
52pub use graph::{
53 NodeIndex,
54 EdgeIndex,
55 GraphIndex,
56 IndexType,
57 DefaultIx,
58 node_index,
59 edge_index,
60};
61
62use util::enumerate;
63
64#[cfg(feature = "serde-1")]
65mod serialization;
66
67pub struct StableGraph<N, E, Ty = Directed, Ix = DefaultIx>
104{
105 g: Graph<Option<N>, Option<E>, Ty, Ix>,
106 node_count: usize,
107 edge_count: usize,
108
109 free_node: NodeIndex<Ix>,
117 free_edge: EdgeIndex<Ix>,
118}
119
120pub type StableDiGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Directed, Ix>;
125
126pub type StableUnGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Undirected, Ix>;
131
132impl<N, E, Ty, Ix> fmt::Debug for StableGraph<N, E, Ty, Ix>
133 where N: fmt::Debug,
134 E: fmt::Debug,
135 Ty: EdgeType,
136 Ix: IndexType,
137{
138 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139 let etype = if self.is_directed() { "Directed" } else { "Undirected" };
140 let mut fmt_struct = f.debug_struct("StableGraph");
141 fmt_struct.field("Ty", &etype);
142 fmt_struct.field("node_count", &self.node_count);
143 fmt_struct.field("edge_count", &self.edge_count);
144 if self.g.edges.iter().any(|e| e.weight.is_some()) {
145 fmt_struct.field("edges", &self.g.edges.iter()
146 .filter(|e| e.weight.is_some())
147 .map(|e| NoPretty((e.source().index(), e.target().index())))
148 .format(", "));
149 }
150 if size_of::<N>() != 0 {
152 fmt_struct.field("node weights",
153 &DebugMap(||
154 self.g.nodes.iter()
155 .map(|n| n.weight.as_ref())
156 .enumerate()
157 .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
158 ));
159 }
160 if size_of::<E>() != 0 {
161 fmt_struct.field("edge weights",
162 &DebugMap(||
163 self.g.edges.iter()
164 .map(|n| n.weight.as_ref())
165 .enumerate()
166 .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
167 ));
168 }
169 fmt_struct.field("free_node", &self.free_node);
170 fmt_struct.field("free_edge", &self.free_edge);
171 fmt_struct.finish()
172 }
173}
174
175
176impl<N, E> StableGraph<N, E, Directed> {
177 pub fn new() -> Self {
183 Self::with_capacity(0, 0)
184 }
185}
186
187impl<N, E, Ty, Ix> StableGraph<N, E, Ty, Ix>
188 where Ty: EdgeType,
189 Ix: IndexType,
190{
191 pub fn with_capacity(nodes: usize, edges: usize) -> Self {
193 StableGraph {
194 g: Graph::with_capacity(nodes, edges),
195 node_count: 0,
196 edge_count: 0,
197 free_node: NodeIndex::end(),
198 free_edge: EdgeIndex::end(),
199 }
200 }
201
202 pub fn capacity(&self) -> (usize, usize) {
204 self.g.capacity()
205 }
206
207 pub fn clear(&mut self) {
209 self.node_count = 0;
210 self.edge_count = 0;
211 self.free_node = NodeIndex::end();
212 self.free_edge = EdgeIndex::end();
213 self.g.clear();
214 }
215
216 pub fn clear_edges(&mut self) {
218 self.edge_count = 0;
219 self.free_edge = EdgeIndex::end();
220 self.g.edges.clear();
221 for node in &mut self.g.nodes {
223 if let Some(_) = node.weight {
224 node.next = [EdgeIndex::end(), EdgeIndex::end()];
225 }
226 }
227 }
228
229 pub fn node_count(&self) -> usize {
233 self.node_count
234 }
235
236 pub fn edge_count(&self) -> usize {
240 self.edge_count
241 }
242
243 #[inline]
245 pub fn is_directed(&self) -> bool {
246 Ty::is_directed()
247 }
248
249 pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
258 let index = if self.free_node != NodeIndex::end() {
259 let node_idx = self.free_node;
260 let node_slot = &mut self.g.nodes[node_idx.index()];
261 let _old = replace(&mut node_slot.weight, Some(weight));
262 debug_assert!(_old.is_none());
263 self.free_node = node_slot.next[0]._into_node();
264 node_slot.next[0] = EdgeIndex::end();
265 node_idx
266 } else {
267 self.g.add_node(Some(weight))
268 };
269 self.node_count += 1;
270 index
271 }
272
273 fn add_vacant_node(&mut self, free_node: &mut NodeIndex<Ix>) {
275 let node_idx = self.g.add_node(None);
276 let node_slot = &mut self.g.nodes[node_idx.index()];
278 node_slot.next[0] = free_node._into_edge();
279 *free_node = node_idx;
280 }
281
282 pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N> {
293 let node_weight = match self.g.nodes.get_mut(a.index()) {
294 None => return None,
295 Some(n) => n.weight.take(),
296 };
297 if let None = node_weight {
298 return None;
299 }
300 for d in &DIRECTIONS {
301 let k = d.index();
302
303 loop {
305 let next = self.g.nodes[a.index()].next[k];
306 if next == EdgeIndex::end() {
307 break
308 }
309 let ret = self.remove_edge(next);
310 debug_assert!(ret.is_some());
311 let _ = ret;
312 }
313 }
314
315 let node_slot = &mut self.g.nodes[a.index()];
316 node_slot.next = [self.free_node._into_edge(), EdgeIndex::end()];
319 self.free_node = a;
320 self.node_count -= 1;
321
322 node_weight
323 }
324
325 pub fn contains_node(&self, a: NodeIndex<Ix>) -> bool {
326 self.get_node(a).is_some()
327 }
328
329 fn get_node(&self, a: NodeIndex<Ix>) -> Option<&Node<Option<N>, Ix>> {
331 self.g.nodes.get(a.index())
332 .and_then(|node| node.weight.as_ref().map(move |_| node))
333 }
334
335 pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E)
348 -> EdgeIndex<Ix>
349 {
350 let edge_idx;
351 let mut new_edge = None::<Edge<_, _>>;
352 {
353 let edge: &mut Edge<_, _>;
354
355 if self.free_edge != EdgeIndex::end() {
356 edge_idx = self.free_edge;
357 edge = &mut self.g.edges[edge_idx.index()];
358 let _old = replace(&mut edge.weight, Some(weight));
359 debug_assert!(_old.is_none());
360 self.free_edge = edge.next[0];
361 edge.node = [a, b];
362 } else {
363 edge_idx = EdgeIndex::new(self.g.edges.len());
364 assert!(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx);
365 new_edge = Some(Edge {
366 weight: Some(weight),
367 node: [a, b],
368 next: [EdgeIndex::end(); 2],
369 });
370 edge = new_edge.as_mut().unwrap();
371 }
372
373 let wrong_index = match index_twice(&mut self.g.nodes, a.index(), b.index()) {
374 Pair::None => Some(cmp::max(a.index(), b.index())),
375 Pair::One(an) => {
376 if an.weight.is_none() {
377 Some(a.index())
378 } else {
379 edge.next = an.next;
380 an.next[0] = edge_idx;
381 an.next[1] = edge_idx;
382 None
383 }
384 }
385 Pair::Both(an, bn) => {
386 if an.weight.is_none() {
388 Some(a.index())
389 } else if bn.weight.is_none() {
390 Some(b.index())
391 } else {
392 edge.next = [an.next[0], bn.next[1]];
393 an.next[0] = edge_idx;
394 bn.next[1] = edge_idx;
395 None
396 }
397 }
398 };
399 if let Some(i) = wrong_index {
400 panic!("StableGraph::add_edge: node index {} is not a node in the graph", i);
401 }
402 self.edge_count += 1;
403 }
404 if let Some(edge) = new_edge {
405 self.g.edges.push(edge);
406 }
407 edge_idx
408 }
409
410 fn add_vacant_edge(&mut self, free_edge: &mut EdgeIndex<Ix>) {
412 let edge_idx = EdgeIndex::new(self.g.edges.len());
413 debug_assert!(edge_idx != EdgeIndex::end());
414 let mut edge = Edge {
415 weight: None,
416 node: [NodeIndex::end(); 2],
417 next: [EdgeIndex::end(); 2],
418 };
419 edge.next[0] = *free_edge;
420 *free_edge = edge_idx;
421 self.g.edges.push(edge);
422 }
423
424 pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E)
434 -> EdgeIndex<Ix>
435 {
436 if let Some(ix) = self.find_edge(a, b) {
437 self[ix] = weight;
438 return ix;
439 }
440 self.add_edge(a, b, weight)
441 }
442
443 pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
450 let (is_edge, edge_node, edge_next) = match self.g.edges.get(e.index()) {
454 None => return None,
455 Some(x) => (x.weight.is_some(), x.node, x.next),
456 };
457 if !is_edge {
458 return None;
459 }
460
461 self.g.change_edge_links(edge_node, e, edge_next);
464
465 let edge = &mut self.g.edges[e.index()];
467 edge.next = [self.free_edge, EdgeIndex::end()];
468 edge.node = [NodeIndex::end(), NodeIndex::end()];
469 self.free_edge = e;
470 self.edge_count -= 1;
471 edge.weight.take()
472 }
473
474 pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
478 match self.g.nodes.get(a.index()) {
479 Some(no) => no.weight.as_ref(),
480 None => None,
481 }
482 }
483
484 pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
488 match self.g.nodes.get_mut(a.index()) {
489 Some(no) => no.weight.as_mut(),
490 None => None,
491 }
492 }
493
494 pub fn node_indices(&self) -> NodeIndices<N, Ix> {
496 NodeIndices {
497 iter: enumerate(self.raw_nodes())
498 }
499 }
500
501 pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
505 match self.g.edges.get(e.index()) {
506 Some(ed) => ed.weight.as_ref(),
507 None => None,
508 }
509 }
510
511 pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
515 match self.g.edges.get_mut(e.index()) {
516 Some(ed) => ed.weight.as_mut(),
517 None => None,
518 }
519 }
520
521 pub fn edge_endpoints(&self, e: EdgeIndex<Ix>)
523 -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)>
524 {
525 match self.g.edges.get(e.index()) {
526 Some(ed) if ed.weight.is_some() => Some((ed.source(), ed.target())),
527 _otherwise => None,
528 }
529 }
530
531 pub fn edge_indices(&self) -> EdgeIndices<E, Ix> {
533 EdgeIndices {
534 iter: enumerate(self.raw_edges())
535 }
536 }
537
538 pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>>
543 {
544 if !self.is_directed() {
545 self.find_edge_undirected(a, b).map(|(ix, _)| ix)
546 } else {
547 match self.get_node(a) {
548 None => None,
549 Some(node) => self.g.find_edge_directed_from_node(node, b)
550 }
551 }
552 }
553
554 pub fn find_edge_undirected(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<(EdgeIndex<Ix>, Direction)>
562 {
563 match self.get_node(a) {
564 None => None,
565 Some(node) => self.g.find_edge_undirected_from_node(node, b),
566 }
567 }
568
569
570 pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
583 self.neighbors_directed(a, Outgoing)
584 }
585
586 pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction)
602 -> Neighbors<E, Ix>
603 {
604 let mut iter = self.neighbors_undirected(a);
605 if self.is_directed() {
606 let k = dir.index();
607 iter.next[1 - k] = EdgeIndex::end();
608 iter.skip_start = NodeIndex::end();
609 }
610 iter
611 }
612
613 pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix>
627 {
628 Neighbors {
629 skip_start: a,
630 edges: &self.g.edges,
631 next: match self.get_node(a) {
632 None => [EdgeIndex::end(), EdgeIndex::end()],
633 Some(n) => n.next,
634 }
635 }
636 }
637
638 pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
646 self.edges_directed(a, Outgoing)
647 }
648
649 pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix>
658 {
659 let mut iter = self.edges_undirected(a);
660 if self.is_directed() {
661 iter.direction = Some(dir);
662 }
663 if self.is_directed() && dir == Incoming {
664 iter.next.swap(0, 1);
665 }
666 iter
667 }
668
669 fn edges_undirected(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
676 Edges {
677 skip_start: a,
678 edges: &self.g.edges,
679 direction: None,
680 next: match self.get_node(a) {
681 None => [EdgeIndex::end(), EdgeIndex::end()],
682 Some(n) => n.next,
683 },
684 ty: PhantomData,
685 }
686 }
687
688 pub fn index_twice_mut<T, U>(&mut self, i: T, j: U)
693 -> (&mut <Self as Index<T>>::Output,
694 &mut <Self as Index<U>>::Output)
695 where Self: IndexMut<T> + IndexMut<U>,
696 T: GraphIndex,
697 U: GraphIndex,
698 {
699 assert!(T::is_node_index() != U::is_node_index() ||
700 i.index() != j.index());
701
702 unsafe {
704 let self_mut = self as *mut _;
705 (<Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
706 <Self as IndexMut<U>>::index_mut(&mut *self_mut, j))
707 }
708 }
709
710 pub fn retain_nodes<F>(&mut self, mut visit: F) where F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool {
726 for i in 0..self.node_bound() {
727 let ix = node_index(i);
728 if self.contains_node(ix) && !visit(Frozen(self), ix) {
729 self.remove_node(ix);
730 }
731 }
732 self.check_free_lists();
733 }
734
735 pub fn retain_edges<F>(&mut self, mut visit: F)
748 where F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool
749 {
750 for i in 0..self.edge_bound() {
751 let ix = edge_index(i);
752 if self.edge_weight(ix).is_some() && !visit(Frozen(self), ix) {
753 self.remove_edge(ix);
754 }
755 }
756 self.check_free_lists();
757 }
758
759 pub fn from_edges<I>(iterable: I) -> Self
777 where I: IntoIterator,
778 I::Item: IntoWeightedEdge<E>,
779 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
780 N: Default,
781 {
782 let mut g = Self::with_capacity(0, 0);
783 g.extend_with_edges(iterable);
784 g
785 }
786
787 pub fn map<'a, F, G, N2, E2>(&'a self, mut node_map: F, mut edge_map: G)
793 -> StableGraph<N2, E2, Ty, Ix>
794 where F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
795 G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
796 {
797 let g = self.g.map(
798 move |i, w| w.as_ref().map(|w| node_map(i, w)),
799 move |i, w| w.as_ref().map(|w| edge_map(i, w)));
800 StableGraph {
801 g: g,
802 node_count: self.node_count,
803 edge_count: self.edge_count,
804 free_node: self.free_node,
805 free_edge: self.free_edge,
806 }
807 }
808
809 pub fn filter_map<'a, F, G, N2, E2>(&'a self, mut node_map: F, mut edge_map: G)
821 -> StableGraph<N2, E2, Ty, Ix>
822 where F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
823 G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
824 {
825 let node_bound = self.node_bound();
826 let edge_bound = self.edge_bound();
827 let mut result_g = StableGraph::with_capacity(node_bound, edge_bound);
828 let mut free_node = NodeIndex::end();
831 let mut free_edge = EdgeIndex::end();
832
833 for (i, node) in enumerate(self.raw_nodes()) {
836 if i >= node_bound { break; }
837 if let Some(node_weight) = node.weight.as_ref() {
838 if let Some(new_weight) = node_map(NodeIndex::new(i), node_weight) {
839 result_g.add_node(new_weight);
840 continue;
841 }
842 }
843 result_g.add_vacant_node(&mut free_node);
844 }
845 for (i, edge) in enumerate(self.raw_edges()) {
846 if i >= edge_bound { break; }
847 let source = edge.source();
848 let target = edge.target();
849 if let Some(edge_weight) = edge.weight.as_ref() {
850 if result_g.contains_node(source) && result_g.contains_node(target) {
851 if let Some(new_weight) = edge_map(EdgeIndex::new(i), edge_weight) {
852 result_g.add_edge(source, target, new_weight);
853 continue;
854 }
855 }
856 }
857 result_g.add_vacant_edge(&mut free_edge);
858 }
859 result_g.free_node = free_node;
860 result_g.free_edge = free_edge;
861 result_g.check_free_lists();
862 result_g
863 }
864
865 pub fn extend_with_edges<I>(&mut self, iterable: I)
873 where I: IntoIterator,
874 I::Item: IntoWeightedEdge<E>,
875 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
876 N: Default,
877 {
878 let iter = iterable.into_iter();
879
880 for elt in iter {
881 let (source, target, weight) = elt.into_weighted_edge();
882 let (source, target) = (source.into(), target.into());
883 let nx = cmp::max(source, target);
884 while nx.index() >= self.node_count() {
885 self.add_node(N::default());
886 }
887 self.add_edge(source, target, weight);
888 }
889 }
890
891 fn raw_nodes(&self) -> &[Node<Option<N>, Ix>] {
895 self.g.raw_nodes()
896 }
897
898 fn raw_edges(&self) -> &[Edge<Option<E>, Ix>] {
899 self.g.raw_edges()
900 }
901
902 fn edge_bound(&self) -> usize {
903 self.edge_references()
904 .next_back()
905 .map_or(0, |edge| edge.id().index() + 1)
906 }
907
908 #[cfg(feature = "serde-1")]
909 fn link_edges(&mut self) -> Result<(), NodeIndex<Ix>> {
911 self.node_count = 0;
913 self.edge_count = 0;
914 let mut free_node = NodeIndex::end();
915 for (node_index, node) in enumerate(&mut self.g.nodes) {
916 if node.weight.is_some() {
917 self.node_count += 1;
918 } else {
919 node.next = [free_node._into_edge(), EdgeIndex::end()];
921 free_node = NodeIndex::new(node_index);
922 }
923 }
924 self.free_node = free_node;
925
926 let mut free_edge = EdgeIndex::end();
927 for (edge_index, edge) in enumerate(&mut self.g.edges) {
928 if edge.weight.is_none() {
929 edge.next = [free_edge, EdgeIndex::end()];
931 free_edge = EdgeIndex::new(edge_index);
932 continue;
933 }
934 let a = edge.source();
935 let b = edge.target();
936 let edge_idx = EdgeIndex::new(edge_index);
937 match index_twice(&mut self.g.nodes, a.index(), b.index()) {
938 Pair::None => return Err(if a > b { a } else { b }),
939 Pair::One(an) => {
940 edge.next = an.next;
941 an.next[0] = edge_idx;
942 an.next[1] = edge_idx;
943 }
944 Pair::Both(an, bn) => {
945 edge.next = [an.next[0], bn.next[1]];
947 an.next[0] = edge_idx;
948 bn.next[1] = edge_idx;
949 }
950 }
951 self.edge_count += 1;
952 }
953 self.free_edge = free_edge;
954 Ok(())
955 }
956
957 #[cfg(not(debug_assertions))]
958 fn check_free_lists(&self) { }
959 #[cfg(debug_assertions)]
960 fn check_free_lists(&self) {
962 let mut free_node = self.free_node;
963 let mut free_node_len = 0;
964 while free_node != NodeIndex::end() {
965 if let Some(n) = self.g.nodes.get(free_node.index()) {
966 if let None = n.weight {
967 free_node = n.next[0]._into_node();
968 free_node_len += 1;
969 continue;
970 }
971 debug_assert!(false, "Corrupt free list: pointing to existing {:?}",
972 free_node.index());
973 }
974 debug_assert!(false, "Corrupt free list: missing {:?}", free_node.index());
975 }
976 debug_assert_eq!(self.node_count(), self.raw_nodes().len() - free_node_len);
977
978 let mut free_edge_len = 0;
979 let mut free_edge = self.free_edge;
980 while free_edge != EdgeIndex::end() {
981 if let Some(n) = self.g.edges.get(free_edge.index()) {
982 if let None = n.weight {
983 free_edge = n.next[0];
984 free_edge_len += 1;
985 continue;
986 }
987 debug_assert!(false, "Corrupt free list: pointing to existing {:?}",
988 free_node.index());
989 }
990 debug_assert!(false, "Corrupt free list: missing {:?}", free_edge.index());
991 }
992 debug_assert_eq!(self.edge_count(), self.raw_edges().len() - free_edge_len);
993 }
994}
995
996impl<N, E, Ty, Ix: IndexType> Clone for StableGraph<N, E, Ty, Ix>
998 where N: Clone, E: Clone,
999{
1000 fn clone(&self) -> Self {
1001 StableGraph {
1002 g: self.g.clone(),
1003 node_count: self.node_count,
1004 edge_count: self.edge_count,
1005 free_node: self.free_node,
1006 free_edge: self.free_edge,
1007 }
1008 }
1009
1010 fn clone_from(&mut self, rhs: &Self) {
1011 self.g.clone_from(&rhs.g);
1012 self.node_count = rhs.node_count;
1013 self.edge_count = rhs.edge_count;
1014 self.free_node = rhs.free_node;
1015 self.free_edge = rhs.free_edge;
1016 }
1017}
1018
1019impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix> where
1023 Ty: EdgeType,
1024 Ix: IndexType,
1025{
1026 type Output = N;
1027 fn index(&self, index: NodeIndex<Ix>) -> &N {
1028 self.node_weight(index).unwrap()
1029 }
1030}
1031
1032impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix> where
1036 Ty: EdgeType,
1037 Ix: IndexType,
1038{
1039 fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1040 self.node_weight_mut(index).unwrap()
1041 }
1042
1043}
1044
1045impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix> where
1049 Ty: EdgeType,
1050 Ix: IndexType,
1051{
1052 type Output = E;
1053 fn index(&self, index: EdgeIndex<Ix>) -> &E {
1054 self.edge_weight(index).unwrap()
1055 }
1056}
1057
1058impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix> where
1062 Ty: EdgeType,
1063 Ix: IndexType,
1064{
1065 fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
1066 self.edge_weight_mut(index).unwrap()
1067 }
1068}
1069
1070impl<N, E, Ty, Ix> Default for StableGraph<N, E, Ty, Ix>
1072 where Ty: EdgeType,
1073 Ix: IndexType,
1074{
1075 fn default() -> Self { Self::with_capacity(0, 0) }
1076}
1077
1078impl<N, E, Ty, Ix> From<Graph<N, E, Ty, Ix>> for StableGraph<N, E, Ty, Ix>
1085 where Ty: EdgeType,
1086 Ix: IndexType,
1087{
1088 fn from(g: Graph<N, E, Ty, Ix>) -> Self {
1089 let nodes = g.nodes.into_iter().map(|e| Node {
1090 weight: Some(e.weight),
1091 next: e.next,
1092 });
1093 let edges = g.edges.into_iter().map(|e| Edge {
1094 weight: Some(e.weight),
1095 node: e.node,
1096 next: e.next,
1097 });
1098 StableGraph {
1099 node_count: nodes.len(),
1100 edge_count: edges.len(),
1101 g: Graph { edges: edges.collect(), nodes: nodes.collect(), ty: g.ty },
1102 free_node: NodeIndex::end(),
1103 free_edge: EdgeIndex::end(),
1104 }
1105 }
1106}
1107
1108impl<N, E, Ty, Ix> From<StableGraph<N, E, Ty, Ix>> for Graph<N, E, Ty, Ix>
1119 where Ty: EdgeType,
1120 Ix: IndexType,
1121{
1122 fn from(graph: StableGraph<N, E, Ty, Ix>) -> Self {
1123 let mut result_g = Graph::with_capacity(graph.node_count(), graph.edge_count());
1124 let mut node_index_map = vec![NodeIndex::end(); graph.node_bound()];
1126
1127 for (i, node) in enumerate(graph.g.nodes) {
1128 if let Some(nw) = node.weight {
1129 node_index_map[i] = result_g.add_node(nw);
1130 }
1131 }
1132 for edge in graph.g.edges {
1133 let source_index = edge.source().index();
1134 let target_index = edge.target().index();
1135 if let Some(ew) = edge.weight {
1136 let source = node_index_map[source_index];
1137 let target = node_index_map[target_index];
1138 debug_assert!(source != NodeIndex::end());
1139 debug_assert!(target != NodeIndex::end());
1140 result_g.add_edge(source, target, ew);
1141 }
1142 }
1143 result_g
1144 }
1145}
1146
1147impl<'a, N, E, Ty, Ix> IntoNodeReferences for &'a StableGraph<N, E, Ty, Ix>
1148 where Ty: EdgeType,
1149 Ix: IndexType,
1150{
1151 type NodeRef = (NodeIndex<Ix>, &'a N);
1152 type NodeReferences = NodeReferences<'a, N, Ix>;
1153 fn node_references(self) -> Self::NodeReferences {
1154 NodeReferences {
1155 iter: enumerate(self.raw_nodes())
1156 }
1157 }
1158}
1159
1160pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
1162 iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1163}
1164
1165impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
1166 where Ix: IndexType
1167{
1168 type Item = (NodeIndex<Ix>, &'a N);
1169
1170 fn next(&mut self) -> Option<Self::Item> {
1171 self.iter.ex_find_map(|(i, node)| {
1172 node.weight.as_ref().map(move |w| (node_index(i), w))
1173 })
1174 }
1175
1176 fn size_hint(&self) -> (usize, Option<usize>) {
1177 let (_, hi) = self.iter.size_hint();
1178 (0, hi)
1179 }
1180}
1181
1182impl<'a, N, Ix> DoubleEndedIterator for NodeReferences<'a, N, Ix>
1183 where Ix: IndexType
1184{
1185 fn next_back(&mut self) -> Option<Self::Item> {
1186 self.iter.ex_rfind_map(|(i, node)| {
1187 node.weight.as_ref().map(move |w| (node_index(i), w))
1188 })
1189 }
1190}
1191
1192#[derive(Debug)]
1194pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
1195 index: EdgeIndex<Ix>,
1196 node: [NodeIndex<Ix>; 2],
1197 weight: &'a E,
1198}
1199
1200impl<'a, E, Ix: IndexType> Clone for EdgeReference<'a, E, Ix> {
1201 fn clone(&self) -> Self {
1202 *self
1203 }
1204}
1205
1206impl<'a, E, Ix: IndexType> Copy for EdgeReference<'a, E, Ix> { }
1207
1208impl<'a, E, Ix: IndexType> PartialEq for EdgeReference<'a, E, Ix>
1209 where E: PartialEq,
1210{
1211 fn eq(&self, rhs: &Self) -> bool {
1212 self.index == rhs.index && self.weight == rhs.weight
1213 }
1214}
1215
1216impl<'a, Ix, E> EdgeReference<'a, E, Ix>
1217 where Ix: IndexType,
1218{
1219 pub fn weight(&self) -> &'a E { self.weight }
1224}
1225
1226impl<'a, Ix, E> EdgeRef for EdgeReference<'a, E, Ix>
1227 where Ix: IndexType,
1228{
1229 type NodeId = NodeIndex<Ix>;
1230 type EdgeId = EdgeIndex<Ix>;
1231 type Weight = E;
1232
1233 fn source(&self) -> Self::NodeId { self.node[0] }
1234 fn target(&self) -> Self::NodeId { self.node[1] }
1235 fn weight(&self) -> &E { self.weight }
1236 fn id(&self) -> Self::EdgeId { self.index }
1237}
1238
1239impl<'a, N, E, Ty, Ix> IntoEdges for &'a StableGraph<N, E, Ty, Ix>
1240 where Ty: EdgeType,
1241 Ix: IndexType,
1242{
1243 type Edges = Edges<'a, E, Ty, Ix>;
1244 fn edges(self, a: Self::NodeId) -> Self::Edges {
1245 self.edges(a)
1246 }
1247}
1248
1249impl<'a, N, E, Ty, Ix> IntoEdgesDirected for &'a StableGraph<N, E, Ty, Ix>
1250 where Ty: EdgeType,
1251 Ix: IndexType,
1252{
1253 type EdgesDirected = Edges<'a, E, Ty, Ix>;
1254 fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
1255 self.edges_directed(a, dir)
1256 }
1257}
1258
1259
1260pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1262 where Ty: EdgeType,
1263 Ix: IndexType,
1264{
1265 skip_start: NodeIndex<Ix>,
1267 edges: &'a [Edge<Option<E>, Ix>],
1268
1269 next: [EdgeIndex<Ix>; 2],
1272
1273 direction: Option<Direction>,
1277 ty: PhantomData<Ty>,
1278}
1279
1280impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1281 where Ty: EdgeType,
1282 Ix: IndexType,
1283{
1284 type Item = EdgeReference<'a, E, Ix>;
1285
1286 fn next(&mut self) -> Option<Self::Item> {
1287 let k = self.direction.unwrap_or(Outgoing).index();
1289 let i = self.next[0].index();
1290 match self.edges.get(i) {
1291 None => {}
1292 Some(&Edge { ref node, weight: Some(ref weight), ref next }) => {
1293 self.next[0] = next[k];
1294 return Some(EdgeReference {
1295 index: edge_index(i),
1296 node: *node,
1297 weight: weight,
1298 });
1299 }
1300 Some(_otherwise) => unreachable!(),
1301 }
1302 if self.direction.is_some() {
1304 return None;
1305 }
1306 debug_assert_eq!(k, 0);
1313 while let Some(edge) = self.edges.get(self.next[1].index()) {
1314 debug_assert!(edge.weight.is_some());
1315 let i = self.next[1].index();
1316 self.next[1] = edge.next[1];
1317 if edge.node[0] != self.skip_start {
1318 return Some(EdgeReference {
1319 index: edge_index(i),
1320 node: swap_pair(edge.node),
1321 weight: edge.weight.as_ref().unwrap(),
1322 });
1323 }
1324 }
1325 None
1326 }
1327}
1328
1329fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1330 x.swap(0, 1);
1331 x
1332}
1333
1334impl<'a, N: 'a, E: 'a, Ty, Ix> IntoEdgeReferences for &'a StableGraph<N, E, Ty, Ix>
1335 where Ty: EdgeType,
1336 Ix: IndexType,
1337{
1338 type EdgeRef = EdgeReference<'a, E, Ix>;
1339 type EdgeReferences = EdgeReferences<'a, E, Ix>;
1340
1341 fn edge_references(self) -> Self::EdgeReferences {
1345 EdgeReferences {
1346 iter: self.g.edges.iter().enumerate()
1347 }
1348 }
1349
1350}
1351
1352pub struct EdgeReferences<'a, E: 'a, Ix: 'a = DefaultIx> {
1354 iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1355}
1356
1357impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
1358 where Ix: IndexType
1359{
1360 type Item = EdgeReference<'a, E, Ix>;
1361
1362 fn next(&mut self) -> Option<Self::Item> {
1363 self.iter.ex_find_map(|(i, edge)|
1364 edge.weight.as_ref().map(move |weight| {
1365 EdgeReference {
1366 index: edge_index(i),
1367 node: edge.node,
1368 weight: weight,
1369 }
1370 }))
1371 }
1372}
1373
1374impl<'a, E, Ix> DoubleEndedIterator for EdgeReferences<'a, E, Ix>
1375 where Ix: IndexType
1376{
1377 fn next_back(&mut self) -> Option<Self::Item> {
1378 self.iter.ex_rfind_map(|(i, edge)|
1379 edge.weight.as_ref().map(move |weight| {
1380 EdgeReference {
1381 index: edge_index(i),
1382 node: edge.node,
1383 weight: weight,
1384 }
1385 }))
1386 }
1387}
1388
1389
1390pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx>
1394{
1395 skip_start: NodeIndex<Ix>,
1397 edges: &'a [Edge<Option<E>, Ix>],
1398 next: [EdgeIndex<Ix>; 2],
1399}
1400
1401impl<'a, E, Ix> Neighbors<'a, E, Ix>
1402 where Ix: IndexType,
1403{
1404 pub fn detach(&self) -> WalkNeighbors<Ix> {
1410 WalkNeighbors {
1411 inner: super::WalkNeighbors {
1412 skip_start: self.skip_start,
1413 next: self.next
1414 },
1415 }
1416 }
1417}
1418
1419impl<'a, E, Ix> Iterator for Neighbors<'a, E, Ix> where
1420 Ix: IndexType,
1421{
1422 type Item = NodeIndex<Ix>;
1423
1424 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1425 match self.edges.get(self.next[0].index()) {
1427 None => {}
1428 Some(edge) => {
1429 debug_assert!(edge.weight.is_some());
1430 self.next[0] = edge.next[0];
1431 return Some(edge.node[1]);
1432 }
1433 }
1434 while let Some(edge) = self.edges.get(self.next[1].index()) {
1439 debug_assert!(edge.weight.is_some());
1440 self.next[1] = edge.next[1];
1441 if edge.node[0] != self.skip_start {
1442 return Some(edge.node[0]);
1443 }
1444 }
1445 None
1446 }
1447}
1448
1449pub struct WalkNeighbors<Ix> {
1486 inner: super::WalkNeighbors<Ix>,
1487}
1488
1489impl<Ix: IndexType> Clone for WalkNeighbors<Ix> {
1490 clone_fields!(WalkNeighbors, inner);
1491}
1492
1493impl<Ix: IndexType> WalkNeighbors<Ix> {
1494 pub fn next<N, E, Ty: EdgeType>(&mut self, g: &StableGraph<N, E, Ty, Ix>)
1501 -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
1502 self.inner.next(&g.g)
1503 }
1504
1505 pub fn next_node<N, E, Ty: EdgeType>(&mut self, g: &StableGraph<N, E, Ty, Ix>)
1506 -> Option<NodeIndex<Ix>>
1507 {
1508 self.next(g).map(|t| t.1)
1509 }
1510
1511 pub fn next_edge<N, E, Ty: EdgeType>(&mut self, g: &StableGraph<N, E, Ty, Ix>)
1512 -> Option<EdgeIndex<Ix>>
1513 {
1514 self.next(g).map(|t| t.0)
1515 }
1516}
1517
1518pub struct NodeIndices<'a, N: 'a, Ix: 'a = DefaultIx> {
1520 iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1521}
1522
1523impl<'a, N, Ix: IndexType> Iterator for NodeIndices<'a, N, Ix> {
1524 type Item = NodeIndex<Ix>;
1525
1526 fn next(&mut self) -> Option<Self::Item> {
1527 self.iter.ex_find_map(|(i, node)| {
1528 if node.weight.is_some() {
1529 Some(node_index(i))
1530 } else { None }
1531 })
1532 }
1533
1534 fn size_hint(&self) -> (usize, Option<usize>) {
1535 let (_, hi) = self.iter.size_hint();
1536 (0, hi)
1537 }
1538}
1539
1540impl<'a, N, Ix: IndexType> DoubleEndedIterator for NodeIndices<'a, N, Ix> {
1541 fn next_back(&mut self) -> Option<Self::Item> {
1542 self.iter.ex_rfind_map(|(i, node)| {
1543 if node.weight.is_some() {
1544 Some(node_index(i))
1545 } else { None }
1546 })
1547 }
1548}
1549
1550impl<N, E, Ty, Ix> NodeIndexable for StableGraph<N, E, Ty, Ix>
1551 where Ty: EdgeType,
1552 Ix: IndexType,
1553{
1554 fn node_bound(&self) -> usize {
1556 self.node_indices()
1557 .next_back()
1558 .map_or(0, |i| i.index() + 1)
1559 }
1560 fn to_index(&self, ix: NodeIndex<Ix>) -> usize { ix.index() }
1561 fn from_index(&self, ix: usize) -> Self::NodeId { NodeIndex::new(ix) }
1562}
1563
1564pub struct EdgeIndices<'a, E: 'a, Ix: 'a = DefaultIx> {
1566 iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1567}
1568
1569impl<'a, E, Ix: IndexType> Iterator for EdgeIndices<'a, E, Ix> {
1570 type Item = EdgeIndex<Ix>;
1571
1572 fn next(&mut self) -> Option<Self::Item> {
1573 self.iter.ex_find_map(|(i, node)| {
1574 if node.weight.is_some() {
1575 Some(edge_index(i))
1576 } else { None }
1577 })
1578 }
1579
1580 fn size_hint(&self) -> (usize, Option<usize>) {
1581 let (_, hi) = self.iter.size_hint();
1582 (0, hi)
1583 }
1584}
1585
1586impl<'a, E, Ix: IndexType> DoubleEndedIterator for EdgeIndices<'a, E, Ix> {
1587 fn next_back(&mut self) -> Option<Self::Item> {
1588 self.iter.ex_rfind_map(|(i, node)| {
1589 if node.weight.is_some() {
1590 Some(edge_index(i))
1591 } else { None }
1592 })
1593 }
1594}
1595
1596
1597#[test]
1598fn stable_graph() {
1599 let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
1600 let a = gr.add_node(0);
1601 let b = gr.add_node(1);
1602 let c = gr.add_node(2);
1603 let _ed = gr.add_edge(a, b, 1);
1604 println!("{:?}", gr);
1605 gr.remove_node(b);
1606 println!("{:?}", gr);
1607 let d = gr.add_node(3);
1608 println!("{:?}", gr);
1609 gr.check_free_lists();
1610 gr.remove_node(a);
1611 gr.check_free_lists();
1612 gr.remove_node(c);
1613 gr.check_free_lists();
1614 println!("{:?}", gr);
1615 gr.add_edge(d, d, 2);
1616 println!("{:?}", gr);
1617
1618 let e = gr.add_node(4);
1619 gr.add_edge(d, e, 3);
1620 println!("{:?}", gr);
1621 for neigh in gr.neighbors(d) {
1622 println!("edge {:?} -> {:?}", d, neigh);
1623 }
1624 gr.check_free_lists();
1625}
1626
1627#[test]
1628fn dfs() {
1629 use visit::Dfs;
1630
1631 let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
1632 let a = gr.add_node("a");
1633 let b = gr.add_node("b");
1634 let c = gr.add_node("c");
1635 let d = gr.add_node("d");
1636 gr.add_edge(a, b, 1);
1637 gr.add_edge(a, c, 2);
1638 gr.add_edge(b, c, 3);
1639 gr.add_edge(b, d, 4);
1640 gr.add_edge(c, d, 5);
1641 gr.add_edge(d, b, 6);
1642 gr.add_edge(c, b, 7);
1643 println!("{:?}", gr);
1644
1645 let mut dfs = Dfs::new(&gr, a);
1646 while let Some(next) = dfs.next(&gr) {
1647 println!("dfs visit => {:?}, weight={:?}", next, &gr[next]);
1648 }
1649}
1650
1651#[test]
1652fn test_retain_nodes() {
1653 let mut gr = StableGraph::<_, _>::with_capacity(6, 6);
1654 let a = gr.add_node("a");
1655 let f = gr.add_node("f");
1656 let b = gr.add_node("b");
1657 let c = gr.add_node("c");
1658 let d = gr.add_node("d");
1659 let e = gr.add_node("e");
1660 gr.add_edge(a, b, 1);
1661 gr.add_edge(a, c, 2);
1662 gr.add_edge(b, c, 3);
1663 gr.add_edge(b, d, 4);
1664 gr.add_edge(c, d, 5);
1665 gr.add_edge(d, b, 6);
1666 gr.add_edge(c, b, 7);
1667 gr.add_edge(d, e, 8);
1668 gr.remove_node(f);
1669
1670 assert_eq!(gr.node_count(), 5);
1671 assert_eq!(gr.edge_count(), 8);
1672 gr.retain_nodes(|frozen_gr, ix| {frozen_gr[ix] >= "c"});
1673 assert_eq!(gr.node_count(), 3);
1674 assert_eq!(gr.edge_count(), 2);
1675
1676 gr.check_free_lists();
1677}