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
57fn age_at(now: u64, at: i128) -> u64 {
58    u64::try_from((i128::from(now) - at).max(0)).unwrap_or(u64::MAX)
59}
60
61#[derive(Clone, Debug)]
62pub(crate) struct MaxHold {
63    peak: u64,
64    at: Option<i128>,
65    pending_age: Option<u64>,
66    hold: u64,
67    decay: u64,
68}
69
70impl MaxHold {
71    pub(crate) fn new(hold: u64, decay: u64) -> Self {
72        Self {
73            peak: 0,
74            at: None,
75            pending_age: None,
76            hold,
77            decay,
78        }
79    }
80
81    /// Anchor a restored-but-unplaced snapshot at the clock reading `now`.
82    pub(crate) fn anchor(&mut self, now: u64) {
83        if let Some(age) = self.pending_age.take() {
84            self.at = Some(i128::from(now) - i128::from(age));
85        }
86    }
87
88    pub(crate) fn value(&self, now: u64) -> u64 {
89        match (self.at, self.pending_age) {
90            (Some(at), _) => decayed(self.peak, age_at(now, at), self.hold, self.decay),
91            (None, Some(age)) => decayed(self.peak, age, self.hold, self.decay),
92            (None, None) => 0,
93        }
94    }
95
96    /// Sample-driven: a sample at least as large as the current decayed
97    /// value replaces the peak (so the memory rises immediately).
98    pub(crate) fn observe(&mut self, now: u64, v: u64) {
99        self.anchor(now);
100        if self.at.is_none() || v >= self.value(now) {
101            self.peak = v;
102            self.at = Some(i128::from(now));
103        }
104    }
105
106    pub(crate) fn snapshot(&self, now: u64) -> StallMemorySnapshot {
107        match (self.at, self.pending_age) {
108            (Some(at), _) => StallMemorySnapshot::new(self.peak, age_at(now, at)),
109            (None, Some(age)) => StallMemorySnapshot::new(self.peak, age),
110            (None, None) => StallMemorySnapshot::default(),
111        }
112    }
113
114    pub(crate) fn restore(&mut self, s: StallMemorySnapshot) {
115        self.peak = s.peak_us;
116        self.at = None;
117        self.pending_age = Some(s.age_us);
118    }
119
120    pub(crate) fn clear(&mut self) {
121        self.peak = 0;
122        self.at = None;
123        self.pending_age = None;
124    }
125}