futures_signals/
future.rsuse std::pin::Pin;
use std::sync::{Arc, Weak, Mutex};
use std::future::Future;
use std::task::{Poll, Waker, Context};
use std::sync::atomic::{AtomicBool, Ordering};
use discard::{Discard, DiscardOnDrop};
use pin_project::pin_project;
#[derive(Debug)]
struct CancelableFutureState {
is_cancelled: AtomicBool,
waker: Mutex<Option<Waker>>,
}
#[derive(Debug)]
pub struct CancelableFutureHandle {
state: Weak<CancelableFutureState>,
}
impl Discard for CancelableFutureHandle {
fn discard(self) {
if let Some(state) = self.state.upgrade() {
let mut lock = state.waker.lock().unwrap();
state.is_cancelled.store(true, Ordering::SeqCst);
if let Some(waker) = lock.take() {
drop(lock);
waker.wake();
}
}
}
}
#[pin_project(project = CancelableFutureProj)]
#[derive(Debug)]
#[must_use = "Futures do nothing unless polled"]
pub struct CancelableFuture<A, B> {
state: Arc<CancelableFutureState>,
#[pin]
future: Option<A>,
when_cancelled: Option<B>,
}
impl<A, B> Future for CancelableFuture<A, B>
where A: Future,
B: FnOnce() -> A::Output {
type Output = A::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let CancelableFutureProj { state, mut future, when_cancelled } = self.project();
if state.is_cancelled.load(Ordering::SeqCst) {
future.set(None);
let callback = when_cancelled.take().unwrap();
Poll::Ready(callback())
} else {
match future.as_pin_mut().unwrap().poll(cx) {
Poll::Pending => {
*state.waker.lock().unwrap() = Some(cx.waker().clone());
Poll::Pending
},
a => a,
}
}
}
}
pub fn cancelable_future<A, B>(future: A, when_cancelled: B) -> (DiscardOnDrop<CancelableFutureHandle>, CancelableFuture<A, B>)
where A: Future,
B: FnOnce() -> A::Output {
let state = Arc::new(CancelableFutureState {
is_cancelled: AtomicBool::new(false),
waker: Mutex::new(None),
});
let cancel_handle = DiscardOnDrop::new(CancelableFutureHandle {
state: Arc::downgrade(&state),
});
let cancel_future = CancelableFuture {
state,
future: Some(future),
when_cancelled: Some(when_cancelled),
};
(cancel_handle, cancel_future)
}