From 25b0631f1af74fcf1e1d8782f6d763881ad58af7 Mon Sep 17 00:00:00 2001 From: gennyble Date: Sat, 17 May 2025 13:12:35 -0500 Subject: get usage over tcp socket --- src/count.rs | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/count.rs (limited to 'src/count.rs') diff --git a/src/count.rs b/src/count.rs new file mode 100644 index 0000000..c3d92bf --- /dev/null +++ b/src/count.rs @@ -0,0 +1,67 @@ +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]) + } +} -- cgit 1.4.1-3-g733a5