use core::{hash::Hash, time::Duration};
use std::{
collections::{BTreeMap, HashMap},
time::Instant,
};
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct Slot {
at: Instant,
seq: u64,
}
#[derive(Debug)]
pub struct Debounce<K> {
quiet: Duration,
pending: HashMap<K, Slot>,
due: BTreeMap<Slot, K>,
next_seq: u64,
}
impl<K> Debounce<K> {
#[must_use]
pub fn new(quiet: Duration) -> Self {
Self {
quiet,
pending: HashMap::new(),
due: BTreeMap::new(),
next_seq: 0,
}
}
#[must_use]
pub const fn quiet(&self) -> Duration {
self.quiet
}
#[must_use]
pub fn len(&self) -> usize {
self.pending.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.pending.is_empty()
}
#[must_use]
pub fn deadline(&self) -> Option<Instant> {
self.due.first_key_value().map(|(slot, _)| slot.at)
}
}
impl<K: Hash + Eq> Debounce<K> {
#[must_use = "the ripe keys are removed from the pending set — dropping them drops the intake"]
pub fn ripe(&mut self, now: Instant) -> Vec<K> {
let mut ripe = Vec::new();
while let Some(head) = self.due.first_entry() {
if head.key().at > now {
break;
}
let key = head.remove();
self.pending.remove(&key);
ripe.push(key);
}
ripe
}
pub fn cancel(&mut self, key: &K) -> bool {
match self.pending.remove(key) {
Some(slot) => {
self.due.remove(&slot);
true
}
None => false,
}
}
}
impl<K: Hash + Eq + Clone> Debounce<K> {
pub fn touch(&mut self, key: K, now: Instant) {
let slot = Slot {
at: now.checked_add(self.quiet).unwrap_or(now),
seq: self.next_seq,
};
self.next_seq += 1;
if let Some(superseded) = self.pending.insert(key.clone(), slot) {
self.due.remove(&superseded);
}
self.due.insert(slot, key);
}
}