qualia_core_db/net/qdnf/route/
forwarding.rs1use crate::net::qdnf::errors::QdnfError;
4use crate::net::qdnf::types::LinkId;
5
6use super::spf::SpfTable;
7
8#[repr(C)]
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub struct ForwardingGeneration {
11 pub id: u64,
12 pub table: SpfTable,
13 pub published: bool,
14}
15
16impl ForwardingGeneration {
17 pub const fn empty(id: u64) -> Self {
19 Self {
20 id,
21 table: SpfTable::EMPTY,
22 published: false,
23 }
24 }
25
26 pub fn publish(&mut self, table: SpfTable) -> Result<(), QdnfError> {
28 if table.nodes == 0 {
29 return Err(QdnfError::Incomplete);
30 }
31 self.table = table;
32 self.published = true;
33 Ok(())
34 }
35
36 pub fn lookup_next(&self, dest_node: u8) -> Result<u8, QdnfError> {
38 if !self.published {
39 return Err(QdnfError::Incomplete);
40 }
41 for i in 0..self.table.nodes {
42 if self.table.dest[i] == dest_node {
43 if self.table.hop_counts[i] == 0 {
44 return Ok(dest_node);
45 }
46 return Ok(self.table.hops[i][0].node);
47 }
48 }
49 Err(QdnfError::NoRoute)
50 }
51}
52
53pub fn decrement_hop(hop_limit: u8) -> Result<u8, QdnfError> {
55 if hop_limit == 0 {
56 Err(QdnfError::HopLimit)
57 } else {
58 Ok(hop_limit - 1)
59 }
60}
61
62pub fn require_adjacency(neighbors: &[LinkId], next: LinkId) -> Result<(), QdnfError> {
64 if neighbors.iter().any(|n| n.0 == next.0) {
65 Ok(())
66 } else {
67 Err(QdnfError::NoRoute)
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 #[test]
76 fn unpublished_table_cannot_forward() {
77 let gen = ForwardingGeneration::empty(1);
78 assert_eq!(gen.lookup_next(1), Err(QdnfError::Incomplete));
79 }
80}