use crate::config::Micros;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct StallMemorySnapshot {
pub peak_us: Micros,
pub age_us: Micros,
}
impl StallMemorySnapshot {
#[must_use]
pub const fn new(peak_us: Micros, age_us: Micros) -> Self {
Self { peak_us, age_us }
}
#[must_use]
pub const fn aged(self, elapsed_us: Micros) -> Self {
Self {
peak_us: self.peak_us,
age_us: self.age_us.saturating_add(elapsed_us),
}
}
}
pub(crate) fn decayed(peak: u64, age: u64, hold: u64, decay: u64) -> u64 {
if age <= hold {
return peak;
}
let into = age - hold;
if into >= decay {
return 0;
}
let v = u128::from(peak) * u128::from(decay - into) / u128::from(decay.max(1));
u64::try_from(v).unwrap_or(u64::MAX)
}
#[derive(Clone, Debug)]
pub(crate) struct MaxHold {
peak: u64,
at: Option<u64>,
pending_age: Option<u64>,
hold: u64,
decay: u64,
}
impl MaxHold {
pub(crate) fn new(hold: u64, decay: u64) -> Self {
Self {
peak: 0,
at: None,
pending_age: None,
hold,
decay,
}
}
pub(crate) fn anchor(&mut self, now: u64) {
if let Some(age) = self.pending_age.take() {
self.at = Some(now.saturating_sub(age));
}
}
pub(crate) fn value(&self, now: u64) -> u64 {
match (self.at, self.pending_age) {
(Some(at), _) => decayed(self.peak, now.saturating_sub(at), self.hold, self.decay),
(None, Some(age)) => decayed(self.peak, age, self.hold, self.decay),
(None, None) => 0,
}
}
pub(crate) fn observe(&mut self, now: u64, v: u64) {
self.anchor(now);
if self.at.is_none() || v >= self.value(now) {
self.peak = v;
self.at = Some(now);
}
}
pub(crate) fn snapshot(&self, now: u64) -> StallMemorySnapshot {
match (self.at, self.pending_age) {
(Some(at), _) => StallMemorySnapshot::new(self.peak, now.saturating_sub(at)),
(None, Some(age)) => StallMemorySnapshot::new(self.peak, age),
(None, None) => StallMemorySnapshot::default(),
}
}
pub(crate) fn restore(&mut self, s: StallMemorySnapshot) {
self.peak = s.peak_us;
self.at = None;
self.pending_age = Some(s.age_us);
}
pub(crate) fn clear(&mut self) {
self.peak = 0;
self.at = None;
self.pending_age = None;
}
}