#[derive(Debug, Clone, Default)]
pub struct PeerStatistics {
pub packets_sent: u64,
pub packets_received: u64,
pub packets_lost: u64,
pub bytes_sent: u64,
pub bytes_received: u64,
}
impl PeerStatistics {
pub fn packet_loss_rate(&self) -> f32 {
if self.packets_sent == 0 {
return 0.0;
}
self.packets_lost as f32 / self.packets_sent as f32
}
pub fn reset(&mut self) {
*self = Self::default();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_statistics_initialized_to_zero() {
let stats = PeerStatistics::default();
assert_eq!(stats.packets_sent, 0);
assert_eq!(stats.packets_received, 0);
assert_eq!(stats.packets_lost, 0);
assert_eq!(stats.bytes_sent, 0);
assert_eq!(stats.bytes_received, 0);
assert_eq!(stats.packet_loss_rate(), 0.0);
}
#[test]
fn test_statistics_packet_loss_rate() {
let mut stats = PeerStatistics::default();
stats.packets_sent = 100;
stats.packets_lost = 10;
let loss_rate = stats.packet_loss_rate();
assert!((loss_rate - 0.1).abs() < 0.001); }
#[test]
fn test_statistics_packet_loss_rate_no_packets_sent() {
let stats = PeerStatistics::default();
assert_eq!(stats.packet_loss_rate(), 0.0);
}
#[test]
fn test_statistics_reset() {
let mut stats = PeerStatistics::default();
stats.packets_sent = 100;
stats.packets_received = 90;
stats.packets_lost = 10;
stats.bytes_sent = 10000;
stats.bytes_received = 9000;
stats.reset();
assert_eq!(stats.packets_sent, 0);
assert_eq!(stats.packets_received, 0);
assert_eq!(stats.packets_lost, 0);
assert_eq!(stats.bytes_sent, 0);
assert_eq!(stats.bytes_received, 0);
}
#[test]
fn test_statistics_track_packet_loss() {
let mut stats = PeerStatistics::default();
stats.packets_lost = 5;
assert_eq!(stats.packets_lost, 5);
}
}