|
| 1 | +// Take a look at the license at the top of the repository in the LICENSE file. |
| 2 | + |
| 3 | +use crate::cancellable::CancellableExtManual; |
| 4 | +use crate::cancellable::CancelledHandlerId; |
| 5 | +use crate::prelude::CancellableExt; |
| 6 | +use crate::Cancellable; |
| 7 | +use crate::IOErrorEnum; |
| 8 | +use pin_project_lite::pin_project; |
| 9 | +use std::fmt::Debug; |
| 10 | +use std::fmt::Display; |
| 11 | +use std::future::Future; |
| 12 | +use std::pin::Pin; |
| 13 | +use std::task::Context; |
| 14 | +use std::task::Poll; |
| 15 | + |
| 16 | +// rustdoc-stripper-ignore-next |
| 17 | +/// Indicator that the [`CancellableFuture`] was cancelled. |
| 18 | +pub struct Cancelled; |
| 19 | + |
| 20 | +pin_project! { |
| 21 | + // rustdoc-stripper-ignore-next |
| 22 | + /// A future which can be cancelled via [`Cancellable`]. |
| 23 | + /// |
| 24 | + /// # Examples |
| 25 | + /// |
| 26 | + /// ``` |
| 27 | + /// # use futures::FutureExt; |
| 28 | + /// # use gio::traits::CancellableExt; |
| 29 | + /// # use gio::CancellableFuture; |
| 30 | + /// let l = glib::MainLoop::new(None, false); |
| 31 | + /// let c = gio::Cancellable::new(); |
| 32 | + /// |
| 33 | + /// l.context().spawn_local(CancellableFuture::new(async { 42 }, c.clone()).map(|_| ())); |
| 34 | + /// c.cancel(); |
| 35 | + /// |
| 36 | + /// ``` |
| 37 | + pub struct CancellableFuture<F> { |
| 38 | + #[pin] |
| 39 | + future: F, |
| 40 | + |
| 41 | + #[pin] |
| 42 | + waker_handler_cb: Option<CancelledHandlerId>, |
| 43 | + |
| 44 | + cancellable: Cancellable, |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +impl<F> CancellableFuture<F> { |
| 49 | + // rustdoc-stripper-ignore-next |
| 50 | + /// Creates a new `CancellableFuture` using a [`Cancellable`]. |
| 51 | + /// |
| 52 | + /// When [`cancel`](CancellableExt::cancel) is called, the future will complete |
| 53 | + /// immediately without making any further progress. In such a case, an error |
| 54 | + /// will be returned by this future (i.e., [`Cancelled`]). |
| 55 | + pub fn new(future: F, cancellable: Cancellable) -> Self { |
| 56 | + Self { |
| 57 | + future, |
| 58 | + waker_handler_cb: None, |
| 59 | + cancellable, |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + // rustdoc-stripper-ignore-next |
| 64 | + /// Checks whether the future has been cancelled. |
| 65 | + /// |
| 66 | + /// This is a shortcut for `self.cancellable().is_cancelled()` |
| 67 | + /// |
| 68 | + /// Note that all this method indicates is whether [`cancel`](CancellableExt::cancel) |
| 69 | + /// was called. This means that it will return true even if: |
| 70 | + /// * `cancel` was called after the future had completed. |
| 71 | + /// * `cancel` was called while the future was being polled. |
| 72 | + #[inline] |
| 73 | + pub fn is_cancelled(&self) -> bool { |
| 74 | + self.cancellable.is_cancelled() |
| 75 | + } |
| 76 | + |
| 77 | + // rustdoc-stripper-ignore-next |
| 78 | + /// Returns the inner [`Cancellable`] associated during creation. |
| 79 | + #[inline] |
| 80 | + pub fn cancellable(&self) -> &Cancellable { |
| 81 | + &self.cancellable |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +impl<F> Future for CancellableFuture<F> |
| 86 | +where |
| 87 | + F: Future, |
| 88 | +{ |
| 89 | + type Output = Result<<F as Future>::Output, Cancelled>; |
| 90 | + |
| 91 | + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 92 | + if self.is_cancelled() { |
| 93 | + return Poll::Ready(Err(Cancelled)); |
| 94 | + } |
| 95 | + |
| 96 | + let mut this = self.as_mut().project(); |
| 97 | + |
| 98 | + match this.future.poll(cx) { |
| 99 | + Poll::Ready(out) => Poll::Ready(Ok(out)), |
| 100 | + |
| 101 | + Poll::Pending => { |
| 102 | + if let Some(prev_handler) = this.waker_handler_cb.take() { |
| 103 | + this.cancellable.disconnect_cancelled(prev_handler); |
| 104 | + } |
| 105 | + |
| 106 | + let canceller_handler_id = this.cancellable.connect_cancelled({ |
| 107 | + let w = cx.waker().clone(); |
| 108 | + move |_| w.wake() |
| 109 | + }); |
| 110 | + |
| 111 | + match canceller_handler_id { |
| 112 | + Some(canceller_handler_id) => { |
| 113 | + *this.waker_handler_cb = Some(canceller_handler_id); |
| 114 | + Poll::Pending |
| 115 | + } |
| 116 | + |
| 117 | + None => Poll::Ready(Err(Cancelled)), |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +impl From<Cancelled> for glib::Error { |
| 125 | + fn from(_: Cancelled) -> Self { |
| 126 | + glib::Error::new(IOErrorEnum::Cancelled, "Task cancelled") |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +impl std::error::Error for Cancelled {} |
| 131 | + |
| 132 | +impl Debug for Cancelled { |
| 133 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 134 | + write!(f, "Task cancelled") |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +impl Display for Cancelled { |
| 139 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 140 | + Debug::fmt(self, f) |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +#[cfg(test)] |
| 145 | +mod tests { |
| 146 | + use super::Cancellable; |
| 147 | + use super::CancellableExt; |
| 148 | + use super::CancellableFuture; |
| 149 | + use super::Cancelled; |
| 150 | + use futures_channel::oneshot; |
| 151 | + |
| 152 | + #[test] |
| 153 | + fn cancellable_future_ok() { |
| 154 | + let ctx = glib::MainContext::new(); |
| 155 | + let c = Cancellable::new(); |
| 156 | + let (tx, rx) = oneshot::channel(); |
| 157 | + |
| 158 | + { |
| 159 | + ctx.spawn_local(async { |
| 160 | + let cancellable_future = CancellableFuture::new(async { 42 }, c); |
| 161 | + assert!(!cancellable_future.is_cancelled()); |
| 162 | + |
| 163 | + let result = cancellable_future.await; |
| 164 | + assert!(matches!(result, Ok(42))); |
| 165 | + |
| 166 | + tx.send(()).unwrap(); |
| 167 | + }); |
| 168 | + } |
| 169 | + |
| 170 | + ctx.block_on(rx).unwrap() |
| 171 | + } |
| 172 | + |
| 173 | + #[test] |
| 174 | + fn cancellable_future_cancel() { |
| 175 | + let ctx = glib::MainContext::new(); |
| 176 | + let c = Cancellable::new(); |
| 177 | + let (tx, rx) = oneshot::channel(); |
| 178 | + |
| 179 | + { |
| 180 | + let c = c.clone(); |
| 181 | + ctx.spawn_local(async move { |
| 182 | + let cancellable_future = CancellableFuture::new(std::future::pending::<()>(), c); |
| 183 | + |
| 184 | + let result = cancellable_future.await; |
| 185 | + assert!(matches!(result, Err(Cancelled))); |
| 186 | + |
| 187 | + tx.send(()).unwrap(); |
| 188 | + }); |
| 189 | + } |
| 190 | + |
| 191 | + std::thread::spawn(move || c.cancel()).join().unwrap(); |
| 192 | + |
| 193 | + ctx.block_on(rx).unwrap(); |
| 194 | + } |
| 195 | +} |
0 commit comments