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
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 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 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}