use std::collections::VecDeque;
#[derive(Debug, Clone)]
pub struct Sampler {
capacity: usize,
samples: VecDeque<f64>,
}
impl Sampler {
#[must_use]
pub fn new(capacity: usize) -> Self {
let capacity = capacity.max(1);
Self {
capacity,
samples: VecDeque::with_capacity(capacity),
}
}
pub fn push(&mut self, sample: f64) {
if self.samples.len() == self.capacity {
self.samples.pop_front();
}
self.samples.push_back(sample);
}
pub fn iter(&self) -> impl Iterator<Item = f64> + '_ {
self.samples.iter().copied()
}
#[must_use]
pub fn latest(&self) -> Option<f64> {
self.samples.back().copied()
}
#[must_use]
pub fn max(&self) -> Option<f64> {
self.samples
.iter()
.copied()
.fold(None, |acc, s| Some(acc.map_or(s, |a: f64| a.max(s))))
}
#[must_use]
pub fn len(&self) -> usize {
self.samples.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.samples.is_empty()
}
pub fn clear(&mut self) {
self.samples.clear();
}
}