use std::{cell::RefCell, sync::Arc};
use tokio::sync::watch;
type Hold = (watch::Receiver<bool>, Arc<()>);
thread_local! {
static HOLD: RefCell<Option<Hold>> = const { RefCell::new(None) };
}
pub(crate) struct SlowDisk {
release: watch::Sender<bool>,
waiting: Arc<()>,
}
impl SlowDisk {
pub(crate) fn waiting(&self) -> usize {
Arc::strong_count(&self.waiting) - 2
}
pub(crate) fn release(&self) {
self.release.send_replace(true);
}
}
pub(crate) fn hold() -> SlowDisk {
let (release, held) = watch::channel(false);
let waiting = Arc::new(());
HOLD.with(|hold| *hold.borrow_mut() = Some((held, waiting.clone())));
SlowDisk { release, waiting }
}
pub(super) async fn wait() {
let held = HOLD.with(|hold| hold.borrow().clone());
if let Some((mut held, waiting)) = held {
let _ = held.wait_for(|released| *released).await;
drop(waiting);
}
}