use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use crate::global::Global;
pub(super) const NOTIFY_COALESCE_WINDOW: Duration = Duration::from_micros(100);
pub(super) struct Coalescer(AtomicU64);
const NEVER: u64 = 0;
impl Coalescer {
pub(super) const fn new() -> Self {
Self(AtomicU64::new(NEVER))
}
pub(super) fn should_notify(&self) -> bool {
let now = clock_us() + 1;
let previous = self.0.load(Ordering::Relaxed);
if previous != NEVER
&& now.saturating_sub(previous) < NOTIFY_COALESCE_WINDOW.as_micros() as u64
{
return false;
}
self.0.store(now, Ordering::Relaxed);
true
}
}
impl Default for Coalescer {
fn default() -> Self {
Self::new()
}
}
fn clock_us() -> u64 {
static BASE: Global<Instant> = Global::new();
let base = *BASE.get_or_init(Instant::now);
Instant::now().saturating_duration_since(base).as_micros() as u64
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_first_notification_is_always_emitted() {
let coalescer = Coalescer::new();
assert!(coalescer.should_notify());
}
#[test]
fn a_second_notification_inside_the_window_is_coalesced() {
let coalescer = Coalescer::new();
assert!(coalescer.should_notify());
assert!(!coalescer.should_notify());
}
#[test]
fn a_notification_after_the_window_is_emitted() {
let coalescer = Coalescer::new();
let _ = coalescer.should_notify();
std::thread::sleep(NOTIFY_COALESCE_WINDOW * 2);
assert!(coalescer.should_notify());
}
}