buffering_runtime/
stall_memory.rs1use crate::config::Micros;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16#[non_exhaustive]
17pub struct StallMemorySnapshot {
18 pub peak_us: Micros,
20 pub age_us: Micros,
22}
23
24impl StallMemorySnapshot {
25 #[must_use]
30 pub const fn new(peak_us: Micros, age_us: Micros) -> Self {
31 Self { peak_us, age_us }
32 }
33
34 #[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
44pub(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 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 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}