qualia_core_db/net/peer/connectivity/
rendezvous.rs1pub const MAX_RECORDS: usize = 16;
4pub const MAX_BODY: usize = 128;
5pub const MAX_RELAY_SET: usize = 8;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub struct Record {
9 pub cap: [u8; 16],
10 pub expiry_unix: u32,
11 pub len: u16,
12 pub body: [u8; MAX_BODY],
13}
14
15impl Record {
16 pub const fn empty() -> Self {
18 Self {
19 cap: [0; 16],
20 expiry_unix: 0,
21 len: 0,
22 body: [0; MAX_BODY],
23 }
24 }
25}
26
27#[derive(Debug, Clone, Copy)]
28pub struct RendezvousStore {
29 recs: [Record; MAX_RECORDS],
30 len: usize,
31}
32
33impl RendezvousStore {
34 pub const fn new() -> Self {
36 Self {
37 recs: [Record::empty(); MAX_RECORDS],
38 len: 0,
39 }
40 }
41
42 pub fn put(&mut self, cap: [u8; 16], expiry_unix: u32, body: &[u8]) -> Result<(), ()> {
44 if body.len() > MAX_BODY || cap == [0u8; 16] {
45 return Err(());
46 }
47 let mut i = 0;
48 while i < self.len {
49 if self.recs[i].cap == cap {
50 self.recs[i].expiry_unix = expiry_unix;
51 self.recs[i].len = body.len() as u16;
52 self.recs[i].body[..body.len()].copy_from_slice(body);
53 return Ok(());
54 }
55 i += 1;
56 }
57 if self.len >= MAX_RECORDS {
58 return Err(());
59 }
60 let mut r = Record::empty();
61 r.cap = cap;
62 r.expiry_unix = expiry_unix;
63 r.len = body.len() as u16;
64 r.body[..body.len()].copy_from_slice(body);
65 self.recs[self.len] = r;
66 self.len += 1;
67 Ok(())
68 }
69
70 pub fn get(&self, cap: &[u8; 16], now_unix: u32) -> Option<&[u8]> {
72 let mut i = 0;
73 while i < self.len {
74 if &self.recs[i].cap == cap {
75 if now_unix >= self.recs[i].expiry_unix {
76 return None;
77 }
78 return Some(&self.recs[i].body[..self.recs[i].len as usize]);
79 }
80 i += 1;
81 }
82 None
83 }
84}
85
86pub fn common_relay(a: &[u64], b: &[u64]) -> Option<u64> {
88 let mut i = 0;
89 while i < a.len() && i < MAX_RELAY_SET {
90 let mut j = 0;
91 while j < b.len() && j < MAX_RELAY_SET {
92 if a[i] != 0 && a[i] == b[j] {
93 return Some(a[i]);
94 }
95 j += 1;
96 }
97 i += 1;
98 }
99 None
100}
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105
106 #[test]
107 fn opaque_expiry_and_common_relay() {
108 let mut s = RendezvousStore::new();
109 let cap = [1u8; 16];
110 s.put(cap, 50, b"hint").unwrap();
111 assert_eq!(s.get(&cap, 10), Some(&b"hint"[..]));
112 assert!(s.get(&cap, 50).is_none());
113 assert_eq!(common_relay(&[3, 5], &[9, 5]), Some(5));
114 assert!(common_relay(&[3], &[9]).is_none());
115 }
116}