1#[cfg(feature = "std")]
6use std::{
7 cmp, fmt, iter,
8 marker::PhantomData,
9 mem::{replace, size_of},
10 ops::{Index, IndexMut},
11 slice,
12};
13
14#[cfg(not(feature = "std"))]
15use core::{
16 cmp, fmt, iter,
17 marker::PhantomData,
18 mem::{replace, size_of},
19 ops::{Index, IndexMut},
20 slice,
21};
22
23use crate::{Directed, Direction, EdgeType, Graph, Incoming, Outgoing, Undirected};
24
25use crate::iter_format::{DebugMap, IterFormatExt, NoPretty};
26use crate::iter_utils::IterUtilsExt;
27
28use super::{index_twice, Edge, Frozen, Node, Pair, DIRECTIONS};
29use crate::visit::{
30 EdgeRef, IntoEdgeReferences, IntoEdges, IntoEdgesDirected, IntoNodeReferences, NodeIndexable,
31};
32use crate::IntoWeightedEdge;
33
34#[doc(no_inline)]
36pub use crate::graph::{
37 edge_index, node_index, DefaultIx, EdgeIndex, GraphIndex, IndexType, NodeIndex,
38};
39
40use crate::util::enumerate;
41
42#[cfg(feature = "serde-1")]
43mod serialization;
44
45pub struct StableGraph<N, E, Ty = Directed, Ix = DefaultIx> {
82 g: Graph<Option<N>, Option<E>, Ty, Ix>,
83 node_count: usize,
84 edge_count: usize,
85
86 free_node: NodeIndex<Ix>,
94 free_edge: EdgeIndex<Ix>,
95}
96
97pub type StableDiGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Directed, Ix>;
102
103pub type StableUnGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Undirected, Ix>;
108
109impl<N, E, Ty, Ix> fmt::Debug for StableGraph<N, E, Ty, Ix>
110where
111 N: fmt::Debug,
112 E: fmt::Debug,
113 Ty: EdgeType,
114 Ix: IndexType,
115{
116 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
117 let etype = if self.is_directed() {
118 "Directed"
119 } else {
120 "Undirected"
121 };
122 let mut fmt_struct = f.debug_struct("StableGraph");
123 fmt_struct.field("Ty", &etype);
124 fmt_struct.field("node_count", &self.node_count);
125 fmt_struct.field("edge_count", &self.edge_count);
126 if self.g.edges.iter().any(|e| e.weight.is_some()) {
127 fmt_struct.field(
128 "edges",
129 &self
130 .g
131 .edges
132 .iter()
133 .filter(|e| e.weight.is_some())
134 .map(|e| NoPretty((e.source().index(), e.target().index())))
135 .format(", "),
136 );
137 }
138 if size_of::<N>() != 0 {
140 fmt_struct.field(
141 "node weights",
142 &DebugMap(|| {
143 self.g
144 .nodes
145 .iter()
146 .map(|n| n.weight.as_ref())
147 .enumerate()
148 .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
149 }),
150 );
151 }
152 if size_of::<E>() != 0 {
153 fmt_struct.field(
154 "edge weights",
155 &DebugMap(|| {
156 self.g
157 .edges
158 .iter()
159 .map(|n| n.weight.as_ref())
160 .enumerate()
161 .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
162 }),
163 );
164 }
165 fmt_struct.field("free_node", &self.free_node);
166 fmt_struct.field("free_edge", &self.free_edge);
167 fmt_struct.finish()
168 }
169}
170
171impl<N, E> StableGraph<N, E, Directed> {
172 pub fn new() -> Self {
178 Self::with_capacity(0, 0)
179 }
180}
181
182impl<N, E, Ty, Ix> StableGraph<N, E, Ty, Ix>
183where
184 Ty: EdgeType,
185 Ix: IndexType,
186{
187 pub fn with_capacity(nodes: usize, edges: usize) -> Self {
189 StableGraph {
190 g: Graph::with_capacity(nodes, edges),
191 node_count: 0,
192 edge_count: 0,
193 free_node: NodeIndex::end(),
194 free_edge: EdgeIndex::end(),
195 }
196 }
197
198 pub fn capacity(&self) -> (usize, usize) {
200 self.g.capacity()
201 }
202
203 pub fn clear(&mut self) {
205 self.node_count = 0;
206 self.edge_count = 0;
207 self.free_node = NodeIndex::end();
208 self.free_edge = EdgeIndex::end();
209 self.g.clear();
210 }
211
212 pub fn clear_edges(&mut self) {
214 self.edge_count = 0;
215 self.free_edge = EdgeIndex::end();
216 self.g.edges.clear();
217 for node in &mut self.g.nodes {
219 if node.weight.is_some() {
220 node.next = [EdgeIndex::end(), EdgeIndex::end()];
221 }
222 }
223 }
224
225 pub fn node_count(&self) -> usize {
229 self.node_count
230 }
231
232 pub fn edge_count(&self) -> usize {
236 self.edge_count
237 }
238
239 #[inline]
241 pub fn is_directed(&self) -> bool {
242 Ty::is_directed()
243 }
244
245 pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
254 let index = if self.free_node != NodeIndex::end() {
255 let node_idx = self.free_node;
256 let node_slot = &mut self.g.nodes[node_idx.index()];
257 let _old = replace(&mut node_slot.weight, Some(weight));
258 debug_assert!(_old.is_none());
259 self.free_node = node_slot.next[0]._into_node();
260 node_slot.next[0] = EdgeIndex::end();
261 node_idx
262 } else {
263 self.g.add_node(Some(weight))
264 };
265 self.node_count += 1;
266 index
267 }
268
269 fn add_vacant_node(&mut self, free_node: &mut NodeIndex<Ix>) {
271 let node_idx = self.g.add_node(None);
272 let node_slot = &mut self.g.nodes[node_idx.index()];
274 node_slot.next[0] = free_node._into_edge();
275 *free_node = node_idx;
276 }
277
278 pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N> {
289 let node_weight = self.g.nodes.get_mut(a.index())?.weight.take()?;
290 for d in &DIRECTIONS {
291 let k = d.index();
292
293 loop {
295 let next = self.g.nodes[a.index()].next[k];
296 if next == EdgeIndex::end() {
297 break;
298 }
299 let ret = self.remove_edge(next);
300 debug_assert!(ret.is_some());
301 let _ = ret;
302 }
303 }
304
305 let node_slot = &mut self.g.nodes[a.index()];
306 node_slot.next = [self.free_node._into_edge(), EdgeIndex::end()];
309 self.free_node = a;
310 self.node_count -= 1;
311
312 Some(node_weight)
313 }
314
315 pub fn contains_node(&self, a: NodeIndex<Ix>) -> bool {
316 self.get_node(a).is_some()
317 }
318
319 fn get_node(&self, a: NodeIndex<Ix>) -> Option<&Node<Option<N>, Ix>> {
321 self.g
322 .nodes
323 .get(a.index())
324 .and_then(|node| node.weight.as_ref().map(move |_| node))
325 }
326
327 pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
340 let edge_idx;
341 let mut new_edge = None::<Edge<_, _>>;
342 {
343 let edge: &mut Edge<_, _>;
344
345 if self.free_edge != EdgeIndex::end() {
346 edge_idx = self.free_edge;
347 edge = &mut self.g.edges[edge_idx.index()];
348 let _old = replace(&mut edge.weight, Some(weight));
349 debug_assert!(_old.is_none());
350 self.free_edge = edge.next[0];
351 edge.node = [a, b];
352 } else {
353 edge_idx = EdgeIndex::new(self.g.edges.len());
354 assert!(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx);
355 new_edge = Some(Edge {
356 weight: Some(weight),
357 node: [a, b],
358 next: [EdgeIndex::end(); 2],
359 });
360 edge = new_edge.as_mut().unwrap();
361 }
362
363 let wrong_index = match index_twice(&mut self.g.nodes, a.index(), b.index()) {
364 Pair::None => Some(cmp::max(a.index(), b.index())),
365 Pair::One(an) => {
366 if an.weight.is_none() {
367 Some(a.index())
368 } else {
369 edge.next = an.next;
370 an.next[0] = edge_idx;
371 an.next[1] = edge_idx;
372 None
373 }
374 }
375 Pair::Both(an, bn) => {
376 if an.weight.is_none() {
378 Some(a.index())
379 } else if bn.weight.is_none() {
380 Some(b.index())
381 } else {
382 edge.next = [an.next[0], bn.next[1]];
383 an.next[0] = edge_idx;
384 bn.next[1] = edge_idx;
385 None
386 }
387 }
388 };
389 if let Some(i) = wrong_index {
390 panic!(
391 "StableGraph::add_edge: node index {} is not a node in the graph",
392 i
393 );
394 }
395 self.edge_count += 1;
396 }
397 if let Some(edge) = new_edge {
398 self.g.edges.push(edge);
399 }
400 edge_idx
401 }
402
403 fn add_vacant_edge(&mut self, free_edge: &mut EdgeIndex<Ix>) {
405 let edge_idx = EdgeIndex::new(self.g.edges.len());
406 debug_assert!(edge_idx != EdgeIndex::end());
407 let mut edge = Edge {
408 weight: None,
409 node: [NodeIndex::end(); 2],
410 next: [EdgeIndex::end(); 2],
411 };
412 edge.next[0] = *free_edge;
413 *free_edge = edge_idx;
414 self.g.edges.push(edge);
415 }
416
417 pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
427 if let Some(ix) = self.find_edge(a, b) {
428 self[ix] = weight;
429 return ix;
430 }
431 self.add_edge(a, b, weight)
432 }
433
434 pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
441 let (is_edge, edge_node, edge_next) = match self.g.edges.get(e.index()) {
445 None => return None,
446 Some(x) => (x.weight.is_some(), x.node, x.next),
447 };
448 if !is_edge {
449 return None;
450 }
451
452 self.g.change_edge_links(edge_node, e, edge_next);
455
456 let edge = &mut self.g.edges[e.index()];
458 edge.next = [self.free_edge, EdgeIndex::end()];
459 edge.node = [NodeIndex::end(), NodeIndex::end()];
460 self.free_edge = e;
461 self.edge_count -= 1;
462 edge.weight.take()
463 }
464
465 pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
469 match self.g.nodes.get(a.index()) {
470 Some(no) => no.weight.as_ref(),
471 None => None,
472 }
473 }
474
475 pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
479 match self.g.nodes.get_mut(a.index()) {
480 Some(no) => no.weight.as_mut(),
481 None => None,
482 }
483 }
484
485 pub fn node_weights_mut(&mut self) -> impl Iterator<Item = &mut N> {
490 self.g
491 .node_weights_mut()
492 .flat_map(|maybe_node| maybe_node.iter_mut())
493 }
494
495 pub fn node_indices(&self) -> NodeIndices<N, Ix> {
497 NodeIndices {
498 iter: enumerate(self.raw_nodes()),
499 }
500 }
501
502 pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
506 match self.g.edges.get(e.index()) {
507 Some(ed) => ed.weight.as_ref(),
508 None => None,
509 }
510 }
511
512 pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
516 match self.g.edges.get_mut(e.index()) {
517 Some(ed) => ed.weight.as_mut(),
518 None => None,
519 }
520 }
521
522 pub fn edge_weights_mut(&mut self) -> impl Iterator<Item = &mut E> {
527 self.g
528 .edge_weights_mut()
529 .flat_map(|maybe_edge| maybe_edge.iter_mut())
530 }
531
532 pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)> {
534 match self.g.edges.get(e.index()) {
535 Some(ed) if ed.weight.is_some() => Some((ed.source(), ed.target())),
536 _otherwise => None,
537 }
538 }
539
540 pub fn edge_indices(&self) -> EdgeIndices<E, Ix> {
542 EdgeIndices {
543 iter: enumerate(self.raw_edges()),
544 }
545 }
546
547 pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
552 self.find_edge(a, b).is_some()
553 }
554
555 pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>> {
560 if !self.is_directed() {
561 self.find_edge_undirected(a, b).map(|(ix, _)| ix)
562 } else {
563 match self.get_node(a) {
564 None => None,
565 Some(node) => self.g.find_edge_directed_from_node(node, b),
566 }
567 }
568 }
569
570 pub fn find_edge_undirected(
578 &self,
579 a: NodeIndex<Ix>,
580 b: NodeIndex<Ix>,
581 ) -> Option<(EdgeIndex<Ix>, Direction)> {
582 match self.get_node(a) {
583 None => None,
584 Some(node) => self.g.find_edge_undirected_from_node(node, b),
585 }
586 }
587
588 pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
601 self.neighbors_directed(a, Outgoing)
602 }
603
604 pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix> {
620 let mut iter = self.neighbors_undirected(a);
621 if self.is_directed() {
622 let k = dir.index();
623 iter.next[1 - k] = EdgeIndex::end();
624 iter.skip_start = NodeIndex::end();
625 }
626 iter
627 }
628
629 pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
643 Neighbors {
644 skip_start: a,
645 edges: &self.g.edges,
646 next: match self.get_node(a) {
647 None => [EdgeIndex::end(), EdgeIndex::end()],
648 Some(n) => n.next,
649 },
650 }
651 }
652
653 pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
661 self.edges_directed(a, Outgoing)
662 }
663
664 pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix> {
676 Edges {
677 skip_start: a,
678 edges: &self.g.edges,
679 direction: dir,
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 externals(&self, dir: Direction) -> Externals<N, Ty, Ix> {
700 Externals {
701 iter: self.raw_nodes().iter().enumerate(),
702 dir,
703 ty: PhantomData,
704 }
705 }
706
707 pub fn index_twice_mut<T, U>(
712 &mut self,
713 i: T,
714 j: U,
715 ) -> (
716 &mut <Self as Index<T>>::Output,
717 &mut <Self as Index<U>>::Output,
718 )
719 where
720 Self: IndexMut<T> + IndexMut<U>,
721 T: GraphIndex,
722 U: GraphIndex,
723 {
724 assert!(T::is_node_index() != U::is_node_index() || i.index() != j.index());
725
726 unsafe {
728 let self_mut = self as *mut _;
729 (
730 <Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
731 <Self as IndexMut<U>>::index_mut(&mut *self_mut, j),
732 )
733 }
734 }
735
736 pub fn retain_nodes<F>(&mut self, mut visit: F)
752 where
753 F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,
754 {
755 for i in 0..self.node_bound() {
756 let ix = node_index(i);
757 if self.contains_node(ix) && !visit(Frozen(self), ix) {
758 self.remove_node(ix);
759 }
760 }
761 self.check_free_lists();
762 }
763
764 pub fn retain_edges<F>(&mut self, mut visit: F)
777 where
778 F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,
779 {
780 for i in 0..self.edge_bound() {
781 let ix = edge_index(i);
782 if self.edge_weight(ix).is_some() && !visit(Frozen(self), ix) {
783 self.remove_edge(ix);
784 }
785 }
786 self.check_free_lists();
787 }
788
789 pub fn from_edges<I>(iterable: I) -> Self
807 where
808 I: IntoIterator,
809 I::Item: IntoWeightedEdge<E>,
810 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
811 N: Default,
812 {
813 let mut g = Self::with_capacity(0, 0);
814 g.extend_with_edges(iterable);
815 g
816 }
817
818 pub fn map<'a, F, G, N2, E2>(
824 &'a self,
825 mut node_map: F,
826 mut edge_map: G,
827 ) -> StableGraph<N2, E2, Ty, Ix>
828 where
829 F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
830 G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
831 {
832 let g = self.g.map(
833 move |i, w| w.as_ref().map(|w| node_map(i, w)),
834 move |i, w| w.as_ref().map(|w| edge_map(i, w)),
835 );
836 StableGraph {
837 g,
838 node_count: self.node_count,
839 edge_count: self.edge_count,
840 free_node: self.free_node,
841 free_edge: self.free_edge,
842 }
843 }
844
845 pub fn filter_map<'a, F, G, N2, E2>(
857 &'a self,
858 mut node_map: F,
859 mut edge_map: G,
860 ) -> StableGraph<N2, E2, Ty, Ix>
861 where
862 F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
863 G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
864 {
865 let node_bound = self.node_bound();
866 let edge_bound = self.edge_bound();
867 let mut result_g = StableGraph::with_capacity(node_bound, edge_bound);
868 let mut free_node = NodeIndex::end();
871 let mut free_edge = EdgeIndex::end();
872
873 for (i, node) in enumerate(self.raw_nodes()) {
876 if i >= node_bound {
877 break;
878 }
879 if let Some(node_weight) = node.weight.as_ref() {
880 if let Some(new_weight) = node_map(NodeIndex::new(i), node_weight) {
881 result_g.add_node(new_weight);
882 continue;
883 }
884 }
885 result_g.add_vacant_node(&mut free_node);
886 }
887 for (i, edge) in enumerate(self.raw_edges()) {
888 if i >= edge_bound {
889 break;
890 }
891 let source = edge.source();
892 let target = edge.target();
893 if let Some(edge_weight) = edge.weight.as_ref() {
894 if result_g.contains_node(source) && result_g.contains_node(target) {
895 if let Some(new_weight) = edge_map(EdgeIndex::new(i), edge_weight) {
896 result_g.add_edge(source, target, new_weight);
897 continue;
898 }
899 }
900 }
901 result_g.add_vacant_edge(&mut free_edge);
902 }
903 result_g.free_node = free_node;
904 result_g.free_edge = free_edge;
905 result_g.check_free_lists();
906 result_g
907 }
908
909 pub fn extend_with_edges<I>(&mut self, iterable: I)
917 where
918 I: IntoIterator,
919 I::Item: IntoWeightedEdge<E>,
920 <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
921 N: Default,
922 {
923 let iter = iterable.into_iter();
924
925 for elt in iter {
926 let (source, target, weight) = elt.into_weighted_edge();
927 let (source, target) = (source.into(), target.into());
928 let nx = cmp::max(source, target);
929 while nx.index() >= self.node_count() {
930 self.add_node(N::default());
931 }
932 self.add_edge(source, target, weight);
933 }
934 }
935
936 fn raw_nodes(&self) -> &[Node<Option<N>, Ix>] {
940 self.g.raw_nodes()
941 }
942
943 fn raw_edges(&self) -> &[Edge<Option<E>, Ix>] {
944 self.g.raw_edges()
945 }
946
947 fn edge_bound(&self) -> usize {
948 self.edge_references()
949 .next_back()
950 .map_or(0, |edge| edge.id().index() + 1)
951 }
952
953 #[cfg(feature = "serde-1")]
954 fn link_edges(&mut self) -> Result<(), NodeIndex<Ix>> {
956 self.node_count = 0;
958 self.edge_count = 0;
959 let mut free_node = NodeIndex::end();
960 for (node_index, node) in enumerate(&mut self.g.nodes) {
961 if node.weight.is_some() {
962 self.node_count += 1;
963 } else {
964 node.next = [free_node._into_edge(), EdgeIndex::end()];
966 free_node = NodeIndex::new(node_index);
967 }
968 }
969 self.free_node = free_node;
970
971 let mut free_edge = EdgeIndex::end();
972 for (edge_index, edge) in enumerate(&mut self.g.edges) {
973 if edge.weight.is_none() {
974 edge.next = [free_edge, EdgeIndex::end()];
976 free_edge = EdgeIndex::new(edge_index);
977 continue;
978 }
979 let a = edge.source();
980 let b = edge.target();
981 let edge_idx = EdgeIndex::new(edge_index);
982 match index_twice(&mut self.g.nodes, a.index(), b.index()) {
983 Pair::None => return Err(if a > b { a } else { b }),
984 Pair::One(an) => {
985 edge.next = an.next;
986 an.next[0] = edge_idx;
987 an.next[1] = edge_idx;
988 }
989 Pair::Both(an, bn) => {
990 edge.next = [an.next[0], bn.next[1]];
992 an.next[0] = edge_idx;
993 bn.next[1] = edge_idx;
994 }
995 }
996 self.edge_count += 1;
997 }
998 self.free_edge = free_edge;
999 Ok(())
1000 }
1001
1002 #[cfg(not(debug_assertions))]
1003 fn check_free_lists(&self) {}
1004 #[cfg(debug_assertions)]
1005 fn check_free_lists(&self) {
1007 let mut free_node = self.free_node;
1008 let mut free_node_len = 0;
1009 while free_node != NodeIndex::end() {
1010 if let Some(n) = self.g.nodes.get(free_node.index()) {
1011 if n.weight.is_none() {
1012 free_node = n.next[0]._into_node();
1013 free_node_len += 1;
1014 continue;
1015 }
1016 debug_assert!(
1017 false,
1018 "Corrupt free list: pointing to existing {:?}",
1019 free_node.index()
1020 );
1021 }
1022 debug_assert!(false, "Corrupt free list: missing {:?}", free_node.index());
1023 }
1024 debug_assert_eq!(self.node_count(), self.raw_nodes().len() - free_node_len);
1025
1026 let mut free_edge_len = 0;
1027 let mut free_edge = self.free_edge;
1028 while free_edge != EdgeIndex::end() {
1029 if let Some(n) = self.g.edges.get(free_edge.index()) {
1030 if n.weight.is_none() {
1031 free_edge = n.next[0];
1032 free_edge_len += 1;
1033 continue;
1034 }
1035 debug_assert!(
1036 false,
1037 "Corrupt free list: pointing to existing {:?}",
1038 free_node.index()
1039 );
1040 }
1041 debug_assert!(false, "Corrupt free list: missing {:?}", free_edge.index());
1042 }
1043 debug_assert_eq!(self.edge_count(), self.raw_edges().len() - free_edge_len);
1044 }
1045}
1046
1047impl<N, E, Ty, Ix: IndexType> Clone for StableGraph<N, E, Ty, Ix>
1049where
1050 N: Clone,
1051 E: Clone,
1052{
1053 fn clone(&self) -> Self {
1054 StableGraph {
1055 g: self.g.clone(),
1056 node_count: self.node_count,
1057 edge_count: self.edge_count,
1058 free_node: self.free_node,
1059 free_edge: self.free_edge,
1060 }
1061 }
1062
1063 fn clone_from(&mut self, rhs: &Self) {
1064 self.g.clone_from(&rhs.g);
1065 self.node_count = rhs.node_count;
1066 self.edge_count = rhs.edge_count;
1067 self.free_node = rhs.free_node;
1068 self.free_edge = rhs.free_edge;
1069 }
1070}
1071
1072impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1076where
1077 Ty: EdgeType,
1078 Ix: IndexType,
1079{
1080 type Output = N;
1081 fn index(&self, index: NodeIndex<Ix>) -> &N {
1082 self.node_weight(index).unwrap()
1083 }
1084}
1085
1086impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1090where
1091 Ty: EdgeType,
1092 Ix: IndexType,
1093{
1094 fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1095 self.node_weight_mut(index).unwrap()
1096 }
1097}
1098
1099impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1103where
1104 Ty: EdgeType,
1105 Ix: IndexType,
1106{
1107 type Output = E;
1108 fn index(&self, index: EdgeIndex<Ix>) -> &E {
1109 self.edge_weight(index).unwrap()
1110 }
1111}
1112
1113impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
1117where
1118 Ty: EdgeType,
1119 Ix: IndexType,
1120{
1121 fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
1122 self.edge_weight_mut(index).unwrap()
1123 }
1124}
1125
1126impl<N, E, Ty, Ix> Default for StableGraph<N, E, Ty, Ix>
1128where
1129 Ty: EdgeType,
1130 Ix: IndexType,
1131{
1132 fn default() -> Self {
1133 Self::with_capacity(0, 0)
1134 }
1135}
1136
1137impl<N, E, Ty, Ix> From<Graph<N, E, Ty, Ix>> for StableGraph<N, E, Ty, Ix>
1144where
1145 Ty: EdgeType,
1146 Ix: IndexType,
1147{
1148 fn from(g: Graph<N, E, Ty, Ix>) -> Self {
1149 let nodes = g.nodes.into_iter().map(|e| Node {
1150 weight: Some(e.weight),
1151 next: e.next,
1152 });
1153 let edges = g.edges.into_iter().map(|e| Edge {
1154 weight: Some(e.weight),
1155 node: e.node,
1156 next: e.next,
1157 });
1158 StableGraph {
1159 node_count: nodes.len(),
1160 edge_count: edges.len(),
1161 g: Graph {
1162 edges: edges.collect(),
1163 nodes: nodes.collect(),
1164 ty: g.ty,
1165 },
1166 free_node: NodeIndex::end(),
1167 free_edge: EdgeIndex::end(),
1168 }
1169 }
1170}
1171
1172impl<N, E, Ty, Ix> From<StableGraph<N, E, Ty, Ix>> for Graph<N, E, Ty, Ix>
1183where
1184 Ty: EdgeType,
1185 Ix: IndexType,
1186{
1187 fn from(graph: StableGraph<N, E, Ty, Ix>) -> Self {
1188 let mut result_g = Graph::with_capacity(graph.node_count(), graph.edge_count());
1189 let mut node_index_map = vec![NodeIndex::end(); graph.node_bound()];
1191
1192 for (i, node) in enumerate(graph.g.nodes) {
1193 if let Some(nw) = node.weight {
1194 node_index_map[i] = result_g.add_node(nw);
1195 }
1196 }
1197 for edge in graph.g.edges {
1198 let source_index = edge.source().index();
1199 let target_index = edge.target().index();
1200 if let Some(ew) = edge.weight {
1201 let source = node_index_map[source_index];
1202 let target = node_index_map[target_index];
1203 debug_assert!(source != NodeIndex::end());
1204 debug_assert!(target != NodeIndex::end());
1205 result_g.add_edge(source, target, ew);
1206 }
1207 }
1208 result_g
1209 }
1210}
1211
1212impl<'a, N, E, Ty, Ix> IntoNodeReferences for &'a StableGraph<N, E, Ty, Ix>
1213where
1214 Ty: EdgeType,
1215 Ix: IndexType,
1216{
1217 type NodeRef = (NodeIndex<Ix>, &'a N);
1218 type NodeReferences = NodeReferences<'a, N, Ix>;
1219 fn node_references(self) -> Self::NodeReferences {
1220 NodeReferences {
1221 iter: enumerate(self.raw_nodes()),
1222 }
1223 }
1224}
1225
1226pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
1228 iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1229}
1230
1231impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
1232where
1233 Ix: IndexType,
1234{
1235 type Item = (NodeIndex<Ix>, &'a N);
1236
1237 fn next(&mut self) -> Option<Self::Item> {
1238 self.iter
1239 .ex_find_map(|(i, node)| node.weight.as_ref().map(move |w| (node_index(i), w)))
1240 }
1241
1242 fn size_hint(&self) -> (usize, Option<usize>) {
1243 let (_, hi) = self.iter.size_hint();
1244 (0, hi)
1245 }
1246}
1247
1248impl<'a, N, Ix> DoubleEndedIterator for NodeReferences<'a, N, Ix>
1249where
1250 Ix: IndexType,
1251{
1252 fn next_back(&mut self) -> Option<Self::Item> {
1253 self.iter
1254 .ex_rfind_map(|(i, node)| node.weight.as_ref().map(move |w| (node_index(i), w)))
1255 }
1256}
1257
1258#[derive(Debug)]
1260pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
1261 index: EdgeIndex<Ix>,
1262 node: [NodeIndex<Ix>; 2],
1263 weight: &'a E,
1264}
1265
1266impl<'a, E, Ix: IndexType> Clone for EdgeReference<'a, E, Ix> {
1267 fn clone(&self) -> Self {
1268 *self
1269 }
1270}
1271
1272impl<'a, E, Ix: IndexType> Copy for EdgeReference<'a, E, Ix> {}
1273
1274impl<'a, E, Ix: IndexType> PartialEq for EdgeReference<'a, E, Ix>
1275where
1276 E: PartialEq,
1277{
1278 fn eq(&self, rhs: &Self) -> bool {
1279 self.index == rhs.index && self.weight == rhs.weight
1280 }
1281}
1282
1283impl<'a, Ix, E> EdgeReference<'a, E, Ix>
1284where
1285 Ix: IndexType,
1286{
1287 pub fn weight(&self) -> &'a E {
1292 self.weight
1293 }
1294}
1295
1296impl<'a, Ix, E> EdgeRef for EdgeReference<'a, E, Ix>
1297where
1298 Ix: IndexType,
1299{
1300 type NodeId = NodeIndex<Ix>;
1301 type EdgeId = EdgeIndex<Ix>;
1302 type Weight = E;
1303
1304 fn source(&self) -> Self::NodeId {
1305 self.node[0]
1306 }
1307 fn target(&self) -> Self::NodeId {
1308 self.node[1]
1309 }
1310 fn weight(&self) -> &E {
1311 self.weight
1312 }
1313 fn id(&self) -> Self::EdgeId {
1314 self.index
1315 }
1316}
1317
1318impl<'a, N, E, Ty, Ix> IntoEdges for &'a StableGraph<N, E, Ty, Ix>
1319where
1320 Ty: EdgeType,
1321 Ix: IndexType,
1322{
1323 type Edges = Edges<'a, E, Ty, Ix>;
1324 fn edges(self, a: Self::NodeId) -> Self::Edges {
1325 self.edges(a)
1326 }
1327}
1328
1329impl<'a, N, E, Ty, Ix> IntoEdgesDirected for &'a StableGraph<N, E, Ty, Ix>
1330where
1331 Ty: EdgeType,
1332 Ix: IndexType,
1333{
1334 type EdgesDirected = Edges<'a, E, Ty, Ix>;
1335 fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
1336 self.edges_directed(a, dir)
1337 }
1338}
1339
1340pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1342where
1343 Ty: EdgeType,
1344 Ix: IndexType,
1345{
1346 skip_start: NodeIndex<Ix>,
1348 edges: &'a [Edge<Option<E>, Ix>],
1349
1350 next: [EdgeIndex<Ix>; 2],
1352
1353 direction: Direction,
1356 ty: PhantomData<Ty>,
1357}
1358
1359impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1360where
1361 Ty: EdgeType,
1362 Ix: IndexType,
1363{
1364 type Item = EdgeReference<'a, E, Ix>;
1365
1366 fn next(&mut self) -> Option<Self::Item> {
1367 let (iterate_over, reverse) = if Ty::is_directed() {
1377 (Some(self.direction), None)
1378 } else {
1379 (None, Some(self.direction.opposite()))
1380 };
1381
1382 if iterate_over.unwrap_or(Outgoing) == Outgoing {
1383 let i = self.next[0].index();
1384 if let Some(Edge {
1385 node,
1386 weight: Some(weight),
1387 next,
1388 }) = self.edges.get(i)
1389 {
1390 self.next[0] = next[0];
1391 return Some(EdgeReference {
1392 index: edge_index(i),
1393 node: if reverse == Some(Outgoing) {
1394 swap_pair(*node)
1395 } else {
1396 *node
1397 },
1398 weight,
1399 });
1400 }
1401 }
1402
1403 if iterate_over.unwrap_or(Incoming) == Incoming {
1404 while let Some(Edge { node, weight, next }) = self.edges.get(self.next[1].index()) {
1405 debug_assert!(weight.is_some());
1406 let edge_index = self.next[1];
1407 self.next[1] = next[1];
1408 if iterate_over.is_none() && node[0] == self.skip_start {
1411 continue;
1412 }
1413
1414 return Some(EdgeReference {
1415 index: edge_index,
1416 node: if reverse == Some(Incoming) {
1417 swap_pair(*node)
1418 } else {
1419 *node
1420 },
1421 weight: weight.as_ref().unwrap(),
1422 });
1423 }
1424 }
1425
1426 None
1427 }
1428}
1429
1430fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1431 x.swap(0, 1);
1432 x
1433}
1434
1435impl<'a, N: 'a, E: 'a, Ty, Ix> IntoEdgeReferences for &'a StableGraph<N, E, Ty, Ix>
1436where
1437 Ty: EdgeType,
1438 Ix: IndexType,
1439{
1440 type EdgeRef = EdgeReference<'a, E, Ix>;
1441 type EdgeReferences = EdgeReferences<'a, E, Ix>;
1442
1443 fn edge_references(self) -> Self::EdgeReferences {
1447 EdgeReferences {
1448 iter: self.g.edges.iter().enumerate(),
1449 }
1450 }
1451}
1452
1453pub struct EdgeReferences<'a, E: 'a, Ix: 'a = DefaultIx> {
1455 iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1456}
1457
1458impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
1459where
1460 Ix: IndexType,
1461{
1462 type Item = EdgeReference<'a, E, Ix>;
1463
1464 fn next(&mut self) -> Option<Self::Item> {
1465 self.iter.ex_find_map(|(i, edge)| {
1466 edge.weight.as_ref().map(move |weight| EdgeReference {
1467 index: edge_index(i),
1468 node: edge.node,
1469 weight,
1470 })
1471 })
1472 }
1473}
1474
1475impl<'a, E, Ix> DoubleEndedIterator for EdgeReferences<'a, E, Ix>
1476where
1477 Ix: IndexType,
1478{
1479 fn next_back(&mut self) -> Option<Self::Item> {
1480 self.iter.ex_rfind_map(|(i, edge)| {
1481 edge.weight.as_ref().map(move |weight| EdgeReference {
1482 index: edge_index(i),
1483 node: edge.node,
1484 weight,
1485 })
1486 })
1487 }
1488}
1489
1490pub struct Externals<'a, N: 'a, Ty, Ix: IndexType = DefaultIx> {
1492 iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1493 dir: Direction,
1494 ty: PhantomData<Ty>,
1495}
1496
1497impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix>
1498where
1499 Ty: EdgeType,
1500 Ix: IndexType,
1501{
1502 type Item = NodeIndex<Ix>;
1503 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1504 let k = self.dir.index();
1505 loop {
1506 match self.iter.next() {
1507 None => return None,
1508 Some((index, node)) => {
1509 if node.weight.is_some()
1510 && node.next[k] == EdgeIndex::end()
1511 && (Ty::is_directed() || node.next[1 - k] == EdgeIndex::end())
1512 {
1513 return Some(NodeIndex::new(index));
1514 } else {
1515 continue;
1516 }
1517 }
1518 }
1519 }
1520 }
1521}
1522
1523pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx> {
1527 skip_start: NodeIndex<Ix>,
1529 edges: &'a [Edge<Option<E>, Ix>],
1530 next: [EdgeIndex<Ix>; 2],
1531}
1532
1533impl<'a, E, Ix> Neighbors<'a, E, Ix>
1534where
1535 Ix: IndexType,
1536{
1537 pub fn detach(&self) -> WalkNeighbors<Ix> {
1543 WalkNeighbors {
1544 inner: super::WalkNeighbors {
1545 skip_start: self.skip_start,
1546 next: self.next,
1547 },
1548 }
1549 }
1550}
1551
1552impl<'a, E, Ix> Iterator for Neighbors<'a, E, Ix>
1553where
1554 Ix: IndexType,
1555{
1556 type Item = NodeIndex<Ix>;
1557
1558 fn next(&mut self) -> Option<NodeIndex<Ix>> {
1559 match self.edges.get(self.next[0].index()) {
1561 None => {}
1562 Some(edge) => {
1563 debug_assert!(edge.weight.is_some());
1564 self.next[0] = edge.next[0];
1565 return Some(edge.node[1]);
1566 }
1567 }
1568 while let Some(edge) = self.edges.get(self.next[1].index()) {
1573 debug_assert!(edge.weight.is_some());
1574 self.next[1] = edge.next[1];
1575 if edge.node[0] != self.skip_start {
1576 return Some(edge.node[0]);
1577 }
1578 }
1579 None
1580 }
1581}
1582
1583pub struct WalkNeighbors<Ix> {
1620 inner: super::WalkNeighbors<Ix>,
1621}
1622
1623impl<Ix: IndexType> Clone for WalkNeighbors<Ix> {
1624 clone_fields!(WalkNeighbors, inner);
1625}
1626
1627impl<Ix: IndexType> WalkNeighbors<Ix> {
1628 pub fn next<N, E, Ty: EdgeType>(
1635 &mut self,
1636 g: &StableGraph<N, E, Ty, Ix>,
1637 ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
1638 self.inner.next(&g.g)
1639 }
1640
1641 pub fn next_node<N, E, Ty: EdgeType>(
1642 &mut self,
1643 g: &StableGraph<N, E, Ty, Ix>,
1644 ) -> Option<NodeIndex<Ix>> {
1645 self.next(g).map(|t| t.1)
1646 }
1647
1648 pub fn next_edge<N, E, Ty: EdgeType>(
1649 &mut self,
1650 g: &StableGraph<N, E, Ty, Ix>,
1651 ) -> Option<EdgeIndex<Ix>> {
1652 self.next(g).map(|t| t.0)
1653 }
1654}
1655
1656pub struct NodeIndices<'a, N: 'a, Ix: 'a = DefaultIx> {
1658 iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1659}
1660
1661impl<'a, N, Ix: IndexType> Iterator for NodeIndices<'a, N, Ix> {
1662 type Item = NodeIndex<Ix>;
1663
1664 fn next(&mut self) -> Option<Self::Item> {
1665 self.iter.ex_find_map(|(i, node)| {
1666 if node.weight.is_some() {
1667 Some(node_index(i))
1668 } else {
1669 None
1670 }
1671 })
1672 }
1673
1674 fn size_hint(&self) -> (usize, Option<usize>) {
1675 let (_, hi) = self.iter.size_hint();
1676 (0, hi)
1677 }
1678}
1679
1680impl<'a, N, Ix: IndexType> DoubleEndedIterator for NodeIndices<'a, N, Ix> {
1681 fn next_back(&mut self) -> Option<Self::Item> {
1682 self.iter.ex_rfind_map(|(i, node)| {
1683 if node.weight.is_some() {
1684 Some(node_index(i))
1685 } else {
1686 None
1687 }
1688 })
1689 }
1690}
1691
1692impl<N, E, Ty, Ix> NodeIndexable for StableGraph<N, E, Ty, Ix>
1693where
1694 Ty: EdgeType,
1695 Ix: IndexType,
1696{
1697 fn node_bound(&self) -> usize {
1699 self.node_indices().next_back().map_or(0, |i| i.index() + 1)
1700 }
1701 fn to_index(&self, ix: NodeIndex<Ix>) -> usize {
1702 ix.index()
1703 }
1704 fn from_index(&self, ix: usize) -> Self::NodeId {
1705 NodeIndex::new(ix)
1706 }
1707}
1708
1709pub struct EdgeIndices<'a, E: 'a, Ix: 'a = DefaultIx> {
1711 iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1712}
1713
1714impl<'a, E, Ix: IndexType> Iterator for EdgeIndices<'a, E, Ix> {
1715 type Item = EdgeIndex<Ix>;
1716
1717 fn next(&mut self) -> Option<Self::Item> {
1718 self.iter.ex_find_map(|(i, node)| {
1719 if node.weight.is_some() {
1720 Some(edge_index(i))
1721 } else {
1722 None
1723 }
1724 })
1725 }
1726
1727 fn size_hint(&self) -> (usize, Option<usize>) {
1728 let (_, hi) = self.iter.size_hint();
1729 (0, hi)
1730 }
1731}
1732
1733impl<'a, E, Ix: IndexType> DoubleEndedIterator for EdgeIndices<'a, E, Ix> {
1734 fn next_back(&mut self) -> Option<Self::Item> {
1735 self.iter.ex_rfind_map(|(i, node)| {
1736 if node.weight.is_some() {
1737 Some(edge_index(i))
1738 } else {
1739 None
1740 }
1741 })
1742 }
1743}
1744
1745#[allow(unused_variables)]
1746#[test]
1747fn stable_graph() {
1748 let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
1749 let a = gr.add_node(0);
1750 let b = gr.add_node(1);
1751 let c = gr.add_node(2);
1752 let _ed = gr.add_edge(a, b, 1);
1753 #[cfg(feature = "std")]
1754 println!("{:?}", gr);
1755 gr.remove_node(b);
1756 #[cfg(feature = "std")]
1757 println!("{:?}", gr);
1758 let d = gr.add_node(3);
1759 #[cfg(feature = "std")]
1760 println!("{:?}", gr);
1761 gr.check_free_lists();
1762 gr.remove_node(a);
1763 gr.check_free_lists();
1764 gr.remove_node(c);
1765 gr.check_free_lists();
1766 #[cfg(feature = "std")]
1767 println!("{:?}", gr);
1768 gr.add_edge(d, d, 2);
1769 #[cfg(feature = "std")]
1770 println!("{:?}", gr);
1771
1772 let e = gr.add_node(4);
1773 gr.add_edge(d, e, 3);
1774 #[cfg(feature = "std")]
1775 println!("{:?}", gr);
1776 for neigh in gr.neighbors(d) {
1777 #[cfg(feature = "std")]
1778 println!("edge {:?} -> {:?}", d, neigh);
1779 }
1780 gr.check_free_lists();
1781}
1782
1783#[allow(unused_variables)]
1784#[test]
1785fn dfs() {
1786 use crate::visit::Dfs;
1787
1788 let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
1789 let a = gr.add_node("a");
1790 let b = gr.add_node("b");
1791 let c = gr.add_node("c");
1792 let d = gr.add_node("d");
1793 gr.add_edge(a, b, 1);
1794 gr.add_edge(a, c, 2);
1795 gr.add_edge(b, c, 3);
1796 gr.add_edge(b, d, 4);
1797 gr.add_edge(c, d, 5);
1798 gr.add_edge(d, b, 6);
1799 gr.add_edge(c, b, 7);
1800 #[cfg(feature = "std")]
1801 println!("{:?}", gr);
1802
1803 let mut dfs = Dfs::new(&gr, a);
1804 while let Some(next) = dfs.next(&gr) {
1805 #[cfg(feature = "std")]
1806 println!("dfs visit => {:?}, weight={:?}", next, &gr[next]);
1807 }
1808}
1809
1810#[test]
1811fn test_retain_nodes() {
1812 let mut gr = StableGraph::<_, _>::with_capacity(6, 6);
1813 let a = gr.add_node("a");
1814 let f = gr.add_node("f");
1815 let b = gr.add_node("b");
1816 let c = gr.add_node("c");
1817 let d = gr.add_node("d");
1818 let e = gr.add_node("e");
1819 gr.add_edge(a, b, 1);
1820 gr.add_edge(a, c, 2);
1821 gr.add_edge(b, c, 3);
1822 gr.add_edge(b, d, 4);
1823 gr.add_edge(c, d, 5);
1824 gr.add_edge(d, b, 6);
1825 gr.add_edge(c, b, 7);
1826 gr.add_edge(d, e, 8);
1827 gr.remove_node(f);
1828
1829 assert_eq!(gr.node_count(), 5);
1830 assert_eq!(gr.edge_count(), 8);
1831 gr.retain_nodes(|frozen_gr, ix| frozen_gr[ix] >= "c");
1832 assert_eq!(gr.node_count(), 3);
1833 assert_eq!(gr.edge_count(), 2);
1834
1835 gr.check_free_lists();
1836}