use crate::traits::GuardRecovery;
use std::pin::Pin;
use std::sync::{Arc, LazyLock, Mutex};
use std::task::{Context, Poll, Waker};
#[cfg(not(target_family = "wasm"))]
use std::sync::Condvar;
pub type ShutdownEventsLock = LazyLock<ShutdownEvents>;
pub static SHUTDOWN_EVENTS: ShutdownEventsLock =
LazyLock::new(|| ShutdownEvents {
dart_stopped: Event::new(),
#[cfg(not(target_family = "wasm"))]
rust_stopped: Event::new(),
});
pub struct ShutdownEvents {
pub dart_stopped: Event,
#[cfg(not(target_family = "wasm"))]
pub rust_stopped: Event,
}
pub fn dart_shutdown() -> impl Future<Output = ()> {
SHUTDOWN_EVENTS.dart_stopped.wait_async()
}
pub struct Event {
inner: Arc<Mutex<EventInner>>,
#[cfg(not(target_family = "wasm"))]
condvar: Condvar,
}
impl Event {
pub fn new() -> Self {
let inner = EventInner {
flag: false,
session: 0,
wakers: Vec::new(),
};
Event {
inner: Arc::new(Mutex::new(inner)),
#[cfg(not(target_family = "wasm"))]
condvar: Condvar::new(),
}
}
pub fn wait_async(&self) -> EventFuture {
let guard = self.inner.lock().recover();
EventFuture {
started_session: guard.session,
inner: self.inner.clone(),
}
}
}
#[cfg(not(target_family = "wasm"))]
impl Event {
pub fn set(&self) {
let mut guard = self.inner.lock().recover();
guard.flag = true; guard.session += 1;
self.condvar.notify_all();
for waker in guard.wakers.drain(..) {
waker.wake();
}
}
pub fn clear(&self) {
let mut guard = self.inner.lock().recover();
guard.flag = false; }
pub fn wait(&self) {
let mut guard = self.inner.lock().recover();
let started_session = guard.session;
loop {
if guard.flag || guard.session != started_session {
break;
}
guard = self.condvar.wait(guard).recover();
}
}
}
struct EventInner {
flag: bool, session: usize, wakers: Vec<Waker>, }
pub struct EventFuture {
started_session: usize,
inner: Arc<Mutex<EventInner>>, }
impl Future for EventFuture {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut guard = self.inner.lock().recover();
if guard.flag || guard.session != self.started_session {
Poll::Ready(())
} else {
let waker = cx.waker();
if !guard
.wakers
.iter()
.any(|existing_waker| existing_waker.will_wake(waker))
{
guard.wakers.push(waker.clone());
}
Poll::Pending
}
}
}