//! A fixed-length FIFO that models the transport delay of a sensor bus. use std::collections::VecDeque; /// A FIFO of `steps` samples. /// /// The queue starts filled with `initial`, so the first `steps` calls to /// [`Delay::push`] report that value while the queue drains. #[derive(Debug, Clone, PartialEq)] pub struct Delay { initial: T, queue: VecDeque, } impl Delay { /// A delay of `steps` samples, reporting `initial` until the queue fills. pub fn new(steps: usize, initial: T) -> Self { Self { initial: initial.clone(), queue: core::iter::repeat_n(initial, steps).collect(), } } /// Pushes a new sample and returns the one measured `steps` samples ago, or the /// new sample itself when the delay is zero. pub fn push(&mut self, value: T) -> T { if self.queue.is_empty() { return value; } self.queue.push_back(value); self.queue .pop_front() .unwrap_or_else(|| self.initial.clone()) } }