buffering_runtime/window.rs
1//! Sliding minimum over a trailing time window (monotonic deque).
2
3use crate::error::Error;
4use crate::time::window_micros;
5use alloc::collections::VecDeque;
6
7/// Monotonic-deque sliding minimum of `(time, value)` samples.
8///
9/// Amortised O(1) per push. The deque is pre-sized to `max_samples + 1` so no
10/// allocation happens after construction; over the cap the oldest entry is
11/// dropped (the window shrinks) and counted.
12#[derive(Clone, Debug)]
13pub struct MinWindow {
14 dq: VecDeque<(u64, i64)>,
15 window_us: u64,
16 cap: usize,
17 overflows: u32,
18 last_t: Option<u64>,
19}
20
21impl MinWindow {
22 /// New window of `window` holding at most `max_samples` entries.
23 ///
24 /// # Errors
25 /// [`Error::ZeroLengthWindow`] when `window` is zero.
26 pub fn new(window: core::time::Duration, max_samples: u16) -> Result<Self, Error> {
27 let window_us = window_micros(window);
28 if window_us == 0 {
29 return Err(Error::ZeroLengthWindow);
30 }
31 let cap = usize::from(max_samples).max(1);
32 Ok(Self {
33 dq: VecDeque::with_capacity(cap + 1),
34 window_us,
35 cap,
36 overflows: 0,
37 last_t: None,
38 })
39 }
40
41 /// Add a sample at time `t` (non-decreasing) and return the minimum of
42 /// the samples within the trailing window (inclusive of this one).
43 ///
44 /// **Long-gap rule.** If the silence since the previous sample is at
45 /// least the window, expiry is skipped for this one push: otherwise a
46 /// delivery stall longer than the window (2 s, 4 s) would
47 /// evict the whole pre-stall baseline and the first post-stall sample
48 /// would read a PDV of 0. The next push (normal spacing) expires the old
49 /// entries as usual.
50 pub fn push(&mut self, t: u64, v: i64) -> i64 {
51 let long_gap = self
52 .last_t
53 .is_some_and(|p| t.saturating_sub(p) >= self.window_us);
54 self.last_t = Some(t);
55 while self.dq.back().is_some_and(|b| b.1 >= v) {
56 self.dq.pop_back();
57 }
58 self.dq.push_back((t, v));
59 while !long_gap
60 && self.dq.len() > 1
61 && self
62 .dq
63 .front()
64 .is_some_and(|f| f.0.saturating_add(self.window_us) <= t)
65 {
66 self.dq.pop_front();
67 }
68 while self.dq.len() > self.cap {
69 self.dq.pop_front();
70 self.overflows = self.overflows.saturating_add(1);
71 }
72 self.dq.front().map_or(v, |f| f.1)
73 }
74
75 /// Current minimum, `None` when empty.
76 #[must_use]
77 pub fn min(&self) -> Option<i64> {
78 self.dq.front().map(|f| f.1)
79 }
80
81 /// Entries currently held.
82 #[must_use]
83 pub fn len(&self) -> usize {
84 self.dq.len()
85 }
86
87 /// True when no sample is held.
88 #[must_use]
89 pub fn is_empty(&self) -> bool {
90 self.dq.is_empty()
91 }
92
93 /// Entries dropped because the cap was hit.
94 #[must_use]
95 pub fn overflows(&self) -> u32 {
96 self.overflows
97 }
98
99 /// Drop every sample (the overflow counter is kept).
100 pub fn clear(&mut self) {
101 self.dq.clear();
102 self.last_t = None;
103 }
104}