//! Fixed-capacity neighbour cache. The caller supplies a trusted monotonic clock //! and an already validated IP/MAC pair; this module is not an ARP wire parser. #[derive(Clone,Copy,Debug,PartialEq,Eq)] #[repr(u64)] pub enum Error { Configuration=1, Address=2, Clock=3, TimeOverflow=4, Capacity=5, Conflict=6 } #[derive(Clone,Copy,Debug,PartialEq,Eq)] pub enum Change { Added, Refreshed } #[derive(Clone,Copy,Debug,PartialEq,Eq)] pub struct Entry { pub ip:[u8;4], pub mac:[u8;6], pub expires:u64 } #[derive(Clone,Copy,Debug,PartialEq,Eq)] pub struct Snapshot { pub entries:[Option;N], pub ttl:u64, pub now:u64, pub added:u64, pub refreshed:u64, pub rejected:u64, pub expired:u64 } // Four explicit words keep the physical audit representation independent of // Rust's Option layout. Empty slots have all four words zero. #[repr(C)] #[derive(Clone,Copy)] struct Slot { live:u64, ip:u64, mac:u64, expires:u64 } impl Slot { const EMPTY:Self=Self{live:0,ip:0,mac:0,expires:0}; } #[repr(C)] pub struct Cache { slots:[Slot;N], ttl:u64, now:u64, added:u64, refreshed:u64, rejected:u64, expired:u64 } impl Cache { pub fn new(ttl:u64)->Result{if N==0||N>128||ttl==0{return Err(Error::Configuration);}Ok(Self{slots:[Slot::EMPTY;N],ttl,now:0,added:0,refreshed:0,rejected:0,expired:0})} fn pack_mac(mac:[u8;6])->u64{let mut n=0;for(i,b)in mac.iter().enumerate(){n|=(*b as u64)<<(i*8);}n} fn unpack_mac(n:u64)->[u8;6]{core::array::from_fn(|i|(n>>(i*8))as u8)} pub fn snapshot(&self)->Snapshot{Snapshot{entries:core::array::from_fn(|i|{let s=self.slots[i];if s.live==0{None}else{Some(Entry{ip:(s.ip as u32).to_be_bytes(),mac:Self::unpack_mac(s.mac),expires:s.expires})}}),ttl:self.ttl,now:self.now,added:self.added,refreshed:self.refreshed,rejected:self.rejected,expired:self.expired}} fn ip_valid(ip:[u8;4])->bool {ip!=[0;4]&&ip[0]<224&&ip!=[255;4]} fn advance(&mut self,now:u64)->Result<(),Error>{ if nowResult,Error>{if !Self::ip_valid(ip){return Err(Error::Address);}self.advance(now)?;let ip=u32::from_be_bytes(ip)as u64;Ok(self.slots.iter().find(|s|s.live!=0&&s.ip==ip).map(|s|Self::unpack_mac(s.mac)))} pub fn remember(&mut self,ip:[u8;4],mac:[u8;6],now:u64)->Result{ if !Self::ip_valid(ip)||mac==[0;6]||mac[0]&1!=0{return Err(Error::Address);} if now