Skip to main content

buffering_runtime/
stall_memory.rs

1//! Stall memory: a max-hold of the PDV with a hold then a linear decay.
2
3use crate::config::Micros;
4
5/// Plain-data snapshot of the stall memory, for session persistence.
6///
7/// **Aging semantics.** `peak_us` is the raw held peak; `age_us` is how long
8/// ago (on the controller's arrival clock) that peak was observed. The
9/// decayed value is `peak` while `age <= hold`, then falls linearly to 0 over
10/// `decay`. A snapshot restored after `N` seconds of wall time must be aged by
11/// `N` first: [`StallMemorySnapshot::aged`]. The restored memory is anchored
12/// at the first clock reading the new controller sees, so a restore adds no
13/// extra age of its own.
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16#[non_exhaustive]
17pub struct StallMemorySnapshot {
18    /// Raw held peak PDV.
19    pub peak_us: Micros,
20    /// Age of that peak.
21    pub age_us: Micros,
22}
23
24impl StallMemorySnapshot {
25    /// Build a snapshot. The struct is `#[non_exhaustive]`, so a foreign
26    /// crate or FFI wrapper cannot use a struct literal: this `const fn` is
27    /// the constructor (usable in `const`/`static` context; `Default` is the
28    /// empty memory and the fields stay public for reading).
29    #[must_use]
30    pub const fn new(peak_us: Micros, age_us: Micros) -> Self {
31        Self { peak_us, age_us }
32    }
33
34    /// The same memory `elapsed_us` of wall time later (saturating).
35    #[must_use]
36    pub const fn aged(self, elapsed_us: Micros) -> Self {
37        Self {
38            peak_us: self.peak_us,
39            age_us: self.age_us.saturating_add(elapsed_us),
40        }
41    }
42}
43
44/// Decayed value of a peak of the given age.
45pub(crate) fn decayed(peak: u64, age: u64, hold: u64, decay: u64) -> u64 {
46    if age <= hold {
47        return peak;
48    }
49    let into = age - hold;
50    if into >= decay {
51        return 0;
52    }
53    let v = u128::from(peak) * u128::from(decay - into) / u128::from(decay.max(1));
54    u64::try_from(v).unwrap_or(u64::MAX)
55}
56
57#[derive(Clone, Debug)]
58pub(crate) struct MaxHold {
59    peak: u64,
60    at: Option<u64>,
61    pending_age: Option<u64>,
62    hold: u64,
63    decay: u64,
64}
65
66impl MaxHold {
67    pub(crate) fn new(hold: u64, decay: u64) -> Self {
68        Self {
69            peak: 0,
70            at: None,
71            pending_age: None,
72            hold,
73            decay,
74        }
75    }
76
77    /// Anchor a restored-but-unplaced snapshot at the clock reading `now`.
78    pub(crate) fn anchor(&mut self, now: u64) {
79        if let Some(age) = self.pending_age.take() {
80            self.at = Some(now.saturating_sub(age));
81        }
82    }
83
84    pub(crate) fn value(&self, now: u64) -> u64 {
85        match (self.at, self.pending_age) {
86            (Some(at), _) => decayed(self.peak, now.saturating_sub(at), self.hold, self.decay),
87            (None, Some(age)) => decayed(self.peak, age, self.hold, self.decay),
88            (None, None) => 0,
89        }
90    }
91
92    /// Sample-driven: a sample at least as large as the current decayed
93    /// value replaces the peak (so the memory rises immediately).
94    pub(crate) fn observe(&mut self, now: u64, v: u64) {
95        self.anchor(now);
96        if self.at.is_none() || v >= self.value(now) {
97            self.peak = v;
98            self.at = Some(now);
99        }
100    }
101
102    pub(crate) fn snapshot(&self, now: u64) -> StallMemorySnapshot {
103        match (self.at, self.pending_age) {
104            (Some(at), _) => StallMemorySnapshot::new(self.peak, now.saturating_sub(at)),
105            (None, Some(age)) => StallMemorySnapshot::new(self.peak, age),
106            (None, None) => StallMemorySnapshot::default(),
107        }
108    }
109
110    pub(crate) fn restore(&mut self, s: StallMemorySnapshot) {
111        self.peak = s.peak_us;
112        self.at = None;
113        self.pending_age = Some(s.age_us);
114    }
115
116    pub(crate) fn clear(&mut self) {
117        self.peak = 0;
118        self.at = None;
119        self.pending_age = None;
120    }
121}