1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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])
}
}
|