Skip to main content

mlua_isle/
task.rs

1//! Task handle — a cancellable future for a single Lua operation.
2//!
3//! A [`Task`] is returned by [`Isle::spawn_eval`], [`Isle::spawn_call`],
4//! and [`Isle::spawn_exec`].
5//! It provides a [`CancelToken`] for interruption and a blocking
6//! [`wait`](Task::wait) method to collect the result.
7
8use crate::error::IsleError;
9use crate::hook::CancelToken;
10use std::sync::mpsc;
11
12/// Handle to a pending Lua operation whose result is a `T`.
13///
14/// `T` is the type the request converts its result to on the Lua
15/// thread (the `T` of [`Isle::eval`](crate::Isle::eval) and the other
16/// request methods).
17///
18/// The operation runs on the Lua thread.  The caller can:
19/// - [`wait`](Task::wait) for the result (blocking).
20/// - [`cancel`](Task::cancel) the operation.
21/// - [`try_recv`](Task::try_recv) to poll without blocking.
22///
23/// Dropping a `Task` before its result was received **cancels** the
24/// operation.  Call [`detach`](Task::detach) to let it run to completion
25/// without keeping the handle.
26#[must_use = "dropping a Task cancels the operation; use `.detach()` to let it run"]
27pub struct Task<T> {
28    rx: mpsc::Receiver<Result<T, IsleError>>,
29    cancel: CancelToken,
30    /// Result received or detached: dropping must not cancel.
31    released: std::cell::Cell<bool>,
32}
33
34impl<T> Task<T> {
35    pub(crate) fn new(rx: mpsc::Receiver<Result<T, IsleError>>, cancel: CancelToken) -> Self {
36        Self {
37            rx,
38            cancel,
39            released: std::cell::Cell::new(false),
40        }
41    }
42
43    /// Block until the result is available.
44    pub fn wait(self) -> Result<T, IsleError> {
45        let result = self.rx.recv();
46        self.released.set(true);
47        result.map_err(|_| IsleError::RecvFailed)?
48    }
49
50    /// Let the operation run to completion without this handle.
51    ///
52    /// The result is discarded.  The operation can still be cancelled
53    /// through a clone of its [`cancel_token`](Self::cancel_token).
54    pub fn detach(self) {
55        self.released.set(true);
56    }
57
58    /// Cancel the operation.
59    ///
60    /// This signals the Lua debug hook to interrupt execution.
61    /// The task will eventually return [`IsleError::Cancelled`].
62    pub fn cancel(&self) {
63        self.cancel.cancel();
64    }
65
66    /// Non-blocking poll for the result.
67    pub fn try_recv(&self) -> Option<Result<T, IsleError>> {
68        let result = self.rx.try_recv().ok();
69        if result.is_some() {
70            self.released.set(true);
71        }
72        result
73    }
74
75    /// Access the cancel token (e.g. to share with other code).
76    pub fn cancel_token(&self) -> &CancelToken {
77        &self.cancel
78    }
79}
80
81impl<T> Drop for Task<T> {
82    fn drop(&mut self) {
83        if !self.released.get() {
84            self.cancel.cancel();
85        }
86    }
87}