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 crate::{Directed, Direction, EdgeType, Graph, Incoming, Outgoing, Undirected};
16
17use crate::iter_format::{DebugMap, IterFormatExt, NoPretty};
18use crate::iter_utils::IterUtilsExt;
19
20use super::{index_twice, Edge, Frozen, Node, Pair, DIRECTIONS};
21use crate::visit::{
22 EdgeRef, IntoEdgeReferences, IntoEdges, IntoEdgesDirected, IntoNodeReferences, NodeIndexable,
23};
24use crate::IntoWeightedEdge;
25
26#[doc(no_inline)]
28pub use crate::graph::{
29 edge_index, node_index, DefaultIx, EdgeIndex, GraphIndex, IndexType, NodeIndex,
30};
31
32use crate::util::enumerate;
33
34#[cfg(feature = "serde-1")]
35mod serialization;
36
37pub struct StableGraph<N, E, Ty = Directed, Ix = DefaultIx> {
74 g: Graph<Option<N>, Option<E>, Ty, Ix>,
75 node_count: usize,
76 edge_count: usize,
77
78 free_node: NodeIndex<Ix>,
86 free_edge: EdgeIndex<Ix>,
87}
88
89pub type StableDiGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Directed, Ix>;
94
95pub type StableUnGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Undirected, Ix>;
100
101impl<N, E, Ty, Ix> fmt::Debug for StableGraph<N, E, Ty, Ix>
102where
103 N: fmt::Debug,
104 E: fmt::Debug,
105 Ty: EdgeType,
106 Ix: IndexType,
107{
108 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109 let etype = if self.is_directed() {
110 "Directed"
111 } else {
112 "Undirected"
113 };
114 let mut fmt_struct = f.debug_struct("StableGraph");
115 fmt_struct.field("Ty", &etype);
116 fmt_struct.field("node_count", &self.node_count);
117 fmt_struct.field("edge_count", &self.edge_count);
118 if self.g.edges.iter().any(|e| e.weight.is_some()) {
119 fmt_struct.field(
120 "edges",
121 &self
122 .g
123 .edges
124 .iter()
125 .filter(|e| e.weight.is_some())
126 .map(|e| NoPretty((e.source().index(), e.target().index())))
127 .format(", "),
128 );
129 }
130 if size_of::<N>() != 0 {
132 fmt_struct.field(
133 "node weights",
134 &DebugMap(|| {
135 self.g
136 .nodes
137 .iter()
138 .map(|n| n.weight.as_ref())
139 .enumerate()
140 .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
141 }),
142 );
143 }
144 if size_of::<E>() != 0 {
145 fmt_struct.field(
146 "edge weights",
147 &DebugMap(|| {
148 self.g
149 .edges
150 .iter()
151 .map(|n| n.weight.as_ref())
152 .enumerate()
153 .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
154 }),
155 );
156 }
157 fmt_struct.field("free_node", &self.free_node);
158 fmt_struct.field("free_edge", &self.free_edge);
159 fmt_struct.finish()
160 }
161}
162
163impl<N, E> StableGraph<N, E, Directed> {
164 pub fn new() -> Self {
170 Self::with_capacity(0, 0)
171 }
172}
173
174impl<N, E, Ty, Ix> StableGraph<N, E, Ty, Ix>
175where
176 Ty: EdgeType,
177 Ix: IndexType,
178{
179 pub fn with_capacity(nodes: usize, edges: usize) -> Self {
181 StableGraph {
182 g: Graph::with_capacity(nodes, edges),
183 node_count: 0,
184 edge_count: 0,
185 free_node: NodeIndex::end(),
186 free_edge: EdgeIndex::end(),
187 }
188 }
189
190 pub fn capacity(&self) -> (usize, usize) {
192 self.g.capacity()
193 }
194
195 pub fn clear(&mut self) {
197 self.node_count = 0;
198 self.edge_count = 0;
199 self.free_node = NodeIndex::end();
200 self.free_edge = EdgeIndex::end();
201 self.g.clear();
202 }
203
204 pub fn clear_edges(&mut self) {
206 self.edge_count = 0;
207 self.free_edge = EdgeIndex::end();
208 self.g.edges.clear();
209 for node in &mut self.g.nodes {
211 if node.weight.is_some() {
212 node.next = [EdgeIndex::end(), EdgeIndex::end()];
213 }
214 }
215 }
216
217 pub fn node_count(&self) -> usize {
221 self.node_count
222 }
223
224 pub fn edge_count(&self) -> usize {
228 self.edge_count
229 }
230
231 #[inline]
233 pub fn is_directed(&self) -> bool {
234 Ty::is_directed()
235 }
236
237 pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
246 let index = if self.free_node != NodeIndex::end() {
247 let node_idx = self.free_node;
248 let node_slot = &mut self.g.nodes[node_idx.index()];
249 let _old = replace(&mut node_slot.weight, Some(weight));
250 debug_assert!(_old.is_none());
251 self.free_node = node_slot.next[0]._into_node();
252 node_slot.next[0] = EdgeIndex::end();
253 node_idx
254 } else {
255 self.g.add_node(Some(weight))
256 };
257 self.node_count += 1;
258 index
259 }
260
261 fn add_vacant_node(&mut self, free_node: &mut NodeIndex<Ix>) {
263 let node_idx = self.g.add_node(None);
264 let node_slot = &mut self.g.nodes[node_idx.index()];
266 node_slot.next[0] = free_node._into_edge();
267 *free_node = node_idx;
268 }
269
270 pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N> {
281 let node_weight = self.g.nodes.get_mut(a.index())?.weight.take()?;
282 for d in &DIRECTIONS {
283 let k = d.index();
284
285 loop {
287 let next = self.g.nodes[a.index()].next[k];
288 if next == EdgeIndex::end() {
289 break;
290 }
291 let ret = self.remove_edge(next);
292 debug_assert!(ret.is_some());
293 let _ = ret;
294 }
295 }
296
297 let node_slot = &mut self.g.nodes[a.index()];
298 node_slot.next = [self.free_node._into_edge(), EdgeIndex::end()];
301 self.free_node = a;
302 self.node_count -= 1;
303
304 Some(node_weight)
305 }
306
307 pub fn contains_node(&self, a: NodeIndex<Ix>) -> bool {
308 self.get_node(a).is_some()
309 }
310
311 fn get_node(&self, a: NodeIndex<Ix>) -> Option<&Node<Option<N>, Ix>> {
313 self.g
314 .nodes
315 .get(a.index())
316 .and_then(|node| node.weight.as_ref().map(move |_| node))
317 }
318
319 pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
332 let edge_idx;
333 let mut new_edge = None::<Edge<_, _>>;
334 {
335 let edge: &mut Edge<_, _>;
336
337 if self.free_edge != EdgeIndex::end() {
338 edge_idx = self.free_edge;
339 edge = &mut self.g.edges[edge_idx.index()];
340 let _old = replace(&mut edge.weight, Some(weight));
341 debug_assert!(_old.is_none());
342 self.free_edge = edge.next[0];
343 edge.node = [a, b];
344 } else {
345 edge_idx = EdgeIndex::new(self.g.edges.len());
346 assert!(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx);
347 new_edge = Some(Edge {
348 weight: Some(weight),
349 node: [a, b],
350 next: [EdgeIndex::end(); 2],
351 });
352 edge = new_edge.as_mut().unwrap();
353 }
354
355 let wrong_index = match index_twice(&mut self.g.nodes, a.index(), b.index()) {
356 Pair::None => Some(cmp::max(a.index(), b.index())),
357 Pair::One(an) => {
358 if an.weight.is_none() {
359 Some(a.index())
360 } else {
361 edge.next = an.next;
362 an.next[0] = edge_idx;
363 an.next[1] = edge_idx;
364 None
365 }
366 }
367 Pair::Both(an, bn) => {
368 if an.weight.is_none() {
370 Some(a.index())
371 } else if bn.weight.is_none() {
372 Some(b.index())
373 } else {
374 edge.next = [an.next[0], bn.next[1]];
375 an.next[0] = edge_idx;
376 bn.next[1] = edge_idx;
377 None
378 }
379 }
380 };
381 if let Some(i) = wrong_index {
382 panic!(
383 "StableGraph::add_edge: node index {} is not a node in the graph",
384 i
385 );
386 }
387 self.edge_count += 1;
388 }
389 if let Some(edge) = new_edge {
390 self.g.edges.push(edge);
391 }
392 edge_idx
393 }
394
395 fn add_vacant_edge(&mut self, free_edge: &mut EdgeIndex<Ix>) {
397 let edge_idx = EdgeIndex::new(self.g.edges.len());
398 debug_assert!(edge_idx != EdgeIndex::end());
399 let mut edge = Edge {
400 weight: None,
401 node: [NodeIndex::end(); 2],
402 next: [EdgeIndex::end(); 2],
403 };
404 edge.next[0] = *free_edge;
405 *free_edge = edge_idx;
406 self.g.edges.push(edge);
407 }
408
409 pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
419 if let Some(ix) = self.find_edge(a, b) {
420 self[ix] = weight;
421 return ix;
422 }
423 self.add_edge(a, b, weight)
424 }
425
426 pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
433 let (is_edge, edge_node, edge_next) = match self.g.edges.get(e.index()) {
437 None => return None,
438 Some(x) => (x.weight.is_some(), x.node, x.next),
439 };
440 if !is_edge {
441 return None;
442 }
443
444 self.g.change_edge_links(edge_node, e, edge_next);
447
448 let edge = &mut self.g.edges[e.index()];
450 edge.next = [self.free_edge, EdgeIndex::end()];
451 edge.node = [NodeIndex::end(), NodeIndex::end()];
452 self.free_edge = e;
453 self.edge_count -= 1;
454 edge.weight.take()
455 }
456
457 pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
461 match self.g.nodes.get(a.index()) {
462 Some(no) => no.weight.as_ref(),
463 None => None,
464 }
465 }
466
467 pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
471 match self.g.nodes.get_mut(a.index()) {
472 Some(no) => no.weight.as_mut(),
473 None => None,
474 }
475 }
476
477 pub fn node_weights_mut(&mut self) -> impl Iterator<Item = &mut N> {
482 self.g
483 .node_weights_mut()
484 .flat_map(|maybe_node| maybe_node.iter_mut())
485 }
486
487 pub fn node_indices(&self) -> NodeIndices<N, Ix> {
489 NodeIndices {
490 iter: enumerate(self.raw_nodes()),
491 }
492 }
493
494 pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
498 match self.g.edges.get(e.index()) {
499 Some(ed) => ed.weight.as_ref(),
500 None => None,
501 }
502 }
503
504 pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
508 match self.g.edges.get_mut(e.index()) {
509 Some(ed) => ed.weight.as_mut(),
510 None => None,
511 }
512 }
513
514 pub fn edge_weights_mut(&mut self) -> impl Iterator<Item = &mut E> {
519 self.g
520 .edge_weights_mut()
521 .flat_map(|maybe_edge| maybe_edge.iter_mut())
522 }
523
524 pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)> {
526 match self.g.edges.get(e.index()) {
527 Some(ed) if ed.weight.is_some() => Some((ed.source(), ed.target())),
528 _otherwise => None,
529 }
530 }
531
532 pub fn edge_indices(&self) -> EdgeIndices<E, Ix> {
534 EdgeIndices {
535 iter: enumerate(self.raw_edges()),
536 }
537 }
538
539 pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
544 self.find_edge(a, b).is_some()
545 }
546
547 pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>> {
552 if !self.is_directed() {
553 self.find_edge_undirected(a, b).map(|(ix, _)| ix)
554 } else {
555 match self.get_node(a) {
556 None => None,
557 Some(node) => self.g.find_edge_directed_from_node(node, b),
558 }
559 }
560 }
561
562 pub fn find_edge_undirected(
570 &self,
571 a: NodeIndex<Ix>,
572 b: NodeIndex<Ix>,
573 ) -> Option<(EdgeIndex<Ix>, Direction)> {
574 match self.get_node(a) {
575 None => None,
576 Some(node) => self.g.find_edge_undirected_from_node(node, b),
577 }
578 }
579
580 pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
593 self.neighbors_directed(a, Outgoing)
594 }
595
596 pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix> {
612 let mut iter = self.neighbors_undirected(a);
613 if self.is_directed() {
614 let k = dir.index();
615 iter.next[1 - k] = EdgeIndex::end();
616 iter.skip_start = NodeIndex::end();
617 }
618 iter
619 }
620
621 pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
635 Neighbors {
636 skip_start: a,
637 edges: &self.g.edges,
638 next: match self.get_node(a) {
639 None => [EdgeIndex::end(), EdgeIndex::end()],
640 Some(n) => n.next,
641 },
642 }
643 }
644
645 pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
653 self.edges_directed(a, Outgoing)
654 }
655
656 pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix> {
668 Edges {
669 skip_start: a,
670 edges: &self.g.edges,
671 direction: dir,
672 next: match self.get_node(a) {
673 None => [EdgeIndex::end(), EdgeIndex::end()],
674 Some(n) => n.next,
675 },
676 ty: PhantomData,
677 }
678 }
679
680 pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix> {
692 Externals {
693 iter: self.raw_nodes().iter().enumerate(),
694 dir,
695 ty: PhantomData,
696 }
697 }
698
699 pub fn index_twice_mut<T, U>(
704 &mut self,
705 i: T,
706 j: U,
707 ) -> (
708 &mut <Self as Index<T>>::Output,
709 &mut <Self as Index<U>>::Output,
710 )
711 where
712 Self: IndexMut<T> + IndexMut<U>,
713 T: GraphIndex,
714 U: GraphIndex,
715 {
716 assert!(T::is_node_index() != U::is_node_index() || i.index() != j.index());
717
718 unsafe {
720 let self_mut = self as *mut _;
721 (
722 <Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
723 <Self as IndexMut<U>>::index_mut(&mut *self_mut, j),
724 )
725 }
726 }
727
728 pub fn retain_nodes<F>(&mut self, mut visit: F)
744 where
745 F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,
746 {
747 for i in 0..self.node_bound() {
748 let ix = node_index(i);
749 if self.contains_node(ix) && !visit(Frozen(self), ix) {
750 self.remove_node(ix);
751 }
752 }
753 self.check_free_lists();
754 }
755
756 pub fn retain_edges<F>(&mut self, mut visit: F)
769 where
770 F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,
771 {
772 for i in 0..self.edge_bound() {
773 let ix = edge_index(i);
774 if self.edge_weight(ix).is_some() && !visit(Frozen(self), ix) {
775 self.remove_edge(ix);
776 }
777 }
778 self.check_free_lists();
779 }
780
781 pub fn from_edges<I>(iterable: I) -> Self
799 where
800 I: IntoIterator,
801 I::Item: IntoWeightedEdge<E>,
802 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
803 N: Default,
804 {
805 let mut g = Self::with_capacity(0, 0);
806 g.extend_with_edges(iterable);
807 g
808 }
809
810 pub fn map<'a, F, G, N2, E2>(
816 &'a self,
817 mut node_map: F,
818 mut edge_map: G,
819 ) -> StableGraph<N2, E2, Ty, Ix>
820 where
821 F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
822 G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
823 {
824 let g = self.g.map(
825 move |i, w| w.as_ref().map(|w| node_map(i, w)),
826 move |i, w| w.as_ref().map(|w| edge_map(i, w)),
827 );
828 StableGraph {
829 g,
830 node_count: self.node_count,
831 edge_count: self.edge_count,
832 free_node: self.free_node,
833 free_edge: self.free_edge,
834 }
835 }
836
837 pub fn filter_map<'a, F, G, N2, E2>(
849 &'a self,
850 mut node_map: F,
851 mut edge_map: G,
852 ) -> StableGraph<N2, E2, Ty, Ix>
853 where
854 F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
855 G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
856 {
857 let node_bound = self.node_bound();
858 let edge_bound = self.edge_bound();
859 let mut result_g = StableGraph::with_capacity(node_bound, edge_bound);
860 let mut free_node = NodeIndex::end();
863 let mut free_edge = EdgeIndex::end();
864
865 for (i, node) in enumerate(self.raw_nodes()) {
868 if i >= node_bound {
869 break;
870 }
871 if let Some(node_weight) = node.weight.as_ref() {
872 if let Some(new_weight) = node_map(NodeIndex::new(i), node_weight) {
873 result_g.add_node(new_weight);
874 continue;
875 }
876 }
877 result_g.add_vacant_node(&mut free_node);
878 }
879 for (i, edge) in enumerate(self.raw_edges()) {
880 if i >= edge_bound {
881 break;
882 }
883 let source = edge.source();
884 let target = edge.target();
885 if let Some(edge_weight) = edge.weight.as_ref() {
886 if result_g.contains_node(source) && result_g.contains_node(target) {
887 if let Some(new_weight) = edge_map(EdgeIndex::new(i), edge_weight) {
888 result_g.add_edge(source, target, new_weight);
889 continue;
890 }
891 }
892 }
893 result_g.add_vacant_edge(&mut free_edge);
894 }
895 result_g.free_node = free_node;
896 result_g.free_edge = free_edge;
897 result_g.check_free_lists();
898 result_g
899 }
900
901 pub fn extend_with_edges<I>(&mut self, iterable: I)
909 where
910 I: IntoIterator,
911 I::Item: IntoWeightedEdge<E>,
912 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
913 N: Default,
914 {
915 let iter = iterable.into_iter();
916
917 for elt in iter {
918 let (source, target, weight) = elt.into_weighted_edge();
919 let (source, target) = (source.into(), target.into());
920 let nx = cmp::max(source, target);
921 while nx.index() >= self.node_count() {
922 self.add_node(N::default());
923 }
924 self.add_edge(source, target, weight);
925 }
926 }
927
928 fn raw_nodes(&self) -> &[Node<Option<N>, Ix>] {
932 self.g.raw_nodes()
933 }
934
935 fn raw_edges(&self) -> &[Edge<Option<E>, Ix>] {
936 self.g.raw_edges()
937 }
938
939 fn edge_bound(&self) -> usize {
940 self.edge_references()
941 .next_back()
942 .map_or(0, |edge| edge.id().index() + 1)
943 }
944
945 #[cfg(feature = "serde-1")]
946 fn link_edges(&mut self) -> Result<(), NodeIndex<Ix>> {
948 self.node_count = 0;
950 self.edge_count = 0;
951 let mut free_node = NodeIndex::end();
952 for (node_index, node) in enumerate(&mut self.g.nodes) {
953 if node.weight.is_some() {
954 self.node_count += 1;
955 } else {
956 node.next = [free_node._into_edge(), EdgeIndex::end()];
958 free_node = NodeIndex::new(node_index);
959 }
960 }
961 self.free_node = free_node;
962
963 let mut free_edge = EdgeIndex::end();
964 for (edge_index, edge) in enumerate(&mut self.g.edges) {
965 if edge.weight.is_none() {
966 edge.next = [free_edge, EdgeIndex::end()];
968 free_edge = EdgeIndex::new(edge_index);
969 continue;
970 }
971 let a = edge.source();
972 let b = edge.target();
973 let edge_idx = EdgeIndex::new(edge_index);
974 match index_twice(&mut self.g.nodes, a.index(), b.index()) {
975 Pair::None => return Err(if a > b { a } else { b }),
976 Pair::One(an) => {
977 edge.next = an.next;
978 an.next[0] = edge_idx;
979 an.next[1] = edge_idx;
980 }
981 Pair::Both(an, bn) => {
982 edge.next = [an.next[0], bn.next[1]];
984 an.next[0] = edge_idx;
985 bn.next[1] = edge_idx;
986 }
987 }
988 self.edge_count += 1;
989 }
990 self.free_edge = free_edge;
991 Ok(())
992 }
993
994 #[cfg(not(debug_assertions))]
995 fn check_free_lists(&self) {}
996 #[cfg(debug_assertions)]
997 fn check_free_lists(&self) {
999 let mut free_node = self.free_node;
1000 let mut free_node_len = 0;
1001 while free_node != NodeIndex::end() {
1002 if let Some(n) = self.g.nodes.get(free_node.index()) {
1003 if n.weight.is_none() {
1004 free_node = n.next[0]._into_node();
1005 free_node_len += 1;
1006 continue;
1007 }
1008 debug_assert!(
1009 false,
1010 "Corrupt free list: pointing to existing {:?}",
1011 free_node.index()
1012 );
1013 }
1014 debug_assert!(false, "Corrupt free list: missing {:?}", free_node.index());
1015 }
1016 debug_assert_eq!(self.node_count(), self.raw_nodes().len() - free_node_len);
1017
1018 let mut free_edge_len = 0;
1019 let mut free_edge = self.free_edge;
1020 while free_edge != EdgeIndex::end() {
1021 if let Some(n) = self.g.edges.get(free_edge.index()) {
1022 if n.weight.is_none() {
1023 free_edge = n.next[0];
1024 free_edge_len += 1;
1025 continue;
1026 }
1027 debug_assert!(
1028 false,
1029 "Corrupt free list: pointing to existing {:?}",
1030 free_node.index()
1031 );
1032 }
1033 debug_assert!(false, "Corrupt free list: missing {:?}", free_edge.index());
1034 }
1035 debug_assert_eq!(self.edge_count(), self.raw_edges().len() - free_edge_len);
1036 }
1037}
1038
1039impl<N, E, Ty, Ix: IndexType> Clone for StableGraph<N, E, Ty, Ix>
1041where
1042 N: Clone,
1043 E: Clone,
1044{
1045 fn clone(&self) -> Self {
1046 StableGraph {
1047 g: self.g.clone(),
1048 node_count: self.node_count,
1049 edge_count: self.edge_count,
1050 free_node: self.free_node,
1051 free_edge: self.free_edge,
1052 }
1053 }
1054
1055 fn clone_from(&mut self, rhs: &Self) {
1056 self.g.clone_from(&rhs.g);
1057 self.node_count = rhs.node_count;
1058 self.edge_count = rhs.edge_count;
1059 self.free_node = rhs.free_node;
1060 self.free_edge = rhs.free_edge;
1061 }
1062}
1063
1064impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1068where
1069 Ty: EdgeType,
1070 Ix: IndexType,
1071{
1072 type Output = N;
1073 fn index(&self, index: NodeIndex<Ix>) -> &N {
1074 self.node_weight(index).unwrap()
1075 }
1076}
1077
1078impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1082where
1083 Ty: EdgeType,
1084 Ix: IndexType,
1085{
1086 fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1087 self.node_weight_mut(index).unwrap()
1088 }
1089}
1090
1091impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1095where
1096 Ty: EdgeType,
1097 Ix: IndexType,
1098{
1099 type Output = E;
1100 fn index(&self, index: EdgeIndex<Ix>) -> &E {
1101 self.edge_weight(index).unwrap()
1102 }
1103}
1104
1105impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1109where
1110 Ty: EdgeType,
1111 Ix: IndexType,
1112{
1113 fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
1114 self.edge_weight_mut(index).unwrap()
1115 }
1116}
1117
1118impl<N, E, Ty, Ix> Default for StableGraph<N, E, Ty, Ix>
1120where
1121 Ty: EdgeType,
1122 Ix: IndexType,
1123{
1124 fn default() -> Self {
1125 Self::with_capacity(0, 0)
1126 }
1127}
1128
1129impl<N, E, Ty, Ix> From<Graph<N, E, Ty, Ix>> for StableGraph<N, E, Ty, Ix>
1136where
1137 Ty: EdgeType,
1138 Ix: IndexType,
1139{
1140 fn from(g: Graph<N, E, Ty, Ix>) -> Self {
1141 let nodes = g.nodes.into_iter().map(|e| Node {
1142 weight: Some(e.weight),
1143 next: e.next,
1144 });
1145 let edges = g.edges.into_iter().map(|e| Edge {
1146 weight: Some(e.weight),
1147 node: e.node,
1148 next: e.next,
1149 });
1150 StableGraph {
1151 node_count: nodes.len(),
1152 edge_count: edges.len(),
1153 g: Graph {
1154 edges: edges.collect(),
1155 nodes: nodes.collect(),
1156 ty: g.ty,
1157 },
1158 free_node: NodeIndex::end(),
1159 free_edge: EdgeIndex::end(),
1160 }
1161 }
1162}
1163
1164impl<N, E, Ty, Ix> From<StableGraph<N, E, Ty, Ix>> for Graph<N, E, Ty, Ix>
1175where
1176 Ty: EdgeType,
1177 Ix: IndexType,
1178{
1179 fn from(graph: StableGraph<N, E, Ty, Ix>) -> Self {
1180 let mut result_g = Graph::with_capacity(graph.node_count(), graph.edge_count());
1181 let mut node_index_map = vec![NodeIndex::end(); graph.node_bound()];
1183
1184 for (i, node) in enumerate(graph.g.nodes) {
1185 if let Some(nw) = node.weight {
1186 node_index_map[i] = result_g.add_node(nw);
1187 }
1188 }
1189 for edge in graph.g.edges {
1190 let source_index = edge.source().index();
1191 let target_index = edge.target().index();
1192 if let Some(ew) = edge.weight {
1193 let source = node_index_map[source_index];
1194 let target = node_index_map[target_index];
1195 debug_assert!(source != NodeIndex::end());
1196 debug_assert!(target != NodeIndex::end());
1197 result_g.add_edge(source, target, ew);
1198 }
1199 }
1200 result_g
1201 }
1202}
1203
1204impl<'a, N, E, Ty, Ix> IntoNodeReferences for &'a StableGraph<N, E, Ty, Ix>
1205where
1206 Ty: EdgeType,
1207 Ix: IndexType,
1208{
1209 type NodeRef = (NodeIndex<Ix>, &'a N);
1210 type NodeReferences = NodeReferences<'a, N, Ix>;
1211 fn node_references(self) -> Self::NodeReferences {
1212 NodeReferences {
1213 iter: enumerate(self.raw_nodes()),
1214 }
1215 }
1216}
1217
1218pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
1220 iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1221}
1222
1223impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
1224where
1225 Ix: IndexType,
1226{
1227 type Item = (NodeIndex<Ix>, &'a N);
1228
1229 fn next(&mut self) -> Option<Self::Item> {
1230 self.iter
1231 .ex_find_map(|(i, node)| node.weight.as_ref().map(move |w| (node_index(i), w)))
1232 }
1233
1234 fn size_hint(&self) -> (usize, Option<usize>) {
1235 let (_, hi) = self.iter.size_hint();
1236 (0, hi)
1237 }
1238}
1239
1240impl<'a, N, Ix> DoubleEndedIterator for NodeReferences<'a, N, Ix>
1241where
1242 Ix: IndexType,
1243{
1244 fn next_back(&mut self) -> Option<Self::Item> {
1245 self.iter
1246 .ex_rfind_map(|(i, node)| node.weight.as_ref().map(move |w| (node_index(i), w)))
1247 }
1248}
1249
1250#[derive(Debug)]
1252pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
1253 index: EdgeIndex<Ix>,
1254 node: [NodeIndex<Ix>; 2],
1255 weight: &'a E,
1256}
1257
1258impl<'a, E, Ix: IndexType> Clone for EdgeReference<'a, E, Ix> {
1259 fn clone(&self) -> Self {
1260 *self
1261 }
1262}
1263
1264impl<'a, E, Ix: IndexType> Copy for EdgeReference<'a, E, Ix> {}
1265
1266impl<'a, E, Ix: IndexType> PartialEq for EdgeReference<'a, E, Ix>
1267where
1268 E: PartialEq,
1269{
1270 fn eq(&self, rhs: &Self) -> bool {
1271 self.index == rhs.index && self.weight == rhs.weight
1272 }
1273}
1274
1275impl<'a, Ix, E> EdgeReference<'a, E, Ix>
1276where
1277 Ix: IndexType,
1278{
1279 pub fn weight(&self) -> &'a E {
1284 self.weight
1285 }
1286}
1287
1288impl<'a, Ix, E> EdgeRef for EdgeReference<'a, E, Ix>
1289where
1290 Ix: IndexType,
1291{
1292 type NodeId = NodeIndex<Ix>;
1293 type EdgeId = EdgeIndex<Ix>;
1294 type Weight = E;
1295
1296 fn source(&self) -> Self::NodeId {
1297 self.node[0]
1298 }
1299 fn target(&self) -> Self::NodeId {
1300 self.node[1]
1301 }
1302 fn weight(&self) -> &E {
1303 self.weight
1304 }
1305 fn id(&self) -> Self::EdgeId {
1306 self.index
1307 }
1308}
1309
1310impl<'a, N, E, Ty, Ix> IntoEdges for &'a StableGraph<N, E, Ty, Ix>
1311where
1312 Ty: EdgeType,
1313 Ix: IndexType,
1314{
1315 type Edges = Edges<'a, E, Ty, Ix>;
1316 fn edges(self, a: Self::NodeId) -> Self::Edges {
1317 self.edges(a)
1318 }
1319}
1320
1321impl<'a, N, E, Ty, Ix> IntoEdgesDirected for &'a StableGraph<N, E, Ty, Ix>
1322where
1323 Ty: EdgeType,
1324 Ix: IndexType,
1325{
1326 type EdgesDirected = Edges<'a, E, Ty, Ix>;
1327 fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
1328 self.edges_directed(a, dir)
1329 }
1330}
1331
1332pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1334where
1335 Ty: EdgeType,
1336 Ix: IndexType,
1337{
1338 skip_start: NodeIndex<Ix>,
1340 edges: &'a [Edge<Option<E>, Ix>],
1341
1342 next: [EdgeIndex<Ix>; 2],
1344
1345 direction: Direction,
1348 ty: PhantomData<Ty>,
1349}
1350
1351impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1352where
1353 Ty: EdgeType,
1354 Ix: IndexType,
1355{
1356 type Item = EdgeReference<'a, E, Ix>;
1357
1358 fn next(&mut self) -> Option<Self::Item> {
1359 let (iterate_over, reverse) = if Ty::is_directed() {
1369 (Some(self.direction), None)
1370 } else {
1371 (None, Some(self.direction.opposite()))
1372 };
1373
1374 if iterate_over.unwrap_or(Outgoing) == Outgoing {
1375 let i = self.next[0].index();
1376 if let Some(Edge {
1377 node,
1378 weight: Some(weight),
1379 next,
1380 }) = self.edges.get(i)
1381 {
1382 self.next[0] = next[0];
1383 return Some(EdgeReference {
1384 index: edge_index(i),
1385 node: if reverse == Some(Outgoing) {
1386 swap_pair(*node)
1387 } else {
1388 *node
1389 },
1390 weight,
1391 });
1392 }
1393 }
1394
1395 if iterate_over.unwrap_or(Incoming) == Incoming {
1396 while let Some(Edge { node, weight, next }) = self.edges.get(self.next[1].index()) {
1397 debug_assert!(weight.is_some());
1398 let edge_index = self.next[1];
1399 self.next[1] = next[1];
1400 if iterate_over.is_none() && node[0] == self.skip_start {
1403 continue;
1404 }
1405
1406 return Some(EdgeReference {
1407 index: edge_index,
1408 node: if reverse == Some(Incoming) {
1409 swap_pair(*node)
1410 } else {
1411 *node
1412 },
1413 weight: weight.as_ref().unwrap(),
1414 });
1415 }
1416 }
1417
1418 None
1419 }
1420}
1421
1422fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1423 x.swap(0, 1);
1424 x
1425}
1426
1427impl<'a, N: 'a, E: 'a, Ty, Ix> IntoEdgeReferences for &'a StableGraph<N, E, Ty, Ix>
1428where
1429 Ty: EdgeType,
1430 Ix: IndexType,
1431{
1432 type EdgeRef = EdgeReference<'a, E, Ix>;
1433 type EdgeReferences = EdgeReferences<'a, E, Ix>;
1434
1435 fn edge_references(self) -> Self::EdgeReferences {
1439 EdgeReferences {
1440 iter: self.g.edges.iter().enumerate(),
1441 }
1442 }
1443}
1444
1445pub struct EdgeReferences<'a, E: 'a, Ix: 'a = DefaultIx> {
1447 iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1448}
1449
1450impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
1451where
1452 Ix: IndexType,
1453{
1454 type Item = EdgeReference<'a, E, Ix>;
1455
1456 fn next(&mut self) -> Option<Self::Item> {
1457 self.iter.ex_find_map(|(i, edge)| {
1458 edge.weight.as_ref().map(move |weight| EdgeReference {
1459 index: edge_index(i),
1460 node: edge.node,
1461 weight,
1462 })
1463 })
1464 }
1465}
1466
1467impl<'a, E, Ix> DoubleEndedIterator for EdgeReferences<'a, E, Ix>
1468where
1469 Ix: IndexType,
1470{
1471 fn next_back(&mut self) -> Option<Self::Item> {
1472 self.iter.ex_rfind_map(|(i, edge)| {
1473 edge.weight.as_ref().map(move |weight| EdgeReference {
1474 index: edge_index(i),
1475 node: edge.node,
1476 weight,
1477 })
1478 })
1479 }
1480}
1481
1482pub struct Externals<'a, N: 'a, Ty, Ix: IndexType = DefaultIx> {
1484 iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1485 dir: Direction,
1486 ty: PhantomData<Ty>,
1487}
1488
1489impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix>
1490where
1491 Ty: EdgeType,
1492 Ix: IndexType,
1493{
1494 type Item = NodeIndex<Ix>;
1495 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1496 let k = self.dir.index();
1497 loop {
1498 match self.iter.next() {
1499 None => return None,
1500 Some((index, node)) => {
1501 if node.weight.is_some()
1502 && node.next[k] == EdgeIndex::end()
1503 && (Ty::is_directed() || node.next[1 - k] == EdgeIndex::end())
1504 {
1505 return Some(NodeIndex::new(index));
1506 } else {
1507 continue;
1508 }
1509 }
1510 }
1511 }
1512 }
1513}
1514
1515pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx> {
1519 skip_start: NodeIndex<Ix>,
1521 edges: &'a [Edge<Option<E>, Ix>],
1522 next: [EdgeIndex<Ix>; 2],
1523}
1524
1525impl<'a, E, Ix> Neighbors<'a, E, Ix>
1526where
1527 Ix: IndexType,
1528{
1529 pub fn detach(&self) -> WalkNeighbors<Ix> {
1535 WalkNeighbors {
1536 inner: super::WalkNeighbors {
1537 skip_start: self.skip_start,
1538 next: self.next,
1539 },
1540 }
1541 }
1542}
1543
1544impl<'a, E, Ix> Iterator for Neighbors<'a, E, Ix>
1545where
1546 Ix: IndexType,
1547{
1548 type Item = NodeIndex<Ix>;
1549
1550 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1551 match self.edges.get(self.next[0].index()) {
1553 None => {}
1554 Some(edge) => {
1555 debug_assert!(edge.weight.is_some());
1556 self.next[0] = edge.next[0];
1557 return Some(edge.node[1]);
1558 }
1559 }
1560 while let Some(edge) = self.edges.get(self.next[1].index()) {
1565 debug_assert!(edge.weight.is_some());
1566 self.next[1] = edge.next[1];
1567 if edge.node[0] != self.skip_start {
1568 return Some(edge.node[0]);
1569 }
1570 }
1571 None
1572 }
1573}
1574
1575pub struct WalkNeighbors<Ix> {
1612 inner: super::WalkNeighbors<Ix>,
1613}
1614
1615impl<Ix: IndexType> Clone for WalkNeighbors<Ix> {
1616 clone_fields!(WalkNeighbors, inner);
1617}
1618
1619impl<Ix: IndexType> WalkNeighbors<Ix> {
1620 pub fn next<N, E, Ty: EdgeType>(
1627 &mut self,
1628 g: &StableGraph<N, E, Ty, Ix>,
1629 ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
1630 self.inner.next(&g.g)
1631 }
1632
1633 pub fn next_node<N, E, Ty: EdgeType>(
1634 &mut self,
1635 g: &StableGraph<N, E, Ty, Ix>,
1636 ) -> Option<NodeIndex<Ix>> {
1637 self.next(g).map(|t| t.1)
1638 }
1639
1640 pub fn next_edge<N, E, Ty: EdgeType>(
1641 &mut self,
1642 g: &StableGraph<N, E, Ty, Ix>,
1643 ) -> Option<EdgeIndex<Ix>> {
1644 self.next(g).map(|t| t.0)
1645 }
1646}
1647
1648pub struct NodeIndices<'a, N: 'a, Ix: 'a = DefaultIx> {
1650 iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1651}
1652
1653impl<'a, N, Ix: IndexType> Iterator for NodeIndices<'a, N, Ix> {
1654 type Item = NodeIndex<Ix>;
1655
1656 fn next(&mut self) -> Option<Self::Item> {
1657 self.iter.ex_find_map(|(i, node)| {
1658 if node.weight.is_some() {
1659 Some(node_index(i))
1660 } else {
1661 None
1662 }
1663 })
1664 }
1665
1666 fn size_hint(&self) -> (usize, Option<usize>) {
1667 let (_, hi) = self.iter.size_hint();
1668 (0, hi)
1669 }
1670}
1671
1672impl<'a, N, Ix: IndexType> DoubleEndedIterator for NodeIndices<'a, N, Ix> {
1673 fn next_back(&mut self) -> Option<Self::Item> {
1674 self.iter.ex_rfind_map(|(i, node)| {
1675 if node.weight.is_some() {
1676 Some(node_index(i))
1677 } else {
1678 None
1679 }
1680 })
1681 }
1682}
1683
1684impl<N, E, Ty, Ix> NodeIndexable for StableGraph<N, E, Ty, Ix>
1685where
1686 Ty: EdgeType,
1687 Ix: IndexType,
1688{
1689 fn node_bound(&self) -> usize {
1691 self.node_indices().next_back().map_or(0, |i| i.index() + 1)
1692 }
1693 fn to_index(&self, ix: NodeIndex<Ix>) -> usize {
1694 ix.index()
1695 }
1696 fn from_index(&self, ix: usize) -> Self::NodeId {
1697 NodeIndex::new(ix)
1698 }
1699}
1700
1701pub struct EdgeIndices<'a, E: 'a, Ix: 'a = DefaultIx> {
1703 iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1704}
1705
1706impl<'a, E, Ix: IndexType> Iterator for EdgeIndices<'a, E, Ix> {
1707 type Item = EdgeIndex<Ix>;
1708
1709 fn next(&mut self) -> Option<Self::Item> {
1710 self.iter.ex_find_map(|(i, node)| {
1711 if node.weight.is_some() {
1712 Some(edge_index(i))
1713 } else {
1714 None
1715 }
1716 })
1717 }
1718
1719 fn size_hint(&self) -> (usize, Option<usize>) {
1720 let (_, hi) = self.iter.size_hint();
1721 (0, hi)
1722 }
1723}
1724
1725impl<'a, E, Ix: IndexType> DoubleEndedIterator for EdgeIndices<'a, E, Ix> {
1726 fn next_back(&mut self) -> Option<Self::Item> {
1727 self.iter.ex_rfind_map(|(i, node)| {
1728 if node.weight.is_some() {
1729 Some(edge_index(i))
1730 } else {
1731 None
1732 }
1733 })
1734 }
1735}
1736
1737#[test]
1738fn stable_graph() {
1739 let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
1740 let a = gr.add_node(0);
1741 let b = gr.add_node(1);
1742 let c = gr.add_node(2);
1743 let _ed = gr.add_edge(a, b, 1);
1744 println!("{:?}", gr);
1745 gr.remove_node(b);
1746 println!("{:?}", gr);
1747 let d = gr.add_node(3);
1748 println!("{:?}", gr);
1749 gr.check_free_lists();
1750 gr.remove_node(a);
1751 gr.check_free_lists();
1752 gr.remove_node(c);
1753 gr.check_free_lists();
1754 println!("{:?}", gr);
1755 gr.add_edge(d, d, 2);
1756 println!("{:?}", gr);
1757
1758 let e = gr.add_node(4);
1759 gr.add_edge(d, e, 3);
1760 println!("{:?}", gr);
1761 for neigh in gr.neighbors(d) {
1762 println!("edge {:?} -> {:?}", d, neigh);
1763 }
1764 gr.check_free_lists();
1765}
1766
1767#[test]
1768fn dfs() {
1769 use crate::visit::Dfs;
1770
1771 let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
1772 let a = gr.add_node("a");
1773 let b = gr.add_node("b");
1774 let c = gr.add_node("c");
1775 let d = gr.add_node("d");
1776 gr.add_edge(a, b, 1);
1777 gr.add_edge(a, c, 2);
1778 gr.add_edge(b, c, 3);
1779 gr.add_edge(b, d, 4);
1780 gr.add_edge(c, d, 5);
1781 gr.add_edge(d, b, 6);
1782 gr.add_edge(c, b, 7);
1783 println!("{:?}", gr);
1784
1785 let mut dfs = Dfs::new(&gr, a);
1786 while let Some(next) = dfs.next(&gr) {
1787 println!("dfs visit => {:?}, weight={:?}", next, &gr[next]);
1788 }
1789}
1790
1791#[test]
1792fn test_retain_nodes() {
1793 let mut gr = StableGraph::<_, _>::with_capacity(6, 6);
1794 let a = gr.add_node("a");
1795 let f = gr.add_node("f");
1796 let b = gr.add_node("b");
1797 let c = gr.add_node("c");
1798 let d = gr.add_node("d");
1799 let e = gr.add_node("e");
1800 gr.add_edge(a, b, 1);
1801 gr.add_edge(a, c, 2);
1802 gr.add_edge(b, c, 3);
1803 gr.add_edge(b, d, 4);
1804 gr.add_edge(c, d, 5);
1805 gr.add_edge(d, b, 6);
1806 gr.add_edge(c, b, 7);
1807 gr.add_edge(d, e, 8);
1808 gr.remove_node(f);
1809
1810 assert_eq!(gr.node_count(), 5);
1811 assert_eq!(gr.edge_count(), 8);
1812 gr.retain_nodes(|frozen_gr, ix| frozen_gr[ix] >= "c");
1813 assert_eq!(gr.node_count(), 3);
1814 assert_eq!(gr.edge_count(), 2);
1815
1816 gr.check_free_lists();
1817}