use std::cmp::PartialEq;
use std::time::{Duration, Instant};
#[derive(Debug)]
struct Event<T> {
item: T,
time: Instant,
}
pub enum State<T> {
Ready(T),
Wait(Duration),
Empty,
}
pub struct Debouncer<T> {
delay: Duration,
events: Vec<Event<T>>,
}
impl<T: PartialEq + std::fmt::Debug> Debouncer<T> {
pub fn new(delay: Duration) -> Debouncer<T> {
Debouncer {
delay,
events: vec![],
}
}
pub fn new_events<I: Iterator<Item = T>>(&mut self, mut items: I) {
let time = Instant::now();
let cutoff = time - self.delay;
while let Some(item) = items.next() {
self.events.retain(|e| e.time < cutoff || e.item != item);
self.events.push(Event { item, time });
}
}
pub fn get(&mut self) -> State<T> {
let time = Instant::now();
let cutoff = time - self.delay;
match self.events.get(0) {
None => State::Empty,
Some(e) if e.time > cutoff => State::Wait(e.time - cutoff),
Some(_) => State::Ready(self.events.remove(0).item),
}
}
}