qualia_core_db/net/qdnf/session/
rtt.rs1use crate::net::qdnf::errors::QdnfError;
7
8#[repr(C)]
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub struct RttEstimator {
11 pub latest_us: u32,
12 pub min_us: u32,
13 pub smoothed_us: u32,
14 pub rttvar_us: u32,
15}
16
17impl RttEstimator {
18 pub const fn new() -> Self {
20 Self {
21 latest_us: 0,
22 min_us: 0,
23 smoothed_us: 0,
24 rttvar_us: 0,
25 }
26 }
27}
28
29impl Default for RttEstimator {
30 fn default() -> Self {
31 Self::new()
32 }
33}
34
35pub fn on_ack_sample(est: &mut RttEstimator, sample_us: u32) {
37 if sample_us == 0 {
38 return;
39 }
40 est.latest_us = sample_us;
41 if est.min_us == 0 || sample_us < est.min_us {
42 est.min_us = sample_us;
43 }
44 if est.smoothed_us == 0 {
45 est.smoothed_us = sample_us;
46 est.rttvar_us = sample_us / 2;
47 return;
48 }
49 let diff = abs_u32(est.smoothed_us, sample_us);
50 est.rttvar_us = (est.rttvar_us.saturating_mul(3).saturating_add(diff)) / 4;
51 est.smoothed_us = (est.smoothed_us.saturating_mul(7).saturating_add(sample_us)) / 8;
52}
53
54#[inline]
55fn abs_u32(a: u32, b: u32) -> u32 {
56 if a >= b {
57 a - b
58 } else {
59 b - a
60 }
61}
62
63pub fn smoothed_or_err(est: &RttEstimator) -> Result<u32, QdnfError> {
65 if est.smoothed_us == 0 {
66 Err(QdnfError::Incomplete)
67 } else {
68 Ok(est.smoothed_us)
69 }
70}
71
72#[cfg(test)]
73mod tests {
74 use super::*;
75
76 #[test]
77 fn first_sample_seeds_min_smoothed_and_rttvar() {
78 let mut est = RttEstimator::new();
79 on_ack_sample(&mut est, 1000);
80 assert_eq!(est.latest_us, 1000);
81 assert_eq!(est.min_us, 1000);
82 assert_eq!(est.smoothed_us, 1000);
83 assert_eq!(est.rttvar_us, 500);
84 on_ack_sample(&mut est, 0);
85 assert_eq!(est.smoothed_us, 1000);
86 }
87
88 #[test]
89 fn later_sample_tracks_min_and_ewma() {
90 let mut est = RttEstimator::new();
91 on_ack_sample(&mut est, 1000);
92 on_ack_sample(&mut est, 500);
93 assert_eq!(est.min_us, 500);
94 assert_eq!(est.latest_us, 500);
95 assert!(est.smoothed_us < 1000);
96 assert!(est.smoothed_us > 500);
97 assert_eq!(smoothed_or_err(&est), Ok(est.smoothed_us));
98 }
99
100 #[test]
101 fn unknown_rtt_is_incomplete() {
102 assert_eq!(
103 smoothed_or_err(&RttEstimator::new()),
104 Err(QdnfError::Incomplete)
105 );
106 }
107}