const U16_MAX: usize = u16::MAX as usize; pub struct Count { tcp_tx: Box<[usize]>, tcp_rx: Box<[usize]>, udp_tx: Box<[usize]>, udp_rx: Box<[usize]>, } impl Count { pub fn new() -> Self { Self { tcp_tx: Box::new([0; U16_MAX]), tcp_rx: Box::new([0; U16_MAX]), udp_tx: Box::new([0; U16_MAX]), udp_rx: Box::new([0; U16_MAX]), } } pub fn push_tcp(&mut self, tx_flag: bool, src: u16, dst: u16, len: usize) { // The unsafe code here is bad and not good. As far as I am aware, this // is safe except for allowing race conditions. if tx_flag { let bad_mut = unsafe { &mut *(self.tcp_tx.as_ptr() as *mut [usize; U16_MAX]) }; bad_mut[src as usize] += len; } else { let bad_mut = unsafe { &mut *(self.tcp_rx.as_ptr() as *mut [usize; U16_MAX]) }; bad_mut[dst as usize] += len; } } pub fn push_udp(&mut self, tx_flag: bool, src: u16, dst: u16, len: usize) { // The unsafe code here is bad and not good. As far as I am aware, this // is safe except for allowing race conditions. if tx_flag { let bad_mut = unsafe { &mut *(self.udp_tx.as_ptr() as *mut [usize; U16_MAX]) }; bad_mut[src as usize] += len; } else { let bad_mut = unsafe { &mut *(self.udp_rx.as_ptr() as *mut [usize; U16_MAX]) }; bad_mut[dst as usize] += len; } } pub fn tcp_tx(&self, port: u16) -> usize { self.tcp_tx[port as usize] } pub fn tcp_rx(&self, port: u16) -> usize { self.tcp_rx[port as usize] } pub fn udp_tx(&self, port: u16) -> usize { self.udp_tx[port as usize] } pub fn udp_rx(&self, port: u16) -> usize { self.udp_rx[port as usize] } pub fn many_tcp_tx(&self, ports: &[u16]) -> usize { ports.iter().fold(0, |acc, port| acc + self.tcp_tx[*port as usize]) } pub fn many_tcp_rx(&self, ports: &[u16]) -> usize { ports.iter().fold(0, |acc, port| acc + self.tcp_rx[*port as usize]) } }