use futures::future::{FusedFuture, OptionFuture};
use futures_intrusive::channel::{shared::StateReceiveFuture, StateId};
use pin_project::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use crate::waker;
use crate::Canceled;
#[must_use = "futures do nothing unless polled"]
#[pin_project]
pub struct Cancellation {
#[pin]
inner: OptionFuture<StateReceiveFuture<parking_lot::RawMutex, bool>>,
state_id: StateId,
}
impl Cancellation {
pub(crate) fn none() -> Self {
Self {
inner: None.into(),
state_id: StateId::new(),
}
}
}
impl Future for Cancellation {
type Output = Option<Canceled>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut this = self.project();
this.inner
.as_mut()
.set(waker::cancellation(cx, *this.state_id));
this.inner.as_mut().poll(cx).map(|v| match v {
Some(Some((state_id, true))) => {
*this.state_id = state_id;
Some(Canceled::Graceful)
}
Some(Some((_, false))) => unreachable!(),
Some(None) => Some(Canceled::Forced),
None => None,
})
}
}
impl FusedFuture for Cancellation {
fn is_terminated(&self) -> bool {
self.inner.is_terminated()
}
}
pub fn cancellation() -> Cancellation {
Cancellation::none()
}