qualia_core_db/net/qdnf/link/
neighbor.rs1use crate::net::qdnf::errors::QdnfError;
4use crate::net::qdnf::types::LinkId;
5
6use super::adjacency::{Adjacency, AdjacencyState};
7
8pub const MAX_NEIGHBORS: usize = 32;
9
10pub struct NeighborTable {
11 slots: [Option<Adjacency>; MAX_NEIGHBORS],
12}
13
14impl NeighborTable {
15 pub const fn new() -> Self {
17 Self {
18 slots: [None; MAX_NEIGHBORS],
19 }
20 }
21
22 pub fn insert(&mut self, adj: Adjacency) -> Result<usize, QdnfError> {
24 for slot in self.slots.iter() {
25 if let Some(existing) = slot {
26 if existing.remote.0 == adj.remote.0 {
27 return Ok(0);
28 }
29 }
30 }
31 for (i, slot) in self.slots.iter_mut().enumerate() {
32 if slot.is_none() {
33 *slot = Some(adj);
34 return Ok(i);
35 }
36 }
37 Err(QdnfError::Capacity)
38 }
39
40 pub fn insert_verified(&mut self, adj: Adjacency, verified: bool) -> Result<usize, QdnfError> {
43 if !verified {
44 return Err(QdnfError::Unauthorized);
45 }
46 self.insert(adj)
47 }
48
49 pub fn forwarding(&self, remote: LinkId) -> Option<&Adjacency> {
51 self.slots
52 .iter()
53 .flatten()
54 .find(|a| a.remote.0 == remote.0 && a.state == AdjacencyState::Adjacent)
55 }
56
57 pub fn len(&self) -> usize {
59 self.slots.iter().filter(|s| s.is_some()).count()
60 }
61}
62
63impl Default for NeighborTable {
64 fn default() -> Self {
65 Self::new()
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72 use crate::net::qdnf::types::ObservedLocator;
73
74 #[test]
75 fn full_table_does_not_allocate() {
76 let mut table = NeighborTable::new();
77 for i in 0..MAX_NEIGHBORS {
78 let mut remote = LinkId::ZERO;
79 remote.0[0] = i as u8 + 1;
80 table
81 .insert(Adjacency {
82 local: LinkId::ZERO,
83 remote,
84 observed_peer: ObservedLocator::EMPTY,
85 state: AdjacencyState::Adjacent,
86 generation: 1,
87 mtu: 1280,
88 })
89 .unwrap();
90 }
91 let mut extra = LinkId::ZERO;
92 extra.0[0] = 99;
93 assert_eq!(
94 table.insert(Adjacency {
95 local: LinkId::ZERO,
96 remote: extra,
97 observed_peer: ObservedLocator::EMPTY,
98 state: AdjacencyState::Adjacent,
99 generation: 1,
100 mtu: 1280,
101 }),
102 Err(QdnfError::Capacity)
103 );
104 }
105
106 #[test]
107 fn unverified_challenge_does_not_insert() {
108 let mut table = NeighborTable::new();
109 assert_eq!(
110 table.insert_verified(
111 Adjacency {
112 local: LinkId::ZERO,
113 remote: LinkId([1u8; 16]),
114 observed_peer: ObservedLocator::EMPTY,
115 state: AdjacencyState::BeaconSeen,
116 generation: 1,
117 mtu: 1280,
118 },
119 false,
120 ),
121 Err(QdnfError::Unauthorized)
122 );
123 assert_eq!(table.len(), 0);
124 }
125}