use std::{pin::Pin, sync::MutexGuard};
use event_listener::{Event, EventListener};
use tokio::sync::MutexGuard as AsyncMutexGuard;
pub type ConditionWaiter = Pin<Box<EventListener>>;
#[derive(Default)]
pub struct Condition {
event: Event,
}
impl Condition {
pub fn new() -> Condition {
Condition::default()
}
#[inline]
pub async fn wait<T>(&self, guard: AsyncMutexGuard<'_, T>) {
let listener = self.event.listen();
drop(guard);
listener.await;
}
#[inline]
pub fn waiter<T>(&self, guard: MutexGuard<'_, T>) -> ConditionWaiter {
let listener = self.event.listen();
drop(guard);
Box::pin(listener)
}
#[inline]
pub fn notify_one(&self) {
self.event.notify_additional_relaxed(1);
}
#[inline]
pub fn notify_all(&self) {
self.event.notify_additional_relaxed(usize::MAX);
}
}