Skip to main content

rustnet_core/network/
interface_stats.rs

1use std::io;
2use std::time::{Duration, SystemTime};
3
4/// Statistics for a network interface
5#[derive(Debug, Clone)]
6pub struct InterfaceStats {
7    pub interface_name: String,
8    pub rx_bytes: u64,
9    pub tx_bytes: u64,
10    pub rx_packets: u64,
11    pub tx_packets: u64,
12    pub rx_errors: u64,
13    pub tx_errors: u64,
14    pub rx_dropped: u64,
15    pub tx_dropped: u64,
16    pub collisions: u64,
17    pub timestamp: SystemTime,
18}
19
20impl InterfaceStats {
21    /// Calculate rates from two snapshots
22    pub fn calculate_rates(&self, previous: &InterfaceStats) -> InterfaceRates {
23        let duration = self
24            .timestamp
25            .duration_since(previous.timestamp)
26            .unwrap_or_default()
27            .as_secs_f64();
28
29        if duration == 0.0 {
30            return InterfaceRates::default();
31        }
32
33        InterfaceRates {
34            rx_bytes_per_sec: ((self.rx_bytes.saturating_sub(previous.rx_bytes)) as f64 / duration)
35                as u64,
36            tx_bytes_per_sec: ((self.tx_bytes.saturating_sub(previous.tx_bytes)) as f64 / duration)
37                as u64,
38        }
39    }
40
41    /// Calculate traffic transferred between two cumulative snapshots.
42    pub fn traffic_since(&self, previous: &InterfaceStats) -> InterfaceTrafficWindow {
43        let sampled_for = self
44            .timestamp
45            .duration_since(previous.timestamp)
46            .unwrap_or_default();
47
48        if sampled_for.is_zero() {
49            return InterfaceTrafficWindow::default();
50        }
51
52        InterfaceTrafficWindow {
53            rx_bytes: self.rx_bytes.saturating_sub(previous.rx_bytes),
54            tx_bytes: self.tx_bytes.saturating_sub(previous.tx_bytes),
55            sampled_for,
56        }
57    }
58}
59
60/// Rate calculations for interface statistics
61#[derive(Debug, Clone, Default)]
62pub struct InterfaceRates {
63    pub rx_bytes_per_sec: u64,
64    pub tx_bytes_per_sec: u64,
65}
66
67/// Traffic transferred over a rolling interface-counter window.
68#[derive(Debug, Clone, Default)]
69pub struct InterfaceTrafficWindow {
70    pub rx_bytes: u64,
71    pub tx_bytes: u64,
72    pub sampled_for: Duration,
73}
74
75/// Trait for platform-specific interface statistics providers
76pub trait InterfaceStatsProvider: Send + Sync {
77    /// Get statistics for all available interfaces
78    fn get_all_stats(&self) -> Result<Vec<InterfaceStats>, io::Error>;
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84    use std::time::Duration;
85
86    #[test]
87    fn test_rate_calculation() {
88        let t1 = SystemTime::now();
89        let t2 = t1 + Duration::from_secs(1);
90
91        let stats1 = InterfaceStats {
92            interface_name: "test".to_string(),
93            rx_bytes: 1000,
94            tx_bytes: 500,
95            rx_packets: 10,
96            tx_packets: 5,
97            rx_errors: 0,
98            tx_errors: 0,
99            rx_dropped: 0,
100            tx_dropped: 0,
101            collisions: 0,
102            timestamp: t1,
103        };
104
105        let stats2 = InterfaceStats {
106            interface_name: "test".to_string(),
107            rx_bytes: 2000,
108            tx_bytes: 1000,
109            rx_packets: 20,
110            tx_packets: 10,
111            rx_errors: 0,
112            tx_errors: 0,
113            rx_dropped: 0,
114            tx_dropped: 0,
115            collisions: 0,
116            timestamp: t2,
117        };
118
119        let rates = stats2.calculate_rates(&stats1);
120        assert_eq!(rates.rx_bytes_per_sec, 1000);
121        assert_eq!(rates.tx_bytes_per_sec, 500);
122    }
123
124    #[test]
125    fn test_rate_calculation_zero_duration() {
126        let t = SystemTime::now();
127
128        let stats1 = InterfaceStats {
129            interface_name: "test".to_string(),
130            rx_bytes: 1000,
131            tx_bytes: 500,
132            rx_packets: 10,
133            tx_packets: 5,
134            rx_errors: 0,
135            tx_errors: 0,
136            rx_dropped: 0,
137            tx_dropped: 0,
138            collisions: 0,
139            timestamp: t,
140        };
141
142        let stats2 = stats1.clone();
143
144        let rates = stats2.calculate_rates(&stats1);
145        assert_eq!(rates.rx_bytes_per_sec, 0);
146        assert_eq!(rates.tx_bytes_per_sec, 0);
147    }
148
149    #[test]
150    fn test_rate_calculation_with_counter_wrapping() {
151        let t1 = SystemTime::now();
152        let t2 = t1 + Duration::from_secs(1);
153
154        let stats1 = InterfaceStats {
155            interface_name: "test".to_string(),
156            rx_bytes: 1000,
157            tx_bytes: 500,
158            rx_packets: 10,
159            tx_packets: 5,
160            rx_errors: 0,
161            tx_errors: 0,
162            rx_dropped: 0,
163            tx_dropped: 0,
164            collisions: 0,
165            timestamp: t1,
166        };
167
168        // Simulate counter reset (should use saturating_sub to avoid panic)
169        let stats2 = InterfaceStats {
170            interface_name: "test".to_string(),
171            rx_bytes: 500, // Less than previous
172            tx_bytes: 250,
173            rx_packets: 5,
174            tx_packets: 2,
175            rx_errors: 0,
176            tx_errors: 0,
177            rx_dropped: 0,
178            tx_dropped: 0,
179            collisions: 0,
180            timestamp: t2,
181        };
182
183        let rates = stats2.calculate_rates(&stats1);
184        // Should result in 0 due to saturating_sub
185        assert_eq!(rates.rx_bytes_per_sec, 0);
186        assert_eq!(rates.tx_bytes_per_sec, 0);
187    }
188
189    #[test]
190    fn test_traffic_since() {
191        let t1 = SystemTime::now();
192        let t2 = t1 + Duration::from_secs(60);
193        let first = InterfaceStats {
194            interface_name: "test".to_string(),
195            rx_bytes: 1_000,
196            tx_bytes: 500,
197            rx_packets: 0,
198            tx_packets: 0,
199            rx_errors: 0,
200            tx_errors: 0,
201            rx_dropped: 0,
202            tx_dropped: 0,
203            collisions: 0,
204            timestamp: t1,
205        };
206        let second = InterfaceStats {
207            rx_bytes: 9_000,
208            tx_bytes: 2_500,
209            timestamp: t2,
210            ..first.clone()
211        };
212
213        let window = second.traffic_since(&first);
214        assert_eq!(window.rx_bytes, 8_000);
215        assert_eq!(window.tx_bytes, 2_000);
216        assert_eq!(window.sampled_for, Duration::from_secs(60));
217    }
218}