use std::time::{Duration, Instant};
const DEFAULT_WINDOW_SIZE: usize = 10;
const SAMPLE_INTERVAL_MS: u64 = 500;
const BURST_THRESHOLD_MULTIPLIER: f64 = 3.0;
pub struct SpeedSmoother {
ema_speed: f64,
alpha: f64,
last_update: Option<Instant>,
raw_total_bytes: u64,
sample_start: Option<Instant>,
samples_count: usize,
last_instant_speed: f64,
}
impl SpeedSmoother {
pub fn new(window_size: usize) -> Self {
let n = if window_size == 0 {
DEFAULT_WINDOW_SIZE
} else {
window_size
};
Self {
ema_speed: 0.0,
alpha: 2.0 / (n as f64 + 1.0),
last_update: None,
raw_total_bytes: 0,
sample_start: None,
samples_count: 0,
last_instant_speed: 0.0,
}
}
pub fn with_default_window() -> Self {
Self::new(DEFAULT_WINDOW_SIZE)
}
pub fn record_bytes(&mut self, bytes: u64) {
let now = Instant::now();
if self.sample_start.is_none() {
self.sample_start = Some(now);
}
self.raw_total_bytes += bytes;
let should_sample = match self.last_update {
Some(last) => now.duration_since(last) >= Duration::from_millis(SAMPLE_INTERVAL_MS),
None => true, };
if should_sample {
self.update_ema(now);
}
}
fn update_ema(&mut self, now: Instant) {
let sample_duration = match self.sample_start {
Some(start) => now.duration_since(start).as_secs_f64(),
None => return,
};
if sample_duration <= 0.0 {
return;
}
let instant_speed = self.raw_total_bytes as f64 / sample_duration;
self.last_instant_speed = instant_speed;
if self.samples_count == 0 {
self.ema_speed = instant_speed;
} else {
self.ema_speed = self.alpha * instant_speed + (1.0 - self.alpha) * self.ema_speed;
}
self.raw_total_bytes = 0;
self.sample_start = Some(now);
self.last_update = Some(now);
self.samples_count += 1;
}
pub fn smoothed_speed(&self) -> f64 {
self.ema_speed.max(0.0)
}
pub fn instant_speed(&self) -> f64 {
if self.raw_total_bytes > 0 {
let now = Instant::now();
if let Some(start) = self.sample_start {
let elapsed = now.duration_since(start).as_secs_f64();
if elapsed > 0.0 {
return self.raw_total_bytes as f64 / elapsed;
}
}
}
self.last_instant_speed
}
pub fn eta_seconds(&self, remaining: u64) -> Option<u64> {
let speed = self.smoothed_speed();
if speed <= 0.0 {
return None;
}
Some((remaining as f64 / speed).ceil() as u64)
}
pub fn is_burst(&self) -> bool {
let instant = self.instant_speed();
let ema = self.smoothed_speed();
ema > 0.0 && instant > BURST_THRESHOLD_MULTIPLIER * ema
}
pub fn reset(&mut self) {
self.ema_speed = 0.0;
self.last_update = None;
self.raw_total_bytes = 0;
self.sample_start = None;
self.samples_count = 0;
self.last_instant_speed = 0.0;
}
pub fn samples_count(&self) -> usize {
self.samples_count
}
pub fn alpha(&self) -> f64 {
self.alpha
}
}
impl Default for SpeedSmoother {
fn default() -> Self {
Self::with_default_window()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ema_convergence() {
let smoother = SpeedSmoother::new(10);
let expected_alpha = 2.0 / 11.0;
assert!(
(smoother.alpha() - expected_alpha).abs() < 0.0001,
"Alpha should be 2/(N+1) ≈ 0.1818, got {}",
smoother.alpha()
);
assert_eq!(smoother.smoothed_speed(), 0.0);
assert_eq!(smoother.samples_count(), 0);
}
#[test]
fn test_record_bytes_accumulates() {
let mut smoother = SpeedSmoother::new(10);
smoother.record_bytes(1000);
smoother.record_bytes(500);
assert!(
smoother.smoothed_speed() >= 0.0,
"Speed must be non-negative"
);
}
#[test]
fn test_reset_clears_state() {
let mut smoother = SpeedSmoother::new(10);
smoother.record_bytes(5000);
smoother.reset();
assert_eq!(
smoother.smoothed_speed(),
0.0,
"Speed should be 0 after reset"
);
assert_eq!(
smoother.samples_count(),
0,
"Sample count should be 0 after reset"
);
assert_eq!(
smoother.instant_speed(),
0.0,
"Instant speed should be 0 after reset"
);
let eta = smoother.eta_seconds(12345);
assert!(eta.is_none(), "ETA should be None after reset (no speed)");
assert!(
!smoother.is_burst(),
"Should not be in burst state after reset"
);
}
#[test]
fn test_eta_edge_cases() {
let smoother = SpeedSmoother::new(10);
let eta_no_speed = smoother.eta_seconds(99999);
assert!(
eta_no_speed.is_none(),
"ETA should be None when speed is zero"
);
}
#[test]
fn test_burst_detection_logic() {
let smoother = SpeedSmoother::new(10);
assert!(!smoother.is_burst(), "Should not be burst initially");
}
#[test]
fn test_default_window_size_alpha() {
let smoother = SpeedSmoother::default();
let expected_alpha = 2.0 / (DEFAULT_WINDOW_SIZE as f64 + 1.0);
assert!(
(smoother.alpha() - expected_alpha).abs() < 0.0001,
"Default alpha should be 2/(N+1)"
);
}
#[test]
fn test_custom_window_size() {
let small_window = SpeedSmoother::new(5);
let large_window = SpeedSmoother::new(20);
assert!(
small_window.alpha() > large_window.alpha(),
"Smaller window should have higher alpha"
);
assert!(small_window.alpha() > 0.0 && small_window.alpha() <= 1.0);
assert!(large_window.alpha() > 0.0 && large_window.alpha() <= 1.0);
}
}