//! Bounded Ethernet frame admission for one local unicast MAC and broadcast. pub const HEADER:usize=14; pub const MAX_FRAME:usize=1514; #[derive(Clone,Copy,Debug,PartialEq,Eq)] #[repr(u64)] pub enum Error { Length=1, Destination=2, LocalMac=3 } #[derive(Clone,Copy,Debug,PartialEq,Eq)] #[repr(u64)] pub enum Destination { Local=1, Broadcast=2 } #[derive(Debug,PartialEq,Eq)] pub struct Frame<'a>{bytes:&'a[u8],destination:Destination} impl<'a> Frame<'a>{ pub fn bytes(&self)->&'a[u8]{self.bytes} pub fn payload(&self)->&'a[u8]{&self.bytes[HEADER..]} pub fn destination(&self)->Destination{self.destination} pub fn source(&self)->[u8;6]{let mut m=[0;6];m.copy_from_slice(&self.bytes[6..12]);m} pub fn protocol(&self)->u16{u16::from_be_bytes([self.bytes[12],self.bytes[13]])} } #[derive(Clone,Copy,Debug,PartialEq,Eq)] pub struct Ethernet {local:[u8;6]} impl Ethernet { pub fn new(local:[u8;6])->Result{if local==[0;6]||local[0]&1!=0{return Err(Error::LocalMac);}Ok(Self{local})} pub fn local(&self)->[u8;6]{self.local} pub fn parse<'a>(&self,bytes:&'a[u8])->Result,Error>{ if bytes.len()MAX_FRAME{return Err(Error::Length);} let destination=if bytes[..6]==self.local{Destination::Local}else if bytes[..6]==[255;6]{Destination::Broadcast}else{return Err(Error::Destination);}; Ok(Frame{bytes,destination}) } pub fn deliver(&self,bytes:&[u8],sink:impl FnOnce(Frame<'_>))->Result<(),Error>{let frame=self.parse(bytes)?;sink(frame);Ok(())} }