lattice_graph/lattice_abstract/
neighbors.rs1use std::iter::FusedIterator;
2
3use petgraph::visit::{GetAdjacencyMatrix, IntoNeighbors, IntoNeighborsDirected};
4
5use super::*;
6
7#[derive(Debug)]
9pub struct Neighbors<'a, N, E, S: Shape, C = <S as Shape>::Coordinate> {
10 graph: &'a LatticeGraph<N, E, S>,
11 node: C,
12 state: usize,
13}
14
15impl<'a, N, E, S: Shape, C> Neighbors<'a, N, E, S, C> {
16 pub(crate) fn new(graph: &'a LatticeGraph<N, E, S>, node: C) -> Self {
17 Self {
18 graph,
19 node,
20 state: 0,
21 }
22 }
23}
24
25impl<'a, N, E, S, C, D> Iterator for Neighbors<'a, N, E, S, C>
26where
27 C: Copy,
28 S: Shape<Coordinate = C>,
29 S::Axis: Axis<Direction = D>,
30 D: AxisDirection + Clone,
31{
32 type Item = C;
33
34 fn next(&mut self) -> Option<Self::Item> {
35 while self.state < S::Axis::UNDIRECTED_COUNT {
36 unsafe {
37 let d = D::dir_from_index_unchecked(self.state);
38 let n = self.graph.s.move_coord(self.node, d.clone());
39 self.state += 1;
40 if let Ok(target) = n {
41 return Some(target);
42 }
43 }
44 }
45 None
46 }
47
48 fn size_hint(&self) -> (usize, Option<usize>) {
49 let x = S::Axis::UNDIRECTED_COUNT - self.state;
50 (0, Some(x))
51 }
52}
53
54impl<'a, N, E, S, C, D> FusedIterator for Neighbors<'a, N, E, S, C>
55where
56 C: Copy,
57 S: Shape<Coordinate = C>,
58 S::Axis: Axis<Direction = D>,
59 D: AxisDirection + Clone,
60{
61}
62
63impl<'a, N, E, S, D> IntoNeighbors for &'a LatticeGraph<N, E, S>
64where
65 S: Shape,
66 S::Axis: Axis<Direction = D>,
67 D: AxisDirection + Clone,
68{
69 type Neighbors = Neighbors<'a, N, E, S>;
70
71 fn neighbors(self, a: Self::NodeId) -> Self::Neighbors {
72 Neighbors::new(self, a)
73 }
74}
75
76impl<'a, N, E, S, D> IntoNeighborsDirected for &'a LatticeGraph<N, E, S>
77where
78 S: Shape,
79 S::Axis: Axis<Direction = D>,
80 D: AxisDirection + Clone,
81{
82 type NeighborsDirected = Neighbors<'a, N, E, S>;
83
84 fn neighbors_directed(self, a: Self::NodeId, _d: petgraph::Direction) -> Self::Neighbors {
85 Neighbors::new(self, a)
86 }
87}
88
89impl<N, E, S, C> GetAdjacencyMatrix for LatticeGraph<N, E, S>
90where
91 C: Copy + PartialEq,
92 S: Shape<Coordinate = C>,
93{
94 type AdjMatrix = ();
95 fn adjacency_matrix(&self) -> Self::AdjMatrix {}
96
97 fn is_adjacent(&self, _matrix: &Self::AdjMatrix, a: Self::NodeId, b: Self::NodeId) -> bool {
98 self.s.is_neighbor(a, b)
99 }
100}