buffering_runtime/
stall_memory.rs1use core::time::Duration;
4
5use crate::time::{duration_add, instant_micros, micros_as_duration};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[non_exhaustive]
19pub struct StallMemorySnapshot {
20 pub peak: Duration,
22 pub age: Duration,
24}
25
26impl StallMemorySnapshot {
27 #[must_use]
32 pub const fn new(peak: Duration, age: Duration) -> Self {
33 Self { peak, age }
34 }
35
36 #[must_use]
39 pub fn aged(self, elapsed: Duration) -> Self {
40 Self {
41 peak: self.peak,
42 age: duration_add(self.age, elapsed),
43 }
44 }
45}
46
47pub(crate) fn decayed(peak: u64, age: u64, hold: u64, decay: u64) -> u64 {
49 if age <= hold {
50 return peak;
51 }
52 let into = age - hold;
53 if into >= decay {
54 return 0;
55 }
56 let v = u128::from(peak) * u128::from(decay - into) / u128::from(decay.max(1));
57 u64::try_from(v).unwrap_or(u64::MAX)
58}
59
60fn age_at(now: u64, at: i128) -> u64 {
61 u64::try_from((i128::from(now) - at).max(0)).unwrap_or(u64::MAX)
62}
63
64#[derive(Clone, Debug)]
65pub(crate) struct MaxHold {
66 peak: u64,
67 at: Option<i128>,
68 pending_age: Option<u64>,
69 hold: u64,
70 decay: u64,
71}
72
73impl MaxHold {
74 pub(crate) fn new(hold: u64, decay: u64) -> Self {
75 Self {
76 peak: 0,
77 at: None,
78 pending_age: None,
79 hold,
80 decay,
81 }
82 }
83
84 pub(crate) fn anchor(&mut self, now: u64) {
86 if let Some(age) = self.pending_age.take() {
87 self.at = Some(i128::from(now) - i128::from(age));
88 }
89 }
90
91 pub(crate) fn value(&self, now: u64) -> u64 {
92 match (self.at, self.pending_age) {
93 (Some(at), _) => decayed(self.peak, age_at(now, at), self.hold, self.decay),
94 (None, Some(age)) => decayed(self.peak, age, self.hold, self.decay),
95 (None, None) => 0,
96 }
97 }
98
99 pub(crate) fn observe(&mut self, now: u64, v: u64) {
102 self.anchor(now);
103 if self.at.is_none() || v >= self.value(now) {
104 self.peak = v;
105 self.at = Some(i128::from(now));
106 }
107 }
108
109 pub(crate) fn snapshot(&self, now: u64) -> StallMemorySnapshot {
110 match (self.at, self.pending_age) {
111 (Some(at), _) => StallMemorySnapshot::new(
112 micros_as_duration(self.peak),
113 micros_as_duration(age_at(now, at)),
114 ),
115 (None, Some(age)) => {
116 StallMemorySnapshot::new(micros_as_duration(self.peak), micros_as_duration(age))
117 }
118 (None, None) => StallMemorySnapshot::default(),
119 }
120 }
121
122 pub(crate) fn restore(&mut self, s: StallMemorySnapshot) {
123 self.peak = instant_micros(s.peak);
124 self.at = None;
125 self.pending_age = Some(instant_micros(s.age));
126 }
127
128 pub(crate) fn clear(&mut self) {
129 self.peak = 0;
130 self.at = None;
131 self.pending_age = None;
132 }
133}