Skip to main content

buffering_runtime/
window.rs

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