use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Debug, Clone, Default)]
pub struct TickGuard {
running: Arc<AtomicBool>,
}
#[derive(Debug)]
#[must_use = "dropping the permit releases the guard immediately"]
pub struct TickPermit {
running: Arc<AtomicBool>,
}
impl Drop for TickPermit {
fn drop(&mut self) {
self.running.store(false, Ordering::Release);
}
}
impl TickGuard {
pub fn new() -> Self {
Self::default()
}
pub fn try_acquire(&self) -> Option<TickPermit> {
self.running
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.ok()
.map(|_| TickPermit {
running: self.running.clone(),
})
}
pub fn is_running(&self) -> bool {
self.running.load(Ordering::Acquire)
}
pub fn try_run(&self, f: impl FnOnce()) -> bool {
let Some(_permit) = self.try_acquire() else {
return false;
};
f();
true
}
pub async fn try_run_async<F: Future<Output = ()>>(&self, fut: F) -> bool {
let Some(_permit) = self.try_acquire() else {
return false;
};
fut.await;
true
}
}
#[cfg(test)]
mod tests {
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::time::Duration;
use super::*;
#[test]
fn skips_overlap() {
let g = TickGuard::new();
let inner = g.clone();
let ran_inner = std::cell::Cell::new(false);
assert!(g.try_run(|| {
assert!(inner.is_running());
ran_inner.set(inner.try_run(|| {}));
}));
assert!(!ran_inner.get());
assert!(!g.is_running());
assert!(g.try_run(|| {}));
}
#[test]
fn releases_on_panic() {
let g = TickGuard::new();
let r = catch_unwind(AssertUnwindSafe(|| g.try_run(|| panic!("boom"))));
assert!(r.is_err());
assert!(!g.is_running());
assert!(g.try_run(|| {}));
}
#[test]
fn permit() {
let g = TickGuard::new();
let p = g.try_acquire().unwrap();
assert!(g.try_acquire().is_none());
drop(p);
assert!(g.try_acquire().is_some());
}
#[tokio::test]
async fn async_overlap_and_cancel() {
let g = TickGuard::new();
let g2 = g.clone();
let long = tokio::spawn(async move { g2.try_run_async(tokio::time::sleep(Duration::from_millis(200))).await });
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(!g.try_run_async(async {}).await);
long.abort();
let _ = long.await;
assert!(!g.is_running());
assert!(g.try_run_async(async {}).await);
}
}