Skip to main content

god_graph/graph/
iterators.rs

1//! 图迭代器模块
2//!
3//! 提供各种图遍历迭代器
4
5use crate::edge::EdgeIndex;
6pub use crate::graph::graph_impl::IncidentEdgesIter;
7pub use crate::graph::graph_impl::NeighborsIter;
8use crate::node::NodeIndex;
9
10/// 节点迭代器
11#[allow(dead_code)]
12pub struct NodeIter<'a, T> {
13    inner: core::slice::Iter<'a, Option<T>>,
14    #[allow(dead_code)]
15    current_index: usize,
16}
17
18impl<'a, T> NodeIter<'a, T> {
19    #[allow(dead_code)]
20    pub(crate) fn new(data: &'a [Option<T>]) -> Self {
21        Self {
22            inner: data.iter(),
23            current_index: 0,
24        }
25    }
26}
27
28/// 边迭代器
29#[allow(dead_code)]
30pub struct EdgeIter<'a, E> {
31    inner: core::slice::Iter<'a, Option<E>>,
32    #[allow(dead_code)]
33    current_index: usize,
34}
35
36impl<'a, E> EdgeIter<'a, E> {
37    #[allow(dead_code)]
38    pub(crate) fn new(data: &'a [Option<E>]) -> Self {
39        Self {
40            inner: data.iter(),
41            current_index: 0,
42        }
43    }
44}
45
46/// 邻居迭代器(包装 CSR 迭代器)
47pub struct Neighbors<'a> {
48    indices: core::ops::Range<usize>,
49    col_indices: &'a [usize],
50}
51
52impl<'a> Neighbors<'a> {
53    #[allow(dead_code)]
54    pub(crate) fn new(range: core::ops::Range<usize>, col_indices: &'a [usize]) -> Self {
55        Self {
56            indices: range,
57            col_indices,
58        }
59    }
60}
61
62impl<'a> Iterator for Neighbors<'a> {
63    type Item = NodeIndex;
64
65    #[inline]
66    fn next(&mut self) -> Option<Self::Item> {
67        self.indices
68            .next()
69            .map(|idx| NodeIndex::new(self.col_indices[idx], 0))
70    }
71
72    #[inline]
73    fn size_hint(&self) -> (usize, Option<usize>) {
74        self.indices.size_hint()
75    }
76}
77
78impl<'a> ExactSizeIterator for Neighbors<'a> {}
79impl<'a> core::iter::FusedIterator for Neighbors<'a> {}
80
81/// 关联边迭代器
82pub struct IncidentEdges<'a> {
83    indices: core::ops::Range<usize>,
84    edge_indices: &'a [usize],
85}
86
87impl<'a> IncidentEdges<'a> {
88    #[allow(dead_code)]
89    pub(crate) fn new(range: core::ops::Range<usize>, edge_indices: &'a [usize]) -> Self {
90        Self {
91            indices: range,
92            edge_indices,
93        }
94    }
95}
96
97impl<'a> Iterator for IncidentEdges<'a> {
98    type Item = EdgeIndex;
99
100    #[inline]
101    fn next(&mut self) -> Option<Self::Item> {
102        self.indices
103            .next()
104            .map(|idx| EdgeIndex::new(self.edge_indices[idx], 0))
105    }
106
107    #[inline]
108    fn size_hint(&self) -> (usize, Option<usize>) {
109        self.indices.size_hint()
110    }
111}
112
113impl<'a> ExactSizeIterator for IncidentEdges<'a> {}
114impl<'a> core::iter::FusedIterator for IncidentEdges<'a> {}